push.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. /**
  2. * ZNC Push Module
  3. *
  4. * Allows the user to enter a Push user and API token, and sends
  5. * channel highlights and personal messages to Push.
  6. *
  7. * Copyright (c) 2011 John Reese
  8. * Licensed under the MIT license
  9. */
  10. #define REQUIRESSL
  11. #ifndef PUSHVERSION
  12. #define PUSHVERSION "dev"
  13. #endif
  14. #include <znc/znc.h>
  15. #include <znc/Chan.h>
  16. #include <znc/User.h>
  17. #include <znc/IRCNetwork.h>
  18. #include <znc/Modules.h>
  19. #include <znc/FileUtils.h>
  20. #include <znc/Client.h>
  21. #include "time.h"
  22. #include <string.h>
  23. #ifdef USE_CURL
  24. #include <curl/curl.h>
  25. #endif // USE_CURL
  26. // Forward declaration
  27. class CPushMod;
  28. /**
  29. * Shorthand for encoding a string for a URL.
  30. *
  31. * @param str String to be encoded
  32. * @return Encoded string
  33. */
  34. CString urlencode(const CString& str)
  35. {
  36. return str.Escape_n(CString::EASCII, CString::EURL);
  37. }
  38. #ifndef USE_CURL
  39. /**
  40. * Socket class for generating HTTP requests.
  41. */
  42. class CPushSocket : public CSocket
  43. {
  44. public:
  45. CPushSocket(CModule *p) : CSocket(p)
  46. {
  47. EnableReadLine();
  48. parent = (CPushMod*) p;
  49. first = true;
  50. crlf = "\r\n";
  51. user_agent = "ZNC Push/" + CString(PUSHVERSION);
  52. }
  53. // Implemented after CPushMod
  54. void Request(bool post, const CString& host, const CString& url, MCString& parameters, const CString& auth="");
  55. virtual void ReadLine(const CString& data);
  56. virtual void Disconnected();
  57. private:
  58. CPushMod *parent;
  59. bool first;
  60. // Too lazy to add CString("\r\n\") everywhere
  61. CString crlf;
  62. // User agent to use
  63. CString user_agent;
  64. };
  65. #else
  66. // forward declaration
  67. long make_curl_request(const CString& service_host, const CString& service_url,
  68. const CString& service_auth, MCString& params, int port,
  69. bool use_ssl, bool use_post,
  70. const CString& proxy, bool proxy_ssl_verify,
  71. bool debug);
  72. #endif // USE_CURL
  73. /**
  74. * Push notification module.
  75. */
  76. class CPushMod : public CModule
  77. {
  78. protected:
  79. // Application name
  80. CString app;
  81. // Time last notification was sent for a given context
  82. std::map <CString, time_t> last_notification_time;
  83. // Time of last message by user to a given context
  84. std::map <CString, time_t> last_reply_time;
  85. // Time of last activity by user for a given context
  86. std::map <CString, time_t> last_active_time;
  87. // Time of last activity by user in any context
  88. time_t idle_time;
  89. // User object
  90. CUser *user;
  91. // Configuration options
  92. MCString options;
  93. MCString defaults;
  94. public:
  95. MODCONSTRUCTOR(CPushMod) {
  96. #ifdef USE_CURL
  97. curl_global_init(CURL_GLOBAL_DEFAULT);
  98. #endif
  99. app = "ZNC";
  100. idle_time = time(NULL);
  101. // Current user
  102. user = GetUser();
  103. // Push service information
  104. defaults["service"] = "igloo";
  105. defaults["username"] = "";
  106. defaults["secret"] = "";
  107. defaults["target"] = "";
  108. // Igloo Devices
  109. defaults["device1"] = "";
  110. defaults["device2"] = "";
  111. defaults["device3"] = "";
  112. defaults["device4"] = "";
  113. defaults["device5"] = "";
  114. // Notification settings
  115. defaults["message_content"] = "{context}: [{nick}] {message}";
  116. defaults["message_length"] = "100";
  117. defaults["message_title"] = "{title}";
  118. defaults["message_uri"] = "";
  119. defaults["message_uri_post"] = "no";
  120. defaults["message_uri_title"] = "";
  121. defaults["message_priority"] = "0";
  122. defaults["message_sound"] = "";
  123. defaults["message_escape"] = "";
  124. // Notification conditions
  125. defaults["away_only"] = "no";
  126. defaults["client_count_less_than"] = "0";
  127. defaults["highlight"] = "";
  128. defaults["idle"] = "0";
  129. defaults["last_active"] = "180";
  130. defaults["last_notification"] = "300";
  131. defaults["nick_blacklist"] = "";
  132. defaults["network_blacklist"] = "";
  133. defaults["replied"] = "yes";
  134. defaults["context"] = "*";
  135. // Proxy, for libcurl
  136. defaults["proxy"] = "";
  137. defaults["proxy_ssl_verify"] = "yes";
  138. // Advanced
  139. defaults["channel_conditions"] = "all";
  140. defaults["query_conditions"] = "all";
  141. defaults["debug"] = "off";
  142. }
  143. virtual ~CPushMod() {
  144. #ifdef USE_CURL
  145. curl_global_cleanup();
  146. #endif
  147. }
  148. public:
  149. /**
  150. * Debugging messages. Prints to *push when the debug option is enabled.
  151. *
  152. * @param data Debug message
  153. */
  154. void PutDebug(const CString& data)
  155. {
  156. if (options["debug"] == "on")
  157. {
  158. PutModule(data);
  159. }
  160. }
  161. protected:
  162. /**
  163. * Performs string expansion on a set of keywords.
  164. * Given an initial string and a dictionary of string replacments,
  165. * iterate over the dictionary, expanding keywords one-by-one.
  166. *
  167. * @param content String contents
  168. * @param replace Dictionary of string replacements
  169. * @return Result of string replacements
  170. */
  171. CString expand(const CString& content, MCString& replace)
  172. {
  173. CString result = content.c_str();
  174. for(MCString::iterator i = replace.begin(); i != replace.end(); i++)
  175. {
  176. result.Replace(i->first, i->second);
  177. }
  178. return result;
  179. }
  180. /**
  181. * Verifies whether a given string contains only numbers.
  182. *
  183. * @param content String to verify
  184. */
  185. bool is_number(const CString& content)
  186. {
  187. CString::const_iterator it = content.begin();
  188. while(it != content.end() && std::isdigit(*it)) ++it;
  189. return !content.empty() && it == content.end();
  190. }
  191. /**
  192. * Send a message to the currently-configured push service.
  193. * Requires (and assumes) that the user has already configured their
  194. * username and API secret using the 'set' command.
  195. *
  196. * @param message Message to be sent to the user
  197. * @param title Message title to use
  198. * @param context Channel or nick context
  199. */
  200. void send_message(const CString& message, const CString& title="New Message", const CString& context="*push", const CNick& nick=CString("*push"), const CString& type="")
  201. {
  202. // Set the last notification time
  203. last_notification_time[context] = time(NULL);
  204. // Shorten message if needed
  205. unsigned int message_length = options["message_length"].ToUInt();
  206. CString short_message = message;
  207. if (message_length > 0)
  208. {
  209. short_message = message.Ellipsize(message_length);
  210. }
  211. // Generate an ISO8601 date string
  212. time_t rawtime;
  213. struct tm * timeinfo;
  214. time(&rawtime);
  215. timeinfo = localtime(&rawtime);
  216. char iso8601 [20];
  217. strftime(iso8601, 20, "%Y-%m-%d %H:%M:%S", timeinfo);
  218. // Message string replacements
  219. MCString replace;
  220. replace["{context}"] = context;
  221. replace["{nick}"] = nick.GetNick();
  222. replace["{datetime}"] = CString(iso8601);
  223. replace["{unixtime}"] = CString(time(NULL));
  224. replace["{message}"] = short_message;
  225. replace["{title}"] = title;
  226. replace["{username}"] = options["username"];
  227. replace["{secret}"] = options["secret"];
  228. replace["{target}"] = options["target"];
  229. // network is special because it can be nullptr if the user has none set up yet
  230. CIRCNetwork* network = GetNetwork();
  231. if (network) {
  232. replace["{network}"] = network->GetName();
  233. } else {
  234. replace["{network}"] = "(No network)";
  235. }
  236. if (options["message_escape"] != "")
  237. {
  238. CString::EEscape esc = CString::ToEscape(options["message_escape"]);
  239. for (MCString::iterator i = replace.begin(); i != replace.end(); i++) {
  240. i->second = i->second.Escape(esc);
  241. }
  242. }
  243. CString message_uri = expand(options["message_uri"], replace);
  244. CString message_title = expand(options["message_title"], replace);
  245. CString message_content = expand(options["message_content"], replace);
  246. // Set up the connection profile
  247. CString service = options["service"];
  248. bool use_post = true;
  249. int use_port = 443;
  250. bool use_ssl = true;
  251. CString service_host;
  252. CString service_url;
  253. CString service_auth;
  254. MCString params;
  255. // Service-specific profiles
  256. if (service == "pushbullet")
  257. {
  258. if (options["secret"] == "")
  259. {
  260. PutModule("Error: secret (api key) not set");
  261. return;
  262. }
  263. service_host = "api.pushbullet.com";
  264. service_url = "/v2/pushes";
  265. // BASIC auth, base64-encoded APIKey:
  266. service_auth = options["secret"] + CString(":");
  267. if (options["target"] != "")
  268. {
  269. params["device_iden"] = options["target"];
  270. }
  271. if (message_uri == "")
  272. {
  273. params["type"] = "note";
  274. } else {
  275. params["type"] = "link";
  276. params["url"] = message_uri;
  277. }
  278. params["title"] = message_title;
  279. params["body"] = message_content;
  280. }
  281. else if (service == "boxcar")
  282. {
  283. if (options["username"] == "")
  284. {
  285. PutModule("Error: username not set");
  286. return;
  287. }
  288. CString boxcar_api_key = "puSd2qp2gCDZO7nWkvb9";
  289. CString boxcar_api_secret = "wLQQKSyGybIOkggbiKipefeYGLni9B3FPZabopHp";
  290. service_host = "boxcar.io";
  291. service_url = "/devices/providers/" + boxcar_api_key + "/notifications";
  292. params["email"] = options["username"];
  293. params["notification[from_screen_name]"] = context;
  294. params["notification[message]"] = message_content;
  295. params["notification[source_url]"] = message_uri;
  296. }
  297. else if (service == "boxcar2")
  298. {
  299. if (options["secret"] == "")
  300. {
  301. PutModule("Error: secret not set to apikey");
  302. return;
  303. }
  304. service_host = "new.boxcar.io";
  305. service_url = "/api/notifications";
  306. params["user_credentials"] = options["secret"];
  307. params["notification[title]"] = message_title;
  308. params["notification[long_message]"] = message_content;
  309. if ( options["message_sound"] != "" )
  310. {
  311. params["notification[sound]"] = options["message_sound"];
  312. }
  313. }
  314. else if (service == "nma")
  315. {
  316. if (options["secret"] == "")
  317. {
  318. PutModule("Error: secret not set");
  319. return;
  320. }
  321. if (options["message_priority"] != "")
  322. {
  323. params["priority"] = options["message_priority"];
  324. }
  325. service_host = "www.notifymyandroid.com";
  326. service_url = "/publicapi/notify";
  327. params["apikey"] = options["secret"];
  328. params["application"] = app;
  329. params["event"] = message_title;
  330. params["description"] = message_content;
  331. params["url"] = message_uri;
  332. }
  333. else if (service == "pushover")
  334. {
  335. if (options["username"] == "")
  336. {
  337. PutModule("Error: username (user key) not set");
  338. return;
  339. }
  340. if (options["secret"] == "")
  341. {
  342. PutModule("Error: secret (application token/key) not set");
  343. return;
  344. }
  345. service_host = "api.pushover.net";
  346. service_url = "/1/messages.json";
  347. params["token"] = options["secret"];
  348. params["user"] = options["username"];
  349. params["title"] = message_title;
  350. params["message"] = message_content;
  351. if (message_uri != "")
  352. {
  353. params["url"] = message_uri;
  354. }
  355. if ( options["message_uri_title"] != "" )
  356. {
  357. params["url_title"] = options["message_uri_title"];
  358. }
  359. if (options["target"] != "")
  360. {
  361. params["device"] = options["target"];
  362. }
  363. if ( options["message_sound"] != "" )
  364. {
  365. params["sound"] = options["message_sound"];
  366. }
  367. if (options["message_priority"] != "")
  368. {
  369. params["priority"] = options["message_priority"];
  370. }
  371. }
  372. else if (service == "pushsafer")
  373. {
  374. if (options["secret"] == "")
  375. {
  376. PutModule("Error: privatekey (private or alias key) not set");
  377. return;
  378. }
  379. service_host = "pushsafer.com";
  380. service_url = "/api";
  381. params["k"] = options["secret"];
  382. params["t"] = message_title;
  383. params["m"] = message_content;
  384. if (message_uri != "")
  385. {
  386. params["u"] = message_uri;
  387. }
  388. if (options["message_uri_title"] != "" )
  389. {
  390. params["ut"] = options["message_uri_title"];
  391. }
  392. if (options["target"] != "")
  393. {
  394. params["d"] = options["target"];
  395. }
  396. if (options["message_sound"] != "" )
  397. {
  398. params["s"] = options["message_sound"];
  399. }
  400. }
  401. else if (service == "pushalot")
  402. {
  403. if (options["secret"] == "")
  404. {
  405. PutModule("Error: secret (authorization token) not set");
  406. return;
  407. }
  408. service_host = "pushalot.com";
  409. service_url = "/api/sendmessage";
  410. params["AuthorizationToken"] = options["secret"];
  411. params["Title"] = message_title;
  412. params["Body"] = message_content;
  413. if (message_uri != "")
  414. {
  415. params["Link"] = message_uri;
  416. }
  417. if (options["message_uri_title"] != "" )
  418. {
  419. params["LinkTitle"] = options["message_uri_title"];
  420. }
  421. }
  422. else if (service == "prowl")
  423. {
  424. if (options["secret"] == "")
  425. {
  426. PutModule("Error: secret not set");
  427. return;
  428. }
  429. service_host = "api.prowlapp.com";
  430. service_url = "/publicapi/add";
  431. params["apikey"] = options["secret"];
  432. params["application"] = app;
  433. params["event"] = message_title;
  434. params["description"] = message_content;
  435. params["url"] = message_uri;
  436. }
  437. else if (service == "igloo")
  438. {
  439. if (options["device1"] == "" && options["device2"] == "" && options["device3"] == "" && options["device4"] == "" && options["device5"] == "")
  440. {
  441. PutModule("Error: no devices are set");
  442. return;
  443. }
  444. service_host = "api.iglooirc.com";
  445. service_url = "/znc/push";
  446. params["network"] = network->GetName();
  447. params["channel"] = context;
  448. params["message"] = message;
  449. params["nick"] = network->GetNick();
  450. params["sender"] = nick.GetNick();
  451. params["type"] = type;
  452. //params["developer"] = "true";
  453. params["device1"] = options["device1"];
  454. params["device2"] = options["device2"];
  455. params["device3"] = options["device3"];
  456. params["device4"] = options["device4"];
  457. params["device5"] = options["device5"];
  458. }
  459. else if (service == "supertoasty")
  460. {
  461. if (options["secret"] == "")
  462. {
  463. PutModule("Error: secret (device id) not set");
  464. return;
  465. }
  466. use_post = false;
  467. use_port = 80;
  468. use_ssl = false;
  469. service_host = "api.supertoasty.com";
  470. service_url = "/notify/"+options["secret"];
  471. params["title"] = message_title;
  472. params["text"] = message_content;
  473. params["image"] = "https://raw2.github.com/jreese/znc-push/master/logo.png";
  474. params["sender"] = "ZNC Push";
  475. }
  476. else if (service == "faast")
  477. {
  478. if (options["secret"] == "")
  479. {
  480. PutModule("Error: secret not set to apikey");
  481. return;
  482. }
  483. service_host = "www.appnotifications.com";
  484. service_url = "/account/notifications.json";
  485. params["user_credentials"] = options["secret"];
  486. params["notification[title]"] = message_title;
  487. params["notification[subtitle]"] = context;
  488. params["notification[message]"] = message_content;
  489. params["notification[long_message]"] = message_content;
  490. params["notification[icon_url]"] = "https://raw2.github.com/jreese/znc-push/master/logo.png";
  491. if ( options["message_sound"] != "" )
  492. {
  493. params["notification[sound]"] = options["message_sound"];
  494. }
  495. if ( options["message_uri"] != "" )
  496. {
  497. params["notification[run_command]"] = options["message_uri"];
  498. }
  499. }
  500. else if (service == "nexmo")
  501. {
  502. if (options["username"] == "")
  503. {
  504. PutModule("Error: username (api key) not set");
  505. return;
  506. }
  507. if (options["secret"] == "")
  508. {
  509. PutModule("Error: secret (api secret) not set");
  510. return;
  511. }
  512. if (options["target"] == "")
  513. {
  514. PutModule("Error: destination mobile number (in international format) not set");
  515. return;
  516. }
  517. service_host = "rest.nexmo.com";
  518. service_url = "/sms/json";
  519. params["api_secret"] = options["secret"];
  520. params["api_key"] = options["username"];
  521. params["from"] = message_title;
  522. params["to"] = options["target"];
  523. params["text"] = message_content;
  524. }
  525. else if (service == "url")
  526. {
  527. if (options["message_uri"] == "")
  528. {
  529. PutModule("Error: message_uri not set");
  530. return;
  531. }
  532. CString::size_type count;
  533. VCString parts;
  534. CString url = options["message_uri"];
  535. // Verify that the URL begins with either http:// or https://
  536. count = url.Split("://", parts, false);
  537. if (count != 2)
  538. {
  539. PutModule("Error: invalid url format");
  540. return;
  541. }
  542. if(options["message_uri_post"] != "yes")
  543. {
  544. use_post = false;
  545. }
  546. if (parts[0] == "https")
  547. {
  548. use_ssl = true;
  549. use_port = 443;
  550. }
  551. else if (parts[0] == "http")
  552. {
  553. use_ssl = false;
  554. use_port = 80;
  555. }
  556. else
  557. {
  558. PutModule("Error: invalid url schema");
  559. return;
  560. }
  561. // HTTP basic auth
  562. if(options["username"] != "" || options["secret"] != "")
  563. {
  564. service_auth = options["username"] + CString(":") + options["secret"];
  565. }
  566. // Process the remaining portion of the URL
  567. url = parts[1];
  568. // Split out the host and optional port number; this breaks with raw IPv6 addresses
  569. CString host = url.Token(0, false, "/");
  570. count = host.Split(":", parts, false);
  571. if (count > 1)
  572. {
  573. use_port = parts[1].ToInt();
  574. }
  575. service_host = parts[0];
  576. // Split remaining URL into path and query components
  577. url = "/" + url.Token(1, true, "/");
  578. service_url = expand(url.Token(0, false, "?"), replace);
  579. // Parse and expand query parameter values
  580. url = url.Token(1, true, "?");
  581. url.URLSplit(params);
  582. for (MCString::iterator i = params.begin(); i != params.end(); i++) {
  583. i->second = expand(i->second, replace);
  584. }
  585. }
  586. else if (service == "airgram")
  587. {
  588. PutModule("Error: Airgram service shut down. Please configure another notification provider.");
  589. }
  590. else if (service == "slack")
  591. {
  592. if (options["secret"] == "")
  593. {
  594. PutModule("Error: secret (from webhook, e.g. T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX) not set");
  595. return;
  596. }
  597. if (options["target"] == "")
  598. {
  599. PutModule("Error: target (channel or username) not set");
  600. return;
  601. }
  602. service_host = "hooks.slack.com";
  603. service_url = "/services/" + options["secret"];
  604. if (options["username"] != "")
  605. {
  606. params["username"] = options["username"];
  607. }
  608. params["payload"] = expand("{\"channel\": \"{target}\", \"text\": \"*{title}*: {message}\"}", replace);
  609. PutDebug("payload: " + params["payload"]);
  610. }
  611. else if (service == "discord")
  612. {
  613. if (options["secret"] == "")
  614. {
  615. PutModule("Error: secret (from webhook, e.g. 111111111111111111/abcdefghijklmopqrstuvwxyz1234567890-ABCDEFGHIJKLMNOPQRSTUVWXYZ123456) not set");
  616. return;
  617. }
  618. service_host = "discordapp.com";
  619. service_url = "/api/webhooks/" + options["secret"];
  620. if (options["username"] != "")
  621. {
  622. params["username"] = options["username"];
  623. }
  624. params["content"] = message_content;
  625. }
  626. else if (service == "pushjet")
  627. {
  628. if (options["secret"] == "")
  629. {
  630. PutModule("Error: secret (service key) not set");
  631. return;
  632. }
  633. service_host = "api.pushjet.io";
  634. service_url = "/message";
  635. params["secret"] = options["secret"];
  636. params["title"] = message_title;
  637. params["message"] = message_content;
  638. if (message_uri != "")
  639. {
  640. params["link"] = message_uri;
  641. }
  642. if (options["message_priority"] != "")
  643. {
  644. params["level"] = options["message_priority"];
  645. }
  646. }
  647. else if (service == "telegram")
  648. {
  649. if ((options["secret"] == "") || (options["target"] ==""))
  650. {
  651. PutModule("Error: secret (API key) or target (chat_id) not set");
  652. return;
  653. }
  654. service_host = "api.telegram.org";
  655. service_url = "/bot" + options["secret"] + "/sendMessage";
  656. params["chat_id"] = options["target"];
  657. params["text"] = message_content;
  658. if (options["message_escape"] == "HTML") {
  659. params["parse_mode"] = "HTML";
  660. }
  661. }
  662. else
  663. {
  664. PutModule("Error: service type not selected");
  665. return;
  666. }
  667. PutDebug("service: " + service);
  668. PutDebug("service_host: " + service_host);
  669. PutDebug("service_url: " + service_url);
  670. PutDebug("service_auth: " + service_auth);
  671. PutDebug("use_port: " + CString(use_port));
  672. PutDebug("use_ssl: " + CString(use_ssl ? 1 : 0));
  673. PutDebug("use_post: " + CString(use_post ? 1 : 0));
  674. #ifdef USE_CURL
  675. PutDebug("using libcurl");
  676. long http_code = make_curl_request(service_host, service_url, service_auth, params, use_port, use_ssl, use_post, options["proxy"], options["proxy_ssl_verify"] != "no", options["debug"] == "on");
  677. PutDebug("curl: HTTP status code " + CString(http_code));
  678. if (!(http_code >= 200 && http_code < 300)) {
  679. PutModule("Error: HTTP status code " + CString(http_code));
  680. }
  681. #else
  682. PutDebug("NOT using libcurl");
  683. // Create the socket connection, write to it, and add it to the queue
  684. CPushSocket *sock = new CPushSocket(this);
  685. sock->Connect(service_host, use_port, use_ssl);
  686. sock->Request(use_post, service_host, service_url, params, service_auth);
  687. AddSocket(sock);
  688. #endif
  689. }
  690. /**
  691. * Evaluate a boolean expression using condition values.
  692. * All tokens must be separated by spaces, using "and" and "or" for
  693. * boolean operators, "(" and ")" to enclose sub-expressions, and
  694. * condition option names to evaluate each condition.
  695. *
  696. * @param expression Boolean expression string
  697. * @param context Notification context
  698. * @param nick Sender nick
  699. * @param message Message contents
  700. * @return Result of boolean evaluation
  701. */
  702. bool eval(const CString& expression, const CString& context=CString(""), const CNick& nick=CNick(""), const CString& message=" ")
  703. {
  704. CString padded = expression.Replace_n("(", " ( ");
  705. padded.Replace(")", " ) ");
  706. VCString tokens;
  707. padded.Split(" ", tokens, false);
  708. PutDebug("Evaluating message: <" + nick.GetNick() + "> " + message);
  709. bool result = eval_tokens(tokens.begin(), tokens.end(), context, nick, message);
  710. return result;
  711. }
  712. #define expr(x, y) else if (token == x) { \
  713. bool result = y; \
  714. dbg += CString(x) + "/" + CString(result ? "true" : "false") + " "; \
  715. value = oper ? value && result : value || result; \
  716. }
  717. /**
  718. * Evaluate a tokenized boolean expression, or sub-expression.
  719. *
  720. * @param pos Token vector iterator current position
  721. * @param end Token vector iterator end position
  722. * @param context Notification context
  723. * @param nick Sender nick
  724. * @param message Message contents
  725. * @return Result of boolean expression
  726. */
  727. bool eval_tokens(VCString::iterator pos, VCString::iterator end, const CString& context, const CNick& nick, const CString& message)
  728. {
  729. bool oper = true;
  730. bool value = true;
  731. CString dbg = "";
  732. for(; pos != end; pos++)
  733. {
  734. CString token = pos->AsLower();
  735. if (token == "(")
  736. {
  737. // recursively evaluate sub-expressions
  738. bool inner = eval_tokens(++pos, end, context, nick, message);
  739. dbg += "( inner/" + CString(inner ? "true" : "false") + " ) ";
  740. value = oper ? value && inner : value || inner;
  741. // search ahead to the matching parenthesis token
  742. unsigned int parens = 1;
  743. while(pos != end)
  744. {
  745. if (*pos == "(")
  746. {
  747. parens++;
  748. }
  749. else if (*pos == ")")
  750. {
  751. parens--;
  752. }
  753. if (parens == 0)
  754. {
  755. break;
  756. }
  757. pos++;
  758. }
  759. }
  760. else if (token == ")")
  761. {
  762. pos++;
  763. PutDebug(dbg);
  764. return value;
  765. }
  766. else if (token == "and")
  767. {
  768. dbg += "and ";
  769. oper = true;
  770. }
  771. else if (token == "or")
  772. {
  773. dbg += "or ";
  774. oper = false;
  775. }
  776. expr("true", true)
  777. expr("false", false)
  778. expr("away_only", away_only())
  779. expr("client_count_less_than", client_count_less_than())
  780. expr("highlight", highlight(message))
  781. expr("idle", idle())
  782. expr("last_active", last_active(context))
  783. expr("last_notification", last_notification(context))
  784. expr("nick_blacklist", nick_blacklist(nick))
  785. expr("network_blacklist", network_blacklist())
  786. expr("replied", replied(context))
  787. expr("context", context_filter(context))
  788. else
  789. {
  790. PutModule("Error: Unexpected token \"" + token + "\"");
  791. }
  792. }
  793. PutDebug(dbg);
  794. return value;
  795. }
  796. #undef expr
  797. protected:
  798. /**
  799. * Check if the away status condition is met.
  800. *
  801. * @return True if away_only is not "yes" or away status is set
  802. */
  803. bool away_only()
  804. {
  805. CString value = options["away_only"].AsLower();
  806. return value != "yes" || GetNetwork()->IsIRCAway();
  807. }
  808. /**
  809. * Check how many clients are connected to ZNC.
  810. *
  811. * @return Number of connected clients
  812. */
  813. size_t client_count()
  814. {
  815. return GetNetwork()->GetClients().size();
  816. }
  817. /**
  818. * Check if the client_count condition is met.
  819. *
  820. * @return True if client_count is less than client_count_less_than or if client_count_less_than is zero
  821. */
  822. bool client_count_less_than()
  823. {
  824. unsigned int value = options["client_count_less_than"].ToUInt();
  825. return value == 0 || client_count() < value;
  826. }
  827. /**
  828. * Determine if the given message matches any highlight rules.
  829. *
  830. * @param message Message contents
  831. * @return True if message matches a highlight
  832. */
  833. bool highlight(const CString& message)
  834. {
  835. CString msg = " " + message.AsLower() + " ";
  836. VCString values;
  837. options["highlight"].Split(" ", values, false);
  838. values.push_back("%nick%");
  839. bool matched = false;
  840. bool negated = false;
  841. for (VCString::iterator i = values.begin(); i != values.end(); i++)
  842. {
  843. CString value = i->AsLower();
  844. char prefix = value[0];
  845. bool negate_match = false;
  846. if (prefix == '-')
  847. {
  848. negate_match = true;
  849. value.LeftChomp(1);
  850. }
  851. else if (prefix == '_')
  852. {
  853. value = " " + value.LeftChomp_n(1) + " ";
  854. }
  855. // Expand substrings like %nick%
  856. if (m_pNetwork)
  857. {
  858. value = m_pNetwork->ExpandString(value);
  859. }
  860. else
  861. {
  862. value = GetUser()->ExpandString(value);
  863. }
  864. value = "*" + value.AsLower() + "*";
  865. if (msg.WildCmp(value))
  866. {
  867. if (negate_match)
  868. {
  869. negated = true;
  870. }
  871. else
  872. {
  873. matched = true;
  874. }
  875. }
  876. }
  877. return (matched && !negated);
  878. }
  879. /**
  880. * Determine if the given context matches any context rules.
  881. *
  882. * @param context The context of a message
  883. * @return True if context matches the filter
  884. */
  885. bool context_filter(const CString& raw_context)
  886. {
  887. CString context = raw_context.AsLower();
  888. if (context == "all" || context == "*")
  889. return true;
  890. VCString values;
  891. options["context"].Split(" ", values, false);
  892. for (VCString::iterator i = values.begin(); i != values.end(); i++)
  893. {
  894. CString value = i->AsLower();
  895. char prefix = value[0];
  896. bool push = true;
  897. if (prefix == '-')
  898. {
  899. push = false;
  900. value.LeftChomp(1);
  901. }
  902. if (value != "*")
  903. {
  904. value = "*" + value.AsLower() + "*";
  905. }
  906. if (context.WildCmp(value))
  907. {
  908. return push;
  909. }
  910. }
  911. return false;
  912. }
  913. /**
  914. * Check if the idle condition is met.
  915. *
  916. * @return True if idle is less than or equal to zero or elapsed time is greater than idle
  917. */
  918. bool idle()
  919. {
  920. unsigned int value = options["idle"].ToUInt();
  921. time_t now = time(NULL);
  922. return value == 0 || difftime(now, idle_time) >= value;
  923. }
  924. /**
  925. * Check if the last_active condition is met.
  926. *
  927. * @param context Channel or nick context
  928. * @return True if last_active is less than or equal to zero or elapsed time is greater than last_active
  929. */
  930. bool last_active(const CString& context)
  931. {
  932. unsigned int value = options["last_active"].ToUInt();
  933. time_t now = time(NULL);
  934. return value == 0
  935. || last_active_time.count(context) < 1
  936. || difftime(now, last_active_time[context]) >= value;
  937. }
  938. /**
  939. * Check if the last_notification condition is met.
  940. *
  941. * @param context Channel or nick context
  942. * @return True if last_notification is less than or equal to zero or elapsed time is greater than last_nofication
  943. */
  944. bool last_notification(const CString& context)
  945. {
  946. unsigned int value = options["last_notification"].ToUInt();
  947. time_t now = time(NULL);
  948. return value == 0
  949. || last_notification_time.count(context) < 1
  950. || difftime(now, last_notification_time[context]) >= value;
  951. }
  952. /**
  953. * Check if the nick_blacklist condition is met.
  954. *
  955. * @param nick Nick that sent the message
  956. * @return True if nick is not in the blacklist
  957. */
  958. bool nick_blacklist(const CNick& nick)
  959. {
  960. VCString blacklist;
  961. options["nick_blacklist"].Split(" ", blacklist, false);
  962. CString name = nick.GetNick().AsLower();
  963. for (VCString::iterator i = blacklist.begin(); i != blacklist.end(); i++)
  964. {
  965. CString value;
  966. // Expand substrings like %nick%
  967. if (m_pNetwork)
  968. {
  969. value = m_pNetwork->ExpandString(*i);
  970. }
  971. else
  972. {
  973. value = GetUser()->ExpandString(*i);
  974. }
  975. if (name.WildCmp(value.AsLower()))
  976. {
  977. return false;
  978. }
  979. }
  980. return true;
  981. }
  982. /**
  983. * Check if the network_blacklist condition is met.
  984. *
  985. * @param network Network that the message was received on
  986. * @return True if network is not in the blacklist
  987. */
  988. bool network_blacklist()
  989. {
  990. VCString blacklist;
  991. options["network_blacklist"].Split(" ", blacklist, false);
  992. CString name = (*m_pNetwork).GetName().AsLower();
  993. for (VCString::iterator i = blacklist.begin(); i != blacklist.end(); i++)
  994. {
  995. if (name.WildCmp((*i).AsLower()))
  996. {
  997. return false;
  998. }
  999. }
  1000. return true;
  1001. }
  1002. /**
  1003. * Check if the replied condition is met.
  1004. *
  1005. * @param context Channel or nick context
  1006. * @return True if last_reply_time > last_notification_time or if replied is not "yes"
  1007. */
  1008. bool replied(const CString& context)
  1009. {
  1010. CString value = options["replied"].AsLower();
  1011. return value != "yes"
  1012. || last_notification_time[context] == 0
  1013. || last_notification_time[context] < last_reply_time[context];
  1014. }
  1015. /**
  1016. * Determine when to notify the user of a channel message.
  1017. *
  1018. * @param nick Nick that sent the message
  1019. * @param channel Channel the message was sent to
  1020. * @param message Message contents
  1021. * @return Notification should be sent
  1022. */
  1023. bool notify_channel(const CNick& nick, const CChan& channel, const CString& message)
  1024. {
  1025. CString context = channel.GetName();
  1026. CString expression = options["channel_conditions"].AsLower();
  1027. if (expression != "all")
  1028. {
  1029. return eval(expression, context, nick, message);
  1030. }
  1031. return away_only()
  1032. && client_count_less_than()
  1033. && highlight(message)
  1034. && idle()
  1035. && last_active(context)
  1036. && last_notification(context)
  1037. && nick_blacklist(nick)
  1038. && network_blacklist()
  1039. && replied(context)
  1040. && context_filter(context)
  1041. && true;
  1042. }
  1043. /**
  1044. * Determine when to notify the user of a private message.
  1045. *
  1046. * @param nick Nick that sent the message
  1047. * @return Notification should be sent
  1048. */
  1049. bool notify_pm(const CNick& nick, const CString& message)
  1050. {
  1051. CString context = nick.GetNick();
  1052. CString expression = options["query_conditions"].AsLower();
  1053. if (expression != "all")
  1054. {
  1055. return eval(expression, context, nick, message);
  1056. }
  1057. return away_only()
  1058. && client_count_less_than()
  1059. && idle()
  1060. && last_active(context)
  1061. && last_notification(context)
  1062. && nick_blacklist(nick)
  1063. && network_blacklist()
  1064. && replied(context)
  1065. && true;
  1066. }
  1067. protected:
  1068. /**
  1069. * Handle the plugin being loaded. Retrieve plugin config values.
  1070. *
  1071. * @param args Plugin arguments
  1072. * @param message Message to show the user after loading
  1073. */
  1074. bool OnLoad(const CString& args, CString& message)
  1075. {
  1076. for (MCString::iterator i = defaults.begin(); i != defaults.end(); i++)
  1077. {
  1078. CString value = GetNV(i->first);
  1079. if (value != "")
  1080. {
  1081. options[i->first] = value;
  1082. }
  1083. else
  1084. {
  1085. options[i->first] = defaults[i->first];
  1086. }
  1087. }
  1088. return true;
  1089. }
  1090. /**
  1091. * Handle channel messages.
  1092. *
  1093. * @param nick Nick that sent the message
  1094. * @param channel Channel the message was sent to
  1095. * @param message Message contents
  1096. */
  1097. EModRet OnChanMsg(CNick& nick, CChan& channel, CString& message)
  1098. {
  1099. if (notify_channel(nick, channel, message))
  1100. {
  1101. CString title = "Highlight";
  1102. send_message(message, title, channel.GetName(), nick);
  1103. }
  1104. return CONTINUE;
  1105. }
  1106. /**
  1107. * Handle channel actions.
  1108. *
  1109. * @param nick Nick that sent the action
  1110. * @param channel Channel the message was sent to
  1111. * @param message Message contents
  1112. */
  1113. EModRet OnChanAction(CNick& nick, CChan& channel, CString& message)
  1114. {
  1115. if (notify_channel(nick, channel, message))
  1116. {
  1117. CString title = "Highlight";
  1118. send_message(message, title, channel.GetName(), nick, "action");
  1119. }
  1120. return CONTINUE;
  1121. }
  1122. /**
  1123. * Handle channel notices.
  1124. *
  1125. * @param nick Nick that sent the notice
  1126. * @param channel Channel the notice was sent to
  1127. * @param message Notice contents
  1128. */
  1129. EModRet OnChanNotice(CNick& nick, CChan& channel, CString& message)
  1130. {
  1131. if (notify_channel(nick, channel, message))
  1132. {
  1133. CString title = "Channel Notice";
  1134. send_message(message, title, channel.GetName(), nick);
  1135. }
  1136. return CONTINUE;
  1137. }
  1138. /**
  1139. * Handle a private message.
  1140. *
  1141. * @param nick Nick that sent the message
  1142. * @param message Message contents
  1143. */
  1144. EModRet OnPrivMsg(CNick& nick, CString& message)
  1145. {
  1146. if (notify_pm(nick, message))
  1147. {
  1148. CString title = "Private Message";
  1149. send_message(message, title, nick.GetNick(), nick);
  1150. }
  1151. return CONTINUE;
  1152. }
  1153. /**
  1154. * Handle a private action.
  1155. *
  1156. * @param nick Nick that sent the action
  1157. * @param message Message contents
  1158. */
  1159. EModRet OnPrivAction(CNick& nick, CString& message)
  1160. {
  1161. if (notify_pm(nick, message))
  1162. {
  1163. CString title = "Private Message";
  1164. send_message(message, title, nick.GetNick(), nick, "action");
  1165. }
  1166. return CONTINUE;
  1167. }
  1168. /**
  1169. * Handle a private notice.
  1170. *
  1171. * @param nick Nick that sent the notice
  1172. * @param message Notice contents
  1173. */
  1174. EModRet OnPrivNotice(CNick& nick, CString& message)
  1175. {
  1176. if (notify_pm(nick, message))
  1177. {
  1178. CString title = "Private Notice";
  1179. send_message(message, title, nick.GetNick(), nick);
  1180. }
  1181. return CONTINUE;
  1182. }
  1183. /**
  1184. * Handle a message sent by the user.
  1185. *
  1186. * @param target Target channel or nick
  1187. * @param message Message contents
  1188. */
  1189. EModRet OnUserMsg(CString& target, CString& message)
  1190. {
  1191. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1192. return CONTINUE;
  1193. }
  1194. /**
  1195. * Handle an action sent by the user.
  1196. *
  1197. * @param target Target channel or nick
  1198. * @param message Message contents
  1199. */
  1200. EModRet OnUserAction(CString& target, CString& message)
  1201. {
  1202. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1203. return CONTINUE;
  1204. }
  1205. /**
  1206. * Handle a notice sent by the user.
  1207. *
  1208. * @param target Target channel or nick
  1209. * @param message Notice contents
  1210. */
  1211. EModRet OnUserNotice(CString& target, CString& message)
  1212. {
  1213. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1214. return CONTINUE;
  1215. }
  1216. /**
  1217. * Handle the user joining a channel.
  1218. *
  1219. * @param channel Channel name
  1220. * @param key Channel key
  1221. */
  1222. EModRet OnUserJoin(CString& channel, CString& key)
  1223. {
  1224. idle_time = time(NULL);
  1225. return CONTINUE;
  1226. }
  1227. /**
  1228. * Handle the user parting a channel.
  1229. *
  1230. * @param channel Channel name
  1231. * @param message Part message
  1232. */
  1233. EModRet OnUserPart(CString& channel, CString& message)
  1234. {
  1235. idle_time = time(NULL);
  1236. return CONTINUE;
  1237. }
  1238. /**
  1239. * Handle the user setting the channel topic.
  1240. *
  1241. * @param channel Channel name
  1242. * @param topic Topic message
  1243. */
  1244. EModRet OnUserTopic(CString& channel, CString& topic)
  1245. {
  1246. idle_time = time(NULL);
  1247. return CONTINUE;
  1248. }
  1249. /**
  1250. * Handle the user requesting the channel topic.
  1251. *
  1252. * @param channel Channel name
  1253. */
  1254. EModRet OnUserTopicRequest(CString& channel)
  1255. {
  1256. idle_time = time(NULL);
  1257. return CONTINUE;
  1258. }
  1259. /**
  1260. * Handle direct commands to the *push virtual user.
  1261. *
  1262. * @param command Command string
  1263. */
  1264. void OnModCommand(const CString& command)
  1265. {
  1266. VCString tokens;
  1267. CString::size_type token_count = command.Split(" ", tokens, false);
  1268. if (token_count < 1)
  1269. {
  1270. return;
  1271. }
  1272. CString action = tokens[0].AsLower();
  1273. // SET command
  1274. if (action == "set")
  1275. {
  1276. if (token_count < 3)
  1277. {
  1278. PutModule("Usage: set <option> <value>");
  1279. return;
  1280. }
  1281. CString option = tokens[1].AsLower();
  1282. CString value = command.Token(2, true, " ");
  1283. MCString::iterator pos = options.find(option);
  1284. if (pos == options.end())
  1285. {
  1286. PutModule("Error: invalid option name");
  1287. }
  1288. else
  1289. {
  1290. value.Trim();
  1291. if (option == "channel_conditions" || option == "query_conditions")
  1292. {
  1293. if (value != "all")
  1294. {
  1295. eval(value);
  1296. }
  1297. }
  1298. else if (option == "service")
  1299. {
  1300. value.MakeLower();
  1301. if (value == "pushbullet")
  1302. {
  1303. PutModule("Note: Pushbullet requires setting both 'target' (to device id) and 'secret' (to api key) options");
  1304. }
  1305. else if (value == "boxcar")
  1306. {
  1307. PutModule("Note: Boxcar requires setting the 'username' option");
  1308. }
  1309. else if (value == "boxcar2")
  1310. {
  1311. PutModule("Note: Boxcar 2 requires setting the 'secret' option");
  1312. }
  1313. else if (value == "nma")
  1314. {
  1315. PutModule("Note: NMA requires setting the 'secret' option");
  1316. }
  1317. else if (value == "pushover")
  1318. {
  1319. PutModule("Note: Pushover requires setting both the 'username' (to user key) and the 'secret' (to application api key) option");
  1320. }
  1321. else if (value == "pushsafer")
  1322. {
  1323. PutModule("Note: Pushsafer requires setting the 'private or alias key' option");
  1324. }
  1325. else if (value == "pushalot")
  1326. {
  1327. PutModule("Note: Pushalot requires setting the 'secret' (to user key) (to authorization token) option");
  1328. }
  1329. else if (value == "prowl")
  1330. {
  1331. PutModule("Note: Prowl requires setting the 'secret' option");
  1332. }
  1333. else if (value == "igloo")
  1334. {
  1335. PutModule("Note: Igloo requires adding your devices with device1-5");
  1336. }
  1337. else if (value == "supertoasty")
  1338. {
  1339. PutModule("Note: Supertoasty requires setting the 'secret' option with device id");
  1340. }
  1341. else if (value == "url")
  1342. {
  1343. PutModule("Note: URL requires setting the 'message_uri' option with the full URL");
  1344. }
  1345. else if (value == "faast")
  1346. {
  1347. PutModule("Note: Faast requires setting the secret to your apikey");
  1348. }
  1349. else if (value == "nexmo")
  1350. {
  1351. PutModule("Note: Nexmo requires setting the 'username' (to api key), 'secret' (to api secret), 'message_title' (to sender number in international format), and 'target' (to destination number in international format) options");
  1352. }
  1353. else if (value == "slack")
  1354. {
  1355. PutModule("Note: Slack requires setting 'secret' (from webhook) and 'target' (channel or username), optional 'username' (bot name)");
  1356. }
  1357. else if (value == "discord")
  1358. {
  1359. PutModule("Note: Discord requires setting 'secret' (from webhook), optional 'username' (bot name)");
  1360. }
  1361. else if (value == "pushjet")
  1362. {
  1363. PutModule("Note: Pushjet requires setting 'secret' (service key) option");
  1364. }
  1365. else if (value == "telegram")
  1366. {
  1367. PutModule("Note: Telegram requires setting both the 'secret' (api key) and 'target' (chat_id)");
  1368. }
  1369. else
  1370. {
  1371. PutModule("Error: unknown service name");
  1372. return;
  1373. }
  1374. }
  1375. options[option] = value;
  1376. SetNV(option, options[option]);
  1377. PutModule("Ok");
  1378. }
  1379. }
  1380. // APPEND command
  1381. else if (action == "append")
  1382. {
  1383. if (token_count < 3)
  1384. {
  1385. PutModule("Usage: append <option> <value>");
  1386. return;
  1387. }
  1388. CString option = tokens[1].AsLower();
  1389. CString value = command.Token(2, true, " ");
  1390. MCString::iterator pos = options.find(option);
  1391. if (pos == options.end())
  1392. {
  1393. PutModule("Error: invalid option name");
  1394. }
  1395. else if (option == "service")
  1396. {
  1397. PutModule("Error: cannot append to this option");
  1398. }
  1399. else
  1400. {
  1401. options[option] += " " + value;
  1402. options[option].Trim();
  1403. SetNV(option, options[option]);
  1404. PutModule("Ok");
  1405. }
  1406. }
  1407. // PREPEND command
  1408. else if (action == "prepend")
  1409. {
  1410. if (token_count < 3)
  1411. {
  1412. PutModule("Usage: prepend <option> <value>");
  1413. return;
  1414. }
  1415. CString option = tokens[1].AsLower();
  1416. CString value = command.Token(2, true, " ");
  1417. MCString::iterator pos = options.find(option);
  1418. if (pos == options.end())
  1419. {
  1420. PutModule("Error: invalid option name");
  1421. }
  1422. else if (option == "service")
  1423. {
  1424. PutModule("Error: cannot prepend to this option");
  1425. }
  1426. else
  1427. {
  1428. options[option] = value + " " + options[option];
  1429. options[option].Trim();
  1430. SetNV(option, options[option]);
  1431. PutModule("Ok");
  1432. }
  1433. }
  1434. // UNSET command
  1435. else if (action == "unset")
  1436. {
  1437. if (token_count != 2)
  1438. {
  1439. PutModule("Usage: unset <option>");
  1440. return;
  1441. }
  1442. CString option = tokens[1].AsLower();
  1443. MCString::iterator pos = options.find(option);
  1444. if (pos == options.end())
  1445. {
  1446. PutModule("Error: invalid option name");
  1447. }
  1448. else
  1449. {
  1450. options[option] = defaults[option];
  1451. DelNV(option);
  1452. PutModule("Ok");
  1453. }
  1454. }
  1455. // GET command
  1456. else if (action == "get")
  1457. {
  1458. if (token_count > 2)
  1459. {
  1460. PutModule("Usage: get [<option>]");
  1461. return;
  1462. }
  1463. if (token_count < 2)
  1464. {
  1465. CTable table;
  1466. table.AddColumn("Option");
  1467. table.AddColumn("Value");
  1468. for (MCString::iterator i = options.begin(); i != options.end(); i++)
  1469. {
  1470. table.AddRow();
  1471. table.SetCell("Option", i->first);
  1472. table.SetCell("Value", i->second);
  1473. }
  1474. PutModule(table);
  1475. return;
  1476. }
  1477. CString option = tokens[1].AsLower();
  1478. MCString::iterator pos = options.find(option);
  1479. if (pos == options.end())
  1480. {
  1481. PutModule("Error: invalid option name");
  1482. }
  1483. else
  1484. {
  1485. PutModule(option + CString(": ") + options[option]);
  1486. }
  1487. }
  1488. // SAVE command
  1489. else if (action == "save")
  1490. {
  1491. if (token_count < 2)
  1492. {
  1493. PutModule("Usage: save <filepath>");
  1494. }
  1495. CString file_path = command.Token(1, true, " ");
  1496. int status = options.WriteToDisk(file_path);
  1497. if (status == MCString::MCS_SUCCESS)
  1498. {
  1499. PutModule("Options saved to " + file_path);
  1500. }
  1501. else
  1502. {
  1503. switch (status)
  1504. {
  1505. case MCString::MCS_EOPEN:
  1506. case MCString::MCS_EWRITE:
  1507. case MCString::MCS_EWRITEFIL:
  1508. PutModule("Failed to save options to " + file_path);
  1509. break;
  1510. default:
  1511. PutModule("Failure");
  1512. break;
  1513. }
  1514. }
  1515. }
  1516. // LOAD command
  1517. else if (action == "load")
  1518. {
  1519. if (token_count < 2)
  1520. {
  1521. PutModule("Usage: load <filename>");
  1522. }
  1523. CString file_path = command.Token(1, true, " ");
  1524. if (!CFile::Exists(file_path))
  1525. {
  1526. PutModule("File does not exist: " + file_path);
  1527. return;
  1528. }
  1529. int status = options.ReadFromDisk(file_path);
  1530. if (status == MCString::MCS_SUCCESS)
  1531. {
  1532. PutModule("Options loaded from " + file_path);
  1533. // Restore any defaults that aren't in the loaded dictionary,
  1534. // and save loaded options to ZNC's data store
  1535. for (MCString::iterator i = defaults.begin(); i != defaults.end(); i++)
  1536. {
  1537. CString option = i->first;
  1538. MCString::iterator pos = options.find(option);
  1539. if (pos == options.end())
  1540. {
  1541. options[option] = defaults[option];
  1542. DelNV(option);
  1543. }
  1544. else
  1545. {
  1546. SetNV(option, options[option]);
  1547. }
  1548. }
  1549. }
  1550. else
  1551. {
  1552. switch (status)
  1553. {
  1554. case MCString::MCS_EOPEN:
  1555. case MCString::MCS_EREADFIL:
  1556. PutModule("Failed to read options from " + file_path);
  1557. break;
  1558. default:
  1559. PutModule("Failure");
  1560. break;
  1561. }
  1562. }
  1563. }
  1564. // STATUS command
  1565. else if (action == "status")
  1566. {
  1567. CTable table;
  1568. table.AddColumn("Condition");
  1569. table.AddColumn("Status");
  1570. table.AddRow();
  1571. table.SetCell("Condition", "away");
  1572. table.SetCell("Status", GetNetwork()->IsIRCAway() ? "yes" : "no");
  1573. table.AddRow();
  1574. table.SetCell("Condition", "client_count");
  1575. table.SetCell("Status", CString(client_count()));
  1576. time_t now = time(NULL);
  1577. time_t ago = now - idle_time;
  1578. table.AddRow();
  1579. table.SetCell("Condition", "idle");
  1580. table.SetCell("Status", CString(ago) + " seconds");
  1581. table.AddRow();
  1582. table.SetCell("Condition", "network_blacklist");
  1583. // network_blacklist() is True if the network is not in a blacklist
  1584. table.SetCell("Status", network_blacklist() ? "no" : "yes");
  1585. if (token_count > 1)
  1586. {
  1587. CString context = tokens[1];
  1588. table.AddRow();
  1589. table.SetCell("Condition", "last_active");
  1590. if (last_active_time.count(context) < 1)
  1591. {
  1592. table.SetCell("Status", "n/a");
  1593. }
  1594. else
  1595. {
  1596. ago = now - last_active_time[context];
  1597. table.SetCell("Status", CString(ago) + " seconds");
  1598. }
  1599. table.AddRow();
  1600. table.SetCell("Condition", "last_notification");
  1601. if (last_notification_time.count(context) < 1)
  1602. {
  1603. table.SetCell("Status", "n/a");
  1604. }
  1605. else
  1606. {
  1607. ago = now - last_notification_time[context];
  1608. table.SetCell("Status", CString(ago) + " seconds");
  1609. }
  1610. table.AddRow();
  1611. table.SetCell("Condition", "replied");
  1612. table.SetCell("Status", replied(context) ? "yes" : "no");
  1613. }
  1614. PutModule(table);
  1615. }
  1616. // SUBSCRIBE command
  1617. else if (action == "subscribe")
  1618. {
  1619. // Set up the connection profile
  1620. CString service = options["service"];
  1621. bool use_post = true;
  1622. int use_port = 443;
  1623. bool use_ssl = true;
  1624. CString service_host;
  1625. CString service_url;
  1626. CString service_auth;
  1627. MCString params;
  1628. if (service == "boxcar")
  1629. {
  1630. if (options["username"] == "")
  1631. {
  1632. PutModule("Error: username not set");
  1633. return;
  1634. }
  1635. CString boxcar_api_key = "puSd2qp2gCDZO7nWkvb9";
  1636. service_host = "boxcar.io";
  1637. service_url = "/devices/providers/" + boxcar_api_key + "/notifications/subscribe";
  1638. params["email"] = options["username"];
  1639. }
  1640. else if (service == "airgram")
  1641. {
  1642. PutModule("Error: Airgram service shut down. Please configure a different notification provider.");
  1643. }
  1644. else
  1645. {
  1646. PutModule("Error: service does not support subscribe command");
  1647. return;
  1648. }
  1649. #ifdef USE_CURL
  1650. long http_code = make_curl_request(service_host, service_url, service_auth, params, use_port, use_ssl, use_post, options["proxy"], options["proxy_ssl_verify"] != "no", options["debug"] == "on");
  1651. PutDebug("curl: HTTP status code " + CString(http_code));
  1652. if (!(http_code >= 200 && http_code < 300)) {
  1653. PutModule("Error: HTTP status code " + CString(http_code));
  1654. }
  1655. #else
  1656. // Create the socket connection, write to it, and add it to the queue
  1657. CPushSocket *sock = new CPushSocket(this);
  1658. sock->Connect(service_host, use_port, use_ssl);
  1659. sock->Request(use_post, service_host, service_url, params, service_auth);
  1660. AddSocket(sock);
  1661. #endif
  1662. PutModule("Ok");
  1663. }
  1664. // SEND command
  1665. else if (action == "send")
  1666. {
  1667. CString message = command.Token(1, true, " ", true);
  1668. send_message(message);
  1669. PutModule("Ok");
  1670. }
  1671. // HELP command
  1672. else if (action == "help")
  1673. {
  1674. PutModule("View the detailed documentation at https://github.com/jreese/znc-push/blob/master/README.md");
  1675. }
  1676. // VERSION command
  1677. else if (action == "version")
  1678. {
  1679. PutModule("znc-push " + CString(PUSHVERSION));
  1680. }
  1681. // EVAL command
  1682. else if (action == "eval")
  1683. {
  1684. CString value = command.Token(1, true, " ");
  1685. PutModule(eval(value) ? "true" : "false");
  1686. }
  1687. else
  1688. {
  1689. PutModule("Error: invalid command, try `help`");
  1690. }
  1691. }
  1692. };
  1693. /**
  1694. * Build a query string from a dictionary of request parameters.
  1695. *
  1696. * @param params Request parameters
  1697. * @return query string
  1698. */
  1699. CString build_query_string(MCString& params)
  1700. {
  1701. bool more = false;
  1702. CString query;
  1703. CString key;
  1704. CString value;
  1705. for (MCString::iterator param = params.begin(); param != params.end(); param++)
  1706. {
  1707. key = urlencode(param->first);
  1708. value = urlencode(param->second);
  1709. if (more)
  1710. {
  1711. query += "&" + key + "=" + value;
  1712. }
  1713. else
  1714. {
  1715. query += key + "=" + value;
  1716. more = true;
  1717. }
  1718. }
  1719. return query;
  1720. }
  1721. #ifdef USE_CURL
  1722. /**
  1723. * Send an HTTP request using libcurl.
  1724. *
  1725. * @param service_host Host domain
  1726. * @param service_url Host path
  1727. * @param service_auth Basic auth string
  1728. * @param params Request parameters
  1729. * @param port Port number
  1730. * @param use_ssl Use SSL
  1731. * @param use_post Use POST method
  1732. */
  1733. long make_curl_request(const CString& service_host, const CString& service_url,
  1734. const CString& service_auth, MCString& params, int port,
  1735. bool use_ssl, bool use_post,
  1736. const CString& proxy, bool proxy_ssl_verify,
  1737. bool debug)
  1738. {
  1739. CURL *curl;
  1740. CURLcode result;
  1741. long http_code;
  1742. curl = curl_easy_init();
  1743. CString user_agent = "ZNC Push/" + CString(PUSHVERSION);
  1744. CString url = CString(use_ssl ? "https" : "http") + "://" + service_host + service_url;
  1745. CString query = build_query_string(params);
  1746. if (!query.empty())
  1747. {
  1748. url = url + "?" + query;
  1749. }
  1750. if (debug)
  1751. {
  1752. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1753. }
  1754. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
  1755. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
  1756. curl_easy_setopt(curl, CURLOPT_URL, url.data());
  1757. curl_easy_setopt(curl, CURLOPT_PORT, port);
  1758. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());
  1759. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); // three seconds ought to be good enough for anyone, eh?
  1760. if (service_auth != "")
  1761. {
  1762. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  1763. curl_easy_setopt(curl, CURLOPT_USERPWD, service_auth.data());
  1764. }
  1765. if (use_post)
  1766. {
  1767. curl_easy_setopt(curl, CURLOPT_POST, 1);
  1768. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query.data());
  1769. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, query.length());
  1770. }
  1771. if (proxy != "") {
  1772. curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str());
  1773. if (!proxy_ssl_verify) {
  1774. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1775. }
  1776. }
  1777. result = curl_easy_perform(curl);
  1778. if (result != CURLE_OK) {
  1779. curl_easy_cleanup(curl);
  1780. return -1;
  1781. }
  1782. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
  1783. curl_easy_cleanup(curl);
  1784. return http_code;
  1785. }
  1786. #else
  1787. /**
  1788. * Send an HTTP request.
  1789. *
  1790. * @param post POST command
  1791. * @param host Host domain
  1792. * @param url Resource path
  1793. * @param parameters Query parameters
  1794. * @param auth Basic authentication string
  1795. */
  1796. void CPushSocket::Request(bool post, const CString& host, const CString& url, MCString& parameters, const CString& auth)
  1797. {
  1798. parent->PutDebug("Building notification to " + host + url + "...");
  1799. CString query = build_query_string(parameters);
  1800. // Request headers and POST body
  1801. CString request;
  1802. if (post)
  1803. {
  1804. request += "POST " + url + " HTTP/1.1" + crlf;
  1805. request += "Content-Type: application/x-www-form-urlencoded" + crlf;
  1806. request += "Content-Length: " + CString(query.length()) + crlf;
  1807. }
  1808. else
  1809. {
  1810. request += "GET " + url + "?" + query + " HTTP/1.1" + crlf;
  1811. }
  1812. request += "Host: " + host + crlf;
  1813. request += "Connection: close" + crlf;
  1814. request += "User-Agent: " + user_agent + crlf;
  1815. parent->PutDebug("User-Agent: " + user_agent);
  1816. if (auth != "")
  1817. {
  1818. CString auth_b64 = auth.Base64Encode_n();
  1819. request += "Authorization: Basic " + auth_b64 + crlf;
  1820. parent->PutDebug("Authorization: Basic " + auth_b64);
  1821. }
  1822. request += crlf;
  1823. if (post)
  1824. {
  1825. request += query;
  1826. }
  1827. parent->PutDebug("Query string: " + query);
  1828. Write(request);
  1829. parent->PutDebug("Request sending");
  1830. }
  1831. /**
  1832. * Read each line of data returned from the HTTP request.
  1833. */
  1834. void CPushSocket::ReadLine(const CString& data)
  1835. {
  1836. if (first)
  1837. {
  1838. CString status = data.Token(1);
  1839. CString message = data.Token(2, true);
  1840. parent->PutDebug("Status: " + status);
  1841. parent->PutDebug("Message: " + message);
  1842. first = false;
  1843. }
  1844. else
  1845. {
  1846. parent->PutDebug("Data: " + data);
  1847. }
  1848. }
  1849. void CPushSocket::Disconnected()
  1850. {
  1851. parent->PutDebug("Disconnected.");
  1852. Close(CSocket::CLT_AFTERWRITE);
  1853. }
  1854. #endif // USE_CURL
  1855. template<> void TModInfo<CPushMod>(CModInfo& Info) {
  1856. Info.AddType(CModInfo::UserModule);
  1857. Info.SetWikiPage("push");
  1858. }
  1859. NETWORKMODULEDEFS(CPushMod, "Send highlights and personal messages to a push notification service")