The easy to use and full featured Irc Bot everyone is talking about!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IRC.cs 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Net;
  9. using Combot.IRCServices.Messaging;
  10. using Combot.IRCServices.TCP;
  11. namespace Combot.IRCServices
  12. {
  13. public partial class IRC
  14. {
  15. public List<Channel> Channels = new List<Channel>();
  16. public Messages Message;
  17. public event Action ConnectEvent;
  18. public event Action DisconnectEvent;
  19. public event Action<TCPError> TCPErrorEvent;
  20. public string Nickname;
  21. public Dictionary<string, PrivilegeMode> PrivilegeMapping = new Dictionary<string, PrivilegeMode>() { { "+", PrivilegeMode.v }, { "%", PrivilegeMode.h }, { "@", PrivilegeMode.o }, { "&", PrivilegeMode.a }, { "~", PrivilegeMode.q } };
  22. private int MaxMessageLength;
  23. private int MessageSendDelay;
  24. private DateTime LastMessageSend;
  25. private int ReadTimeout;
  26. private int AllowedFailedReads;
  27. private Thread TCPReader;
  28. private event Action<string> TCPMessageEvent;
  29. private readonly TCPInterface _TCP;
  30. private readonly ReaderWriterLockSlim ChannelRWLock;
  31. public IRC(int maxMessageLength, int messageSendDelay = 0, int readTimeout = 5000, int allowedFailedReads = 0)
  32. {
  33. _TCP = new TCPInterface();
  34. Message = new Messages(this);
  35. Nickname = string.Empty;
  36. ChannelRWLock = new ReaderWriterLockSlim();
  37. LastMessageSend = DateTime.Now;
  38. MaxMessageLength = maxMessageLength;
  39. MessageSendDelay = messageSendDelay;
  40. ReadTimeout = readTimeout;
  41. AllowedFailedReads = allowedFailedReads;
  42. TCPMessageEvent += Message.ParseTCPMessage;
  43. _TCP.TCPConnectionEvent += HandleTCPConnection;
  44. _TCP.TCPErrorEvent += HandleTCPError;
  45. Message.ErrorMessageEvent += HandleErrorMessage;
  46. Message.PingEvent += HandlePing;
  47. Message.ServerReplyEvent += HandleReply;
  48. Message.ChannelModeChangeEvent += HandleChannelModeChange;
  49. Message.UserModeChangeEvent += HandleUserModeChange;
  50. Message.NickChangeEvent += HandleNickChange;
  51. Message.JoinChannelEvent += HandleJoin;
  52. Message.PartChannelEvent += HandlePart;
  53. Message.KickEvent += HandleKick;
  54. Message.QuitEvent += HandleQuit;
  55. }
  56. /// <summary>
  57. /// Starts a TCP connection to the specified host.
  58. /// </summary>
  59. /// <param name="IP">The IP address of the host.</param>
  60. /// <param name="port">The port for the tcp connection.</param>
  61. /// <param name="readTimeout">The timeout for read operations in milliseconds.</param>
  62. /// <param name="allowedFailedCount">Number of times a read can fail before disconnecting.</param>
  63. /// <returns></returns>
  64. public bool Connect(IPAddress IP, int port)
  65. {
  66. bool result = false;
  67. if (!_TCP.Connected)
  68. {
  69. result = _TCP.Connect(IP, port, ReadTimeout, AllowedFailedReads);
  70. if (result)
  71. {
  72. TCPReader = new Thread(ReadTCPMessages);
  73. TCPReader.IsBackground = true;
  74. TCPReader.Start();
  75. if (ConnectEvent != null)
  76. {
  77. ConnectEvent();
  78. }
  79. }
  80. }
  81. return result;
  82. }
  83. /// <summary>
  84. /// Disconencts from the active TCP connection.
  85. /// </summary>
  86. /// <returns></returns>
  87. public bool Disconnect()
  88. {
  89. bool result = false;
  90. if (_TCP.Connected)
  91. {
  92. _TCP.Disconnect();
  93. }
  94. ChannelRWLock.EnterWriteLock();
  95. Channels = new List<Channel>();
  96. ChannelRWLock.ExitWriteLock();
  97. if (DisconnectEvent != null)
  98. {
  99. DisconnectEvent();
  100. }
  101. return result;
  102. }
  103. /// <summary>
  104. /// Logs in the specified nick using their Username and Realname.
  105. /// </summary>
  106. /// <param name="serverName">The server's name.</param>
  107. /// <param name="nick">The nick information for the login.</param>
  108. public void Login(string serverName, Nick nick)
  109. {
  110. Nickname = nick.Nickname;
  111. SendNick(nick.Nickname);
  112. SendUser(nick.Username, nick.Host, serverName, nick.Realname);
  113. }
  114. /// <summary>
  115. /// Parses a given mode and parameter string to generate a channel mode list.
  116. /// </summary>
  117. /// <param name="modeString">The mode string that contains the mode info.</param>
  118. /// <param name="parameterString">The parameter string that is associated with the mode info.</param>
  119. /// <returns></returns>
  120. public List<ChannelModeInfo> ParseChannelModeString(string modeString, string parameterString)
  121. {
  122. string[] modeArgs = parameterString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  123. char[] modeInfo = modeString.ToCharArray();
  124. bool set = true;
  125. int argIndex = 0;
  126. List<ChannelModeInfo> modeInfos = new List<ChannelModeInfo>();
  127. foreach (char mode in modeInfo)
  128. {
  129. if (mode.Equals('-'))
  130. {
  131. set = false;
  132. }
  133. else if (mode.Equals('+'))
  134. {
  135. set = true;
  136. }
  137. else
  138. {
  139. ChannelModeInfo newMode = new ChannelModeInfo();
  140. newMode.Set = set;
  141. ChannelMode foundMode;
  142. bool validMode = Enum.TryParse(mode.ToString(), false, out foundMode);
  143. if (validMode)
  144. {
  145. newMode.Mode = foundMode;
  146. if (modeArgs.GetUpperBound(0) >= argIndex)
  147. {
  148. switch (newMode.Mode)
  149. {
  150. case ChannelMode.k:
  151. case ChannelMode.l:
  152. case ChannelMode.b:
  153. case ChannelMode.e:
  154. case ChannelMode.I:
  155. case ChannelMode.v:
  156. case ChannelMode.h:
  157. case ChannelMode.o:
  158. case ChannelMode.a:
  159. case ChannelMode.q:
  160. newMode.Parameter = modeArgs[argIndex];
  161. argIndex++;
  162. break;
  163. default:
  164. newMode.Parameter = string.Empty;
  165. break;
  166. }
  167. }
  168. else
  169. {
  170. newMode.Parameter = string.Empty;
  171. }
  172. modeInfos.Add(newMode);
  173. }
  174. }
  175. }
  176. return modeInfos;
  177. }
  178. private void ReadTCPMessages()
  179. {
  180. while (_TCP.Connected)
  181. {
  182. string response = ReadTCPMessage();
  183. if (TCPMessageEvent != null && response != null && response != string.Empty)
  184. {
  185. TCPMessageEvent(response);
  186. }
  187. Thread.Sleep(10);
  188. }
  189. }
  190. private string ReadTCPMessage()
  191. {
  192. if (_TCP.Connected)
  193. {
  194. return _TCP.Read();
  195. }
  196. return null;
  197. }
  198. private void SendTCPMessage(string message)
  199. {
  200. if (_TCP.Connected)
  201. {
  202. string replaceWith = string.Empty;
  203. string parsedMessage = message.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
  204. _TCP.Write(parsedMessage);
  205. }
  206. }
  207. private void HandleTCPConnection(int e)
  208. {
  209. if (DisconnectEvent != null)
  210. {
  211. DisconnectEvent();
  212. }
  213. }
  214. private void HandleTCPError(TCPError e)
  215. {
  216. if (TCPErrorEvent != null)
  217. {
  218. TCPErrorEvent(e);
  219. }
  220. }
  221. private void HandleErrorMessage(object sender, ErrorMessage e)
  222. {
  223. Disconnect();
  224. }
  225. /// <summary>
  226. /// Responds with PONG on a PING with the specified arguments.
  227. /// </summary>
  228. /// <param name="sender"></param>
  229. /// <param name="e"></param>
  230. private void HandlePing(object sender, PingInfo e)
  231. {
  232. SendPong(e.Message);
  233. }
  234. private void HandleReply(object sender, IReply e)
  235. {
  236. if (e.GetType() == typeof(ServerReplyMessage))
  237. {
  238. ServerReplyMessage msg = (ServerReplyMessage)e;
  239. switch (msg.ReplyCode)
  240. {
  241. // If we get a WHO response, we parse and add the nicks to the specified channel if they are not there already.
  242. case IRCReplyCode.RPL_WHOREPLY:
  243. ChannelRWLock.EnterWriteLock();
  244. string[] msgSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  245. string target = msgSplit[0];
  246. if (target.StartsWith("&") || target.StartsWith("#"))
  247. {
  248. if (msgSplit.GetUpperBound(0) >= 7)
  249. {
  250. string nickname = msgSplit[4];
  251. string realname = msgSplit[7];
  252. string username = msgSplit[1];
  253. string host = msgSplit[2];
  254. string modeString = msgSplit[5];
  255. Channel channel = Channels.Find(chan => chan.Name == target);
  256. if (channel != null)
  257. {
  258. Nick nick = channel.GetNick(nickname);
  259. bool nickFound = true;
  260. if (nick == null)
  261. {
  262. nickFound = false;
  263. nick = new Nick();
  264. }
  265. nick.Nickname = nickname;
  266. nick.Host = host;
  267. nick.Realname = realname;
  268. nick.Username = username;
  269. nick.Modes = new List<UserMode>();
  270. nick.Privileges = new List<PrivilegeMode>();
  271. char[] modeArr = modeString.ToCharArray();
  272. for (int i = 1; i <= modeArr.GetUpperBound(0); i++)
  273. {
  274. if (PrivilegeMapping.ContainsKey(modeArr[i].ToString()))
  275. {
  276. nick.Privileges.Add(PrivilegeMapping[modeArr[i].ToString()]);
  277. }
  278. else if (modeArr[i].ToString() == "*")
  279. {
  280. nick.Modes.Add(UserMode.o);
  281. }
  282. else
  283. {
  284. nick.Modes.Add((UserMode)Enum.Parse(typeof(UserMode), modeArr[i].ToString()));
  285. }
  286. }
  287. if (!nickFound)
  288. {
  289. channel.AddNick(nick);
  290. }
  291. }
  292. }
  293. }
  294. ChannelRWLock.ExitWriteLock();
  295. break;
  296. // On a topic reply, update the channel's topic
  297. case IRCReplyCode.RPL_TOPIC:
  298. ChannelRWLock.EnterWriteLock();
  299. string[] topicSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  300. string topicChan = topicSplit[0];
  301. Channel topicChannel = Channels.Find(chan => chan.Name == topicChan);
  302. if (topicChannel != null)
  303. {
  304. topicChannel.Topic = topicSplit[1].Remove(0, 1);
  305. }
  306. ChannelRWLock.ExitWriteLock();
  307. break;
  308. default:
  309. break;
  310. }
  311. }
  312. else
  313. {
  314. ServerErrorMessage msg = (ServerErrorMessage)e;
  315. }
  316. }
  317. /// <summary>
  318. /// Update a channel's mode.
  319. /// </summary>
  320. /// <param name="sender"></param>
  321. /// <param name="e"></param>
  322. private void HandleChannelModeChange(object sender, ChannelModeChangeInfo e)
  323. {
  324. ChannelRWLock.EnterWriteLock();
  325. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  326. if (channel != null)
  327. {
  328. foreach (ChannelModeInfo mode in e.Modes)
  329. {
  330. switch (mode.Mode)
  331. {
  332. case ChannelMode.v:
  333. case ChannelMode.h:
  334. case ChannelMode.o:
  335. case ChannelMode.a:
  336. case ChannelMode.q:
  337. Nick changedNick = channel.GetNick(mode.Parameter);
  338. if (mode.Set)
  339. {
  340. changedNick.AddPrivilege((PrivilegeMode)Enum.Parse(typeof(PrivilegeMode), mode.Mode.ToString()));
  341. }
  342. else
  343. {
  344. changedNick.RemovePrivilege((PrivilegeMode)Enum.Parse(typeof(PrivilegeMode), mode.Mode.ToString()));
  345. }
  346. break;
  347. case ChannelMode.b:
  348. if (mode.Set)
  349. {
  350. channel.AddBan(mode.Parameter);
  351. }
  352. else
  353. {
  354. channel.RemoveBan(mode.Parameter);
  355. }
  356. break;
  357. case ChannelMode.k:
  358. if (mode.Set)
  359. {
  360. channel.AddMode(mode.Mode);
  361. channel.Key = mode.Parameter;
  362. }
  363. else
  364. {
  365. channel.RemoveMode(mode.Mode);
  366. channel.Key = string.Empty;
  367. }
  368. break;
  369. default:
  370. if (mode.Set)
  371. {
  372. channel.AddMode(mode.Mode);
  373. }
  374. else
  375. {
  376. channel.RemoveMode(mode.Mode);
  377. }
  378. break;
  379. }
  380. }
  381. SendWho(channel.Name);
  382. }
  383. ChannelRWLock.ExitWriteLock();
  384. }
  385. /// <summary>
  386. /// Update a nick's mode.
  387. /// </summary>
  388. /// <param name="sender"></param>
  389. /// <param name="e"></param>
  390. private void HandleUserModeChange(object sender, UserModeChangeInfo e)
  391. {
  392. ChannelRWLock.EnterWriteLock();
  393. for (int i = 0; i < Channels.Count; i++)
  394. {
  395. Nick changedNick = Channels[i].GetNick(e.Nick.Nickname);
  396. if (changedNick != null)
  397. {
  398. foreach (UserModeInfo mode in e.Modes)
  399. {
  400. if (mode.Set)
  401. {
  402. changedNick.AddMode(mode.Mode);
  403. }
  404. else
  405. {
  406. changedNick.RemoveMode(mode.Mode);
  407. }
  408. }
  409. }
  410. }
  411. ChannelRWLock.ExitWriteLock();
  412. }
  413. /// <summary>
  414. /// Update a nick to use their new nickname.
  415. /// </summary>
  416. /// <param name="sender"></param>
  417. /// <param name="e"></param>
  418. private void HandleNickChange(object sender, NickChangeInfo e)
  419. {
  420. ChannelRWLock.EnterWriteLock();
  421. for (int i = 0; i < Channels.Count; i++)
  422. {
  423. Nick newNick = Channels[i].GetNick(e.OldNick.Nickname);
  424. if (newNick != null)
  425. {
  426. newNick.Nickname = e.NewNick.Nickname;
  427. }
  428. }
  429. ChannelRWLock.ExitWriteLock();
  430. }
  431. /// <summary>
  432. /// Add a nick to a channel on join.
  433. /// </summary>
  434. /// <param name="sender"></param>
  435. /// <param name="e"></param>
  436. private void HandleJoin(object sender, JoinChannelInfo e)
  437. {
  438. ChannelRWLock.EnterWriteLock();
  439. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  440. if (channel != null)
  441. {
  442. channel.AddNick(e.Nick);
  443. }
  444. else
  445. {
  446. Channel newChannel = new Channel();
  447. newChannel.Name = e.Channel;
  448. newChannel.Nicks.Add(e.Nick);
  449. Channels.Add(newChannel);
  450. SendWho(newChannel.Name);
  451. }
  452. ChannelRWLock.ExitWriteLock();
  453. }
  454. /// <summary>
  455. /// Remove a nick from a channel on part.
  456. /// </summary>
  457. /// <param name="sender"></param>
  458. /// <param name="e"></param>
  459. private void HandlePart(object sender, PartChannelInfo e)
  460. {
  461. ChannelRWLock.EnterWriteLock();
  462. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  463. if (channel != null)
  464. {
  465. if (e.Nick.Nickname == Nickname)
  466. {
  467. Channels.Remove(channel);
  468. }
  469. else
  470. {
  471. channel.RemoveNick(e.Nick.Nickname);
  472. }
  473. }
  474. ChannelRWLock.ExitWriteLock();
  475. }
  476. /// <summary>
  477. /// Remove a nick from a channel on kick.
  478. /// </summary>
  479. /// <param name="sender"></param>
  480. /// <param name="e"></param>
  481. private void HandleKick(object sender, KickInfo e)
  482. {
  483. ChannelRWLock.EnterWriteLock();
  484. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  485. if (channel != null)
  486. {
  487. if (e.KickedNick.Nickname == Nickname)
  488. {
  489. Channels.Remove(channel);
  490. }
  491. else
  492. {
  493. channel.RemoveNick(e.KickedNick.Nickname);
  494. }
  495. }
  496. ChannelRWLock.ExitWriteLock();
  497. }
  498. /// <summary>
  499. /// Remove a nick from all channels on quit.
  500. /// </summary>
  501. /// <param name="sender"></param>
  502. /// <param name="e"></param>
  503. private void HandleQuit(object sender, QuitInfo e)
  504. {
  505. ChannelRWLock.EnterWriteLock();
  506. for (int i = 0; i < Channels.Count; i++)
  507. {
  508. Channels[i].RemoveNick(e.Nick.Nickname);
  509. }
  510. ChannelRWLock.ExitWriteLock();
  511. }
  512. }
  513. }