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

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