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

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