Initial commit

This commit is contained in:
Drew DeVault 2013-04-09 15:19:48 -06:00
commit 6402797b96
16 changed files with 590 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
_ReSharper*
bin/
obj/
*.suo

42
ChatSharp.sln Normal file
View File

@ -0,0 +1,42 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatSharp", "ChatSharp\ChatSharp.csproj", "{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestChatSharp", "TestChatSharp\TestChatSharp.csproj", "{BCCCE45F-32D5-4A04-B526-7D5A5673895F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|x86.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Any CPU.Build.0 = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|x86.ActiveCfg = Release|Any CPU
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Debug|Any CPU.ActiveCfg = Debug|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Debug|Mixed Platforms.Build.0 = Debug|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Debug|x86.ActiveCfg = Debug|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Debug|x86.Build.0 = Debug|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Release|Any CPU.ActiveCfg = Release|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Release|Mixed Platforms.ActiveCfg = Release|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Release|Mixed Platforms.Build.0 = Release|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Release|x86.ActiveCfg = Release|x86
{BCCCE45F-32D5-4A04-B526-7D5A5673895F}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ChatSharp</RootNamespace>
<AssemblyName>ChatSharp</AssemblyName>
<TargetFrameworkVersion>v4.0.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Events\RawMessageEventArgs.cs" />
<Compile Include="Events\SocketErrorEventArgs.cs" />
<Compile Include="Handlers\MessageHandlers.cs" />
<Compile Include="IrcClient.cs" />
<Compile Include="IrcMessage.cs" />
<Compile Include="IrcUser.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChatSharp.Events
{
public class RawMessageEventArgs : EventArgs
{
public string Message { get; set; }
public bool Outgoing { get; set; }
public RawMessageEventArgs(string message, bool outgoing)
{
Message = message;
Outgoing = outgoing;
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace ChatSharp.Events
{
public class SocketErrorEventArgs : EventArgs
{
public SocketError SocketError { get; set; }
public SocketErrorEventArgs(SocketError socketError)
{
SocketError = socketError;
}
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChatSharp.Handlers
{
internal static class MessageHandlers
{
public static void RegisterDefaultHandlers()
{
IrcClient.SetHandler("PING", MessageHandlers.HandlePing);
}
public static void HandlePing(IrcClient client, IrcMessage message)
{
Console.WriteLine("Pong");
client.SendMessage(message);
}
}
}

165
ChatSharp/IrcClient.cs Normal file
View File

@ -0,0 +1,165 @@
using System;
using System.Text;
using System.Collections.Generic;
using System.Net.Sockets;
using ChatSharp.Events;
using System.Timers;
namespace ChatSharp
{
public class IrcClient
{
static IrcClient()
{
Handlers = new Dictionary<string, MessageHandler>();
}
public delegate void MessageHandler(IrcClient client, IrcMessage message);
internal static Dictionary<string, MessageHandler> Handlers { get; set; }
public static void SetHandler(string message, MessageHandler handler)
{
message = message.ToUpper();
Handlers[message] = handler;
}
private const int ReadBufferLength = 1024;
private byte[] ReadBuffer { get; set; }
private int ReadBufferIndex { get; set; }
private string ServerHostname { get; set; }
private int ServerPort { get; set; }
private Timer PingTimer { get; set; }
public string ServerAddress
{
get
{
return ServerHostname + ":" + ServerPort;
}
internal set
{
string[] parts = value.Split(':');
if (parts.Length > 2 || parts.Length == 0)
throw new FormatException("Server address is not in correct format ('hostname:port')");
ServerHostname = parts[0];
if (parts.Length > 1)
ServerPort = int.Parse(parts[1]);
else
ServerPort = 6667;
}
}
public Socket Socket { get; set; }
public Encoding Encoding { get; set; }
public IrcUser User { get; set; }
public IrcClient(string serverAddress, IrcUser user)
{
if (serverAddress == null) throw new ArgumentNullException("serverAddress");
if (user == null) throw new ArgumentNullException("user");
User = user;
ServerAddress = serverAddress;
Encoding = Encoding.UTF8;
}
public void ConnectAsync()
{
if (Socket != null && Socket.Connected) throw new InvalidOperationException("Socket is already connected to server.");
Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ReadBuffer = new byte[ReadBufferLength];
ReadBufferIndex = 0;
Socket.BeginConnect(ServerHostname, ServerPort, ConnectComplete, null);
PingTimer = new Timer(30000);
}
private void ConnectComplete(IAsyncResult result)
{
Socket.EndConnect(result);
Socket.BeginReceive(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, SocketFlags.None, DataRecieved, null);
// Write login info
if (!string.IsNullOrEmpty(User.Password))
SendRawMessage("PASS {0}", User.Password);
SendRawMessage("NICK {0}", User.Nick);
SendRawMessage("USER {0} 0.0.0.0 server :{1}", User.User, User.RealName);
}
private void DataRecieved(IAsyncResult result)
{
SocketError error;
int length = Socket.EndReceive(result, out error);
if (error != SocketError.Success)
{
OnNetworkError(new SocketErrorEventArgs(error));
return;
}
ReadBufferIndex = 0;
while (length > 0)
{
int messageLength = Array.IndexOf(ReadBuffer, (byte)'\n', 0, length);
if (messageLength == -1) // Incomplete message
{
ReadBufferIndex = length;
break;
}
messageLength++;
var message = Encoding.GetString(ReadBuffer, 0, messageLength - 2); // -2 to remove \r\n
HandleMessage(message);
Array.Copy(ReadBuffer, messageLength, ReadBuffer, 0, length - messageLength);
length -= messageLength;
}
Socket.BeginReceive(ReadBuffer, ReadBufferIndex, ReadBuffer.Length - ReadBufferIndex, SocketFlags.None, DataRecieved, null);
}
private void HandleMessage(string rawMessage)
{
OnRawMessageRecieved(new RawMessageEventArgs(rawMessage, false));
var message = new IrcMessage(rawMessage);
if (Handlers.ContainsKey(message.Command.ToUpper()))
Handlers[message.Command.ToUpper()](this, message);
else
{
// TODO: Fire an event or something
}
}
public void SendRawMessage(string message, params object[] format)
{
message = string.Format(message, format);
var data = Encoding.GetBytes(message + "\r\n");
Socket.BeginSend(data, 0, data.Length, SocketFlags.None, MessageSent, message);
}
public void SendMessage(IrcMessage message)
{
SendRawMessage(message.RawMessage);
}
private void MessageSent(IAsyncResult result)
{
SocketError error;
Socket.EndSend(result, out error);
if (error != SocketError.Success)
OnNetworkError(new SocketErrorEventArgs(error));
else
OnRawMessageSent(new RawMessageEventArgs((string)result.AsyncState, true));
}
public event EventHandler<SocketErrorEventArgs> NetworkError;
protected internal virtual void OnNetworkError(SocketErrorEventArgs e)
{
if (NetworkError != null) NetworkError(this, e);
}
public event EventHandler<RawMessageEventArgs> RawMessageSent;
protected internal virtual void OnRawMessageSent(RawMessageEventArgs e)
{
if (RawMessageSent != null) RawMessageSent(this, e);
}
public event EventHandler<RawMessageEventArgs> RawMessageRecieved;
protected internal virtual void OnRawMessageRecieved(RawMessageEventArgs e)
{
if (RawMessageRecieved != null) RawMessageRecieved(this, e);
}
}
}

37
ChatSharp/IrcMessage.cs Normal file
View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ChatSharp
{
public class IrcMessage
{
/// <summary>
/// Parses a raw message string received from the server. See RFC 1459, 2.3.1 for details on raw message syntax.
/// </summary>
/// <param name="RawMessage"></param>
public IrcMessage(string RawMessage)
{
this.RawMessage = RawMessage;
var matches = Regex.Match(RawMessage,
@"(?::(?<Prefix>[^ ]+) +)?(?<Command>[^ :]+)" +
@"(?<payload>(?<middle>(?: +[^ :]+)*)(?<coda> +:(?<trailing>.*)?)?)");
Prefix = matches.Groups["Prefix"].Value;
Command = matches.Groups["Command"].Value;
Payload = matches.Groups["payload"].Value.Trim();
var parameters = new List<string>();
parameters.AddRange(matches.Groups["middle"].Value
.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries));
parameters.Add(matches.Groups["trailing"].Value);
Parameters = parameters.ToArray();
}
public string RawMessage, Prefix, Command, Payload;
public string[] Parameters;
}
}

49
ChatSharp/IrcUser.cs Normal file
View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChatSharp
{
public class IrcUser
{
public IrcUser(string host)
{
string[] mask = host.Split('@', '!');
Nick = mask[0];
User = mask[1];
Hostname = mask[2];
}
public IrcUser(string nick, string user)
{
Nick = nick;
User = user;
RealName = User;
}
public IrcUser(string nick, string user, string password) : this(nick, user)
{
Password = password;
}
public IrcUser(string nick, string user, string password, string realName) : this(nick, user, password)
{
RealName = realName;
}
public string Nick { get; internal set; }
public string User { get; internal set; }
public string Password { get; internal set; }
public string RealName { get; internal set; }
public string Hostname { get; internal set; }
public string Hostmask
{
get
{
return Nick + "!" + User + "@" + Hostname;
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ChatSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChatSharp")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("53b25724-8945-43a6-bcba-42b5dfa2c272")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

7
LICENSE Normal file
View File

@ -0,0 +1,7 @@
Copyright (c) 2013 Drew DeVault
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# ChatSharp
A C# library for IRC chat.

6
TestChatSharp/App.config Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0.1,Profile=Client" />
</startup>
</configuration>

21
TestChatSharp/Program.cs Normal file
View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChatSharp;
namespace TestChatSharp
{
class Program
{
static void Main(string[] args)
{
var client = new IrcClient("irc.freenode.net", new IrcUser("SirCmpwnBot", "SirCmpwnBot"));
client.NetworkError += (s, e) => Console.WriteLine("Error: " + e.SocketError);
client.RawMessageRecieved += (s, e) => Console.WriteLine("<< {0}", e.Message);
client.RawMessageSent += (s, e) => Console.WriteLine(">> {0}", e.Message);
client.ConnectAsync();
while (true) ;
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestChatSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestChatSharp")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4c6f3fb9-9e7b-4d83-bdc4-b810be5aa63f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BCCCE45F-32D5-4A04-B526-7D5A5673895F}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TestChatSharp</RootNamespace>
<AssemblyName>TestChatSharp</AssemblyName>
<TargetFrameworkVersion>v4.0.1</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ChatSharp\ChatSharp.csproj">
<Project>{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}</Project>
<Name>ChatSharp</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>