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 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. public List<UserModeInfo> ParseUserModeString(string modeString)
  179. {
  180. List<UserModeInfo> userModes = new List<UserModeInfo>();
  181. bool set = true;
  182. char[] modeArr = modeString.ToCharArray();
  183. for (int i = 1; i <= modeArr.GetUpperBound(0); i++)
  184. {
  185. UserModeInfo newMode = new UserModeInfo();
  186. if (modeArr[i].Equals('-'))
  187. {
  188. set = false;
  189. }
  190. else if (modeArr[i].Equals('+'))
  191. {
  192. set = true;
  193. }
  194. else if (modeArr[i].Equals('*'))
  195. {
  196. newMode.Mode = UserMode.o;
  197. newMode.Set = set;
  198. userModes.Add(newMode);
  199. }
  200. else
  201. {
  202. UserMode foundMode;
  203. bool validMode = Enum.TryParse(modeArr[i].ToString(), false, out foundMode);
  204. if (validMode)
  205. {
  206. newMode.Mode = foundMode;
  207. newMode.Set = set;
  208. userModes.Add(newMode);
  209. }
  210. }
  211. }
  212. return userModes;
  213. }
  214. private void ReadTCPMessages()
  215. {
  216. while (_TCP.Connected)
  217. {
  218. string response = ReadTCPMessage();
  219. if (TCPMessageEvent != null && response != null && response != string.Empty)
  220. {
  221. TCPMessageEvent(response);
  222. }
  223. Thread.Sleep(10);
  224. }
  225. }
  226. private string ReadTCPMessage()
  227. {
  228. if (_TCP.Connected)
  229. {
  230. return _TCP.Read();
  231. }
  232. return null;
  233. }
  234. private void SendTCPMessage(string message)
  235. {
  236. if (_TCP.Connected)
  237. {
  238. string replaceWith = string.Empty;
  239. string parsedMessage = message.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
  240. _TCP.Write(parsedMessage);
  241. }
  242. }
  243. private void HandleTCPConnection(int e)
  244. {
  245. if (DisconnectEvent != null)
  246. {
  247. DisconnectEvent();
  248. }
  249. }
  250. private void HandleTCPError(TCPError e)
  251. {
  252. if (TCPErrorEvent != null)
  253. {
  254. TCPErrorEvent(e);
  255. }
  256. }
  257. private void HandleErrorMessage(object sender, ErrorMessage e)
  258. {
  259. Disconnect();
  260. }
  261. /// <summary>
  262. /// Responds with PONG on a PING with the specified arguments.
  263. /// </summary>
  264. /// <param name="sender"></param>
  265. /// <param name="e"></param>
  266. private void HandlePing(object sender, PingInfo e)
  267. {
  268. SendPong(e.Message);
  269. }
  270. private void HandleReply(object sender, IReply e)
  271. {
  272. if (e.GetType() == typeof(ServerReplyMessage))
  273. {
  274. ServerReplyMessage msg = (ServerReplyMessage)e;
  275. switch (msg.ReplyCode)
  276. {
  277. // If we get a WHO response, we parse and add the nicks to the specified channel if they are not there already.
  278. case IRCReplyCode.RPL_WHOREPLY:
  279. ChannelRWLock.EnterWriteLock();
  280. string[] msgSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  281. string target = msgSplit[0];
  282. if (target.StartsWith("&") || target.StartsWith("#"))
  283. {
  284. if (msgSplit.GetUpperBound(0) >= 7)
  285. {
  286. string nickname = msgSplit[4];
  287. string realname = msgSplit[7];
  288. string username = msgSplit[1];
  289. string host = msgSplit[2];
  290. string modeString = msgSplit[5];
  291. Channel channel = Channels.Find(chan => chan.Name == target);
  292. if (channel != null)
  293. {
  294. Nick nick = channel.GetNick(nickname);
  295. bool nickFound = true;
  296. if (nick == null)
  297. {
  298. nickFound = false;
  299. nick = new Nick();
  300. }
  301. nick.Nickname = nickname;
  302. nick.Host = host;
  303. nick.Realname = realname;
  304. nick.Username = username;
  305. nick.Modes = new List<UserMode>();
  306. nick.Privileges = new List<PrivilegeMode>();
  307. char[] modeArr = modeString.ToCharArray();
  308. for (int i = 1; i <= modeArr.GetUpperBound(0); i++)
  309. {
  310. if (PrivilegeMapping.ContainsKey(modeArr[i].ToString()))
  311. {
  312. nick.Privileges.Add(PrivilegeMapping[modeArr[i].ToString()]);
  313. }
  314. else if (modeArr[i].ToString() == "*")
  315. {
  316. nick.Modes.Add(UserMode.o);
  317. }
  318. else
  319. {
  320. nick.Modes.Add((UserMode)Enum.Parse(typeof(UserMode), modeArr[i].ToString()));
  321. }
  322. }
  323. if (!nickFound)
  324. {
  325. channel.AddNick(nick);
  326. }
  327. }
  328. }
  329. }
  330. ChannelRWLock.ExitWriteLock();
  331. break;
  332. // On a topic reply, update the channel's topic
  333. case IRCReplyCode.RPL_TOPIC:
  334. ChannelRWLock.EnterWriteLock();
  335. string[] topicSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  336. string topicChan = topicSplit[0];
  337. Channel topicChannel = Channels.Find(chan => chan.Name == topicChan);
  338. if (topicChannel != null)
  339. {
  340. topicChannel.Topic = topicSplit[1].Remove(0, 1);
  341. }
  342. ChannelRWLock.ExitWriteLock();
  343. break;
  344. default:
  345. break;
  346. }
  347. }
  348. else
  349. {
  350. ServerErrorMessage msg = (ServerErrorMessage)e;
  351. }
  352. }
  353. /// <summary>
  354. /// Update a channel's mode.
  355. /// </summary>
  356. /// <param name="sender"></param>
  357. /// <param name="e"></param>
  358. private void HandleChannelModeChange(object sender, ChannelModeChangeInfo e)
  359. {
  360. ChannelRWLock.EnterWriteLock();
  361. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  362. if (channel != null)
  363. {
  364. foreach (ChannelModeInfo mode in e.Modes)
  365. {
  366. switch (mode.Mode)
  367. {
  368. case ChannelMode.v:
  369. case ChannelMode.h:
  370. case ChannelMode.o:
  371. case ChannelMode.a:
  372. case ChannelMode.q:
  373. Nick changedNick = channel.GetNick(mode.Parameter);
  374. if (mode.Set)
  375. {
  376. changedNick.AddPrivilege((PrivilegeMode)Enum.Parse(typeof(PrivilegeMode), mode.Mode.ToString()));
  377. }
  378. else
  379. {
  380. changedNick.RemovePrivilege((PrivilegeMode)Enum.Parse(typeof(PrivilegeMode), mode.Mode.ToString()));
  381. }
  382. break;
  383. case ChannelMode.b:
  384. if (mode.Set)
  385. {
  386. channel.AddBan(mode.Parameter);
  387. }
  388. else
  389. {
  390. channel.RemoveBan(mode.Parameter);
  391. }
  392. break;
  393. case ChannelMode.k:
  394. if (mode.Set)
  395. {
  396. channel.AddMode(mode.Mode);
  397. channel.Key = mode.Parameter;
  398. }
  399. else
  400. {
  401. channel.RemoveMode(mode.Mode);
  402. channel.Key = string.Empty;
  403. }
  404. break;
  405. default:
  406. if (mode.Set)
  407. {
  408. channel.AddMode(mode.Mode);
  409. }
  410. else
  411. {
  412. channel.RemoveMode(mode.Mode);
  413. }
  414. break;
  415. }
  416. }
  417. SendWho(channel.Name);
  418. }
  419. ChannelRWLock.ExitWriteLock();
  420. }
  421. /// <summary>
  422. /// Update a nick's mode.
  423. /// </summary>
  424. /// <param name="sender"></param>
  425. /// <param name="e"></param>
  426. private void HandleUserModeChange(object sender, UserModeChangeInfo e)
  427. {
  428. ChannelRWLock.EnterWriteLock();
  429. for (int i = 0; i < Channels.Count; i++)
  430. {
  431. Nick changedNick = Channels[i].GetNick(e.Nick.Nickname);
  432. if (changedNick != null)
  433. {
  434. foreach (UserModeInfo mode in e.Modes)
  435. {
  436. if (mode.Set)
  437. {
  438. changedNick.AddMode(mode.Mode);
  439. }
  440. else
  441. {
  442. changedNick.RemoveMode(mode.Mode);
  443. }
  444. }
  445. }
  446. }
  447. ChannelRWLock.ExitWriteLock();
  448. }
  449. /// <summary>
  450. /// Update a nick to use their new nickname.
  451. /// </summary>
  452. /// <param name="sender"></param>
  453. /// <param name="e"></param>
  454. private void HandleNickChange(object sender, NickChangeInfo e)
  455. {
  456. ChannelRWLock.EnterWriteLock();
  457. for (int i = 0; i < Channels.Count; i++)
  458. {
  459. Nick newNick = Channels[i].GetNick(e.OldNick.Nickname);
  460. if (newNick != null)
  461. {
  462. if (e.OldNick.Nickname == Nickname)
  463. {
  464. Nickname = e.NewNick.Nickname;
  465. }
  466. newNick.Nickname = e.NewNick.Nickname;
  467. }
  468. }
  469. ChannelRWLock.ExitWriteLock();
  470. }
  471. /// <summary>
  472. /// Add a nick to a channel on join.
  473. /// </summary>
  474. /// <param name="sender"></param>
  475. /// <param name="e"></param>
  476. private void HandleJoin(object sender, JoinChannelInfo e)
  477. {
  478. ChannelRWLock.EnterWriteLock();
  479. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  480. if (channel != null)
  481. {
  482. channel.AddNick(e.Nick);
  483. }
  484. else
  485. {
  486. Channel newChannel = new Channel();
  487. newChannel.Name = e.Channel;
  488. newChannel.Nicks.Add(e.Nick);
  489. Channels.Add(newChannel);
  490. SendWho(newChannel.Name);
  491. }
  492. ChannelRWLock.ExitWriteLock();
  493. }
  494. /// <summary>
  495. /// Remove a nick from a channel on part.
  496. /// </summary>
  497. /// <param name="sender"></param>
  498. /// <param name="e"></param>
  499. private void HandlePart(object sender, PartChannelInfo e)
  500. {
  501. ChannelRWLock.EnterWriteLock();
  502. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  503. if (channel != null)
  504. {
  505. if (e.Nick.Nickname == Nickname)
  506. {
  507. Channels.Remove(channel);
  508. }
  509. else
  510. {
  511. channel.RemoveNick(e.Nick.Nickname);
  512. }
  513. }
  514. ChannelRWLock.ExitWriteLock();
  515. }
  516. /// <summary>
  517. /// Remove a nick from a channel on kick.
  518. /// </summary>
  519. /// <param name="sender"></param>
  520. /// <param name="e"></param>
  521. private void HandleKick(object sender, KickInfo e)
  522. {
  523. ChannelRWLock.EnterWriteLock();
  524. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  525. if (channel != null)
  526. {
  527. if (e.KickedNick.Nickname == Nickname)
  528. {
  529. Channels.Remove(channel);
  530. }
  531. else
  532. {
  533. channel.RemoveNick(e.KickedNick.Nickname);
  534. }
  535. }
  536. ChannelRWLock.ExitWriteLock();
  537. }
  538. /// <summary>
  539. /// Remove a nick from all channels on quit.
  540. /// </summary>
  541. /// <param name="sender"></param>
  542. /// <param name="e"></param>
  543. private void HandleQuit(object sender, QuitInfo e)
  544. {
  545. ChannelRWLock.EnterWriteLock();
  546. for (int i = 0; i < Channels.Count; i++)
  547. {
  548. Channels[i].RemoveNick(e.Nick.Nickname);
  549. }
  550. ChannelRWLock.ExitWriteLock();
  551. }
  552. }
  553. }