The easy to use and full featured Irc Bot everyone is talking about!
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

IRC.cs 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. UserMode foundMode;
  321. bool valid = Enum.TryParse(modeArr[i].ToString(), false, out foundMode);
  322. if (valid)
  323. {
  324. nick.Modes.Add(foundMode);
  325. }
  326. }
  327. }
  328. if (!nickFound)
  329. {
  330. channel.AddNick(nick);
  331. }
  332. }
  333. }
  334. }
  335. ChannelRWLock.ExitWriteLock();
  336. break;
  337. // On a topic reply, update the channel's topic
  338. case IRCReplyCode.RPL_TOPIC:
  339. ChannelRWLock.EnterWriteLock();
  340. string[] topicSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  341. string topicChan = topicSplit[0];
  342. Channel topicChannel = Channels.Find(chan => chan.Name == topicChan);
  343. if (topicChannel != null)
  344. {
  345. topicChannel.Topic = topicSplit[1].Remove(0, 1);
  346. }
  347. ChannelRWLock.ExitWriteLock();
  348. break;
  349. default:
  350. break;
  351. }
  352. }
  353. else
  354. {
  355. ServerErrorMessage msg = (ServerErrorMessage)e;
  356. }
  357. }
  358. /// <summary>
  359. /// Update a channel's mode.
  360. /// </summary>
  361. /// <param name="sender"></param>
  362. /// <param name="e"></param>
  363. private void HandleChannelModeChange(object sender, ChannelModeChangeInfo e)
  364. {
  365. ChannelRWLock.EnterWriteLock();
  366. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  367. if (channel != null)
  368. {
  369. foreach (ChannelModeInfo mode in e.Modes)
  370. {
  371. switch (mode.Mode)
  372. {
  373. case ChannelMode.v:
  374. case ChannelMode.h:
  375. case ChannelMode.o:
  376. case ChannelMode.a:
  377. case ChannelMode.q:
  378. Nick changedNick = channel.GetNick(mode.Parameter);
  379. if (mode.Set)
  380. {
  381. changedNick.AddPrivilege((PrivilegeMode)Enum.Parse(typeof(PrivilegeMode), mode.Mode.ToString()));
  382. }
  383. else
  384. {
  385. changedNick.RemovePrivilege((PrivilegeMode)Enum.Parse(typeof(PrivilegeMode), mode.Mode.ToString()));
  386. }
  387. break;
  388. case ChannelMode.b:
  389. if (mode.Set)
  390. {
  391. channel.AddBan(mode.Parameter);
  392. }
  393. else
  394. {
  395. channel.RemoveBan(mode.Parameter);
  396. }
  397. break;
  398. case ChannelMode.k:
  399. if (mode.Set)
  400. {
  401. channel.AddMode(mode.Mode);
  402. channel.Key = mode.Parameter;
  403. }
  404. else
  405. {
  406. channel.RemoveMode(mode.Mode);
  407. channel.Key = string.Empty;
  408. }
  409. break;
  410. default:
  411. if (mode.Set)
  412. {
  413. channel.AddMode(mode.Mode);
  414. }
  415. else
  416. {
  417. channel.RemoveMode(mode.Mode);
  418. }
  419. break;
  420. }
  421. }
  422. SendWho(channel.Name);
  423. }
  424. ChannelRWLock.ExitWriteLock();
  425. }
  426. /// <summary>
  427. /// Update a nick's mode.
  428. /// </summary>
  429. /// <param name="sender"></param>
  430. /// <param name="e"></param>
  431. private void HandleUserModeChange(object sender, UserModeChangeInfo e)
  432. {
  433. ChannelRWLock.EnterWriteLock();
  434. for (int i = 0; i < Channels.Count; i++)
  435. {
  436. Nick changedNick = Channels[i].GetNick(e.Nick.Nickname);
  437. if (changedNick != null)
  438. {
  439. foreach (UserModeInfo mode in e.Modes)
  440. {
  441. if (mode.Set)
  442. {
  443. changedNick.AddMode(mode.Mode);
  444. }
  445. else
  446. {
  447. changedNick.RemoveMode(mode.Mode);
  448. }
  449. }
  450. }
  451. }
  452. ChannelRWLock.ExitWriteLock();
  453. }
  454. /// <summary>
  455. /// Update a nick to use their new nickname.
  456. /// </summary>
  457. /// <param name="sender"></param>
  458. /// <param name="e"></param>
  459. private void HandleNickChange(object sender, NickChangeInfo e)
  460. {
  461. ChannelRWLock.EnterWriteLock();
  462. for (int i = 0; i < Channels.Count; i++)
  463. {
  464. Nick newNick = Channels[i].GetNick(e.OldNick.Nickname);
  465. if (newNick != null)
  466. {
  467. if (e.OldNick.Nickname == Nickname)
  468. {
  469. Nickname = e.NewNick.Nickname;
  470. }
  471. newNick.Nickname = e.NewNick.Nickname;
  472. }
  473. }
  474. ChannelRWLock.ExitWriteLock();
  475. }
  476. /// <summary>
  477. /// Add a nick to a channel on join.
  478. /// </summary>
  479. /// <param name="sender"></param>
  480. /// <param name="e"></param>
  481. private void HandleJoin(object sender, JoinChannelInfo e)
  482. {
  483. ChannelRWLock.EnterWriteLock();
  484. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  485. if (channel != null)
  486. {
  487. channel.AddNick(e.Nick);
  488. }
  489. else
  490. {
  491. Channel newChannel = new Channel();
  492. newChannel.Name = e.Channel;
  493. newChannel.Nicks.Add(e.Nick);
  494. Channels.Add(newChannel);
  495. SendWho(newChannel.Name);
  496. }
  497. ChannelRWLock.ExitWriteLock();
  498. }
  499. /// <summary>
  500. /// Remove a nick from a channel on part.
  501. /// </summary>
  502. /// <param name="sender"></param>
  503. /// <param name="e"></param>
  504. private void HandlePart(object sender, PartChannelInfo e)
  505. {
  506. ChannelRWLock.EnterWriteLock();
  507. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  508. if (channel != null)
  509. {
  510. if (e.Nick.Nickname == Nickname)
  511. {
  512. Channels.Remove(channel);
  513. }
  514. else
  515. {
  516. channel.RemoveNick(e.Nick.Nickname);
  517. }
  518. }
  519. ChannelRWLock.ExitWriteLock();
  520. }
  521. /// <summary>
  522. /// Remove a nick from a channel on kick.
  523. /// </summary>
  524. /// <param name="sender"></param>
  525. /// <param name="e"></param>
  526. private void HandleKick(object sender, KickInfo e)
  527. {
  528. ChannelRWLock.EnterWriteLock();
  529. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  530. if (channel != null)
  531. {
  532. if (e.KickedNick.Nickname == Nickname)
  533. {
  534. Channels.Remove(channel);
  535. }
  536. else
  537. {
  538. channel.RemoveNick(e.KickedNick.Nickname);
  539. }
  540. }
  541. ChannelRWLock.ExitWriteLock();
  542. }
  543. /// <summary>
  544. /// Remove a nick from all channels on quit.
  545. /// </summary>
  546. /// <param name="sender"></param>
  547. /// <param name="e"></param>
  548. private void HandleQuit(object sender, QuitInfo e)
  549. {
  550. ChannelRWLock.EnterWriteLock();
  551. for (int i = 0; i < Channels.Count; i++)
  552. {
  553. Channels[i].RemoveNick(e.Nick.Nickname);
  554. }
  555. ChannelRWLock.ExitWriteLock();
  556. }
  557. }
  558. }