push.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  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. for (VCString::iterator i = values.begin(); i != values.end(); i++)
  840. {
  841. CString value = i->AsLower();
  842. char prefix = value[0];
  843. bool negate_match = false;
  844. if (prefix == '-')
  845. {
  846. negate_match = true;
  847. value.LeftChomp(1);
  848. }
  849. else if (prefix == '_')
  850. {
  851. value = " " + value.LeftChomp_n(1) + " ";
  852. }
  853. // Expand substrings like %nick%
  854. if (m_pNetwork)
  855. {
  856. value = m_pNetwork->ExpandString(value);
  857. }
  858. else
  859. {
  860. value = GetUser()->ExpandString(value);
  861. }
  862. value = "*" + value.AsLower() + "*";
  863. if (msg.WildCmp(value))
  864. {
  865. return !negate_match;
  866. }
  867. }
  868. return false;
  869. }
  870. /**
  871. * Determine if the given context matches any context rules.
  872. *
  873. * @param context The context of a message
  874. * @return True if context matches the filter
  875. */
  876. bool context_filter(const CString& raw_context)
  877. {
  878. CString context = raw_context.AsLower();
  879. if (context == "all" || context == "*")
  880. return true;
  881. VCString values;
  882. options["context"].Split(" ", values, false);
  883. for (VCString::iterator i = values.begin(); i != values.end(); i++)
  884. {
  885. CString value = i->AsLower();
  886. char prefix = value[0];
  887. bool push = true;
  888. if (prefix == '-')
  889. {
  890. push = false;
  891. value.LeftChomp(1);
  892. }
  893. if (value != "*")
  894. {
  895. value = "*" + value.AsLower() + "*";
  896. }
  897. if (context.WildCmp(value))
  898. {
  899. return push;
  900. }
  901. }
  902. return false;
  903. }
  904. /**
  905. * Check if the idle condition is met.
  906. *
  907. * @return True if idle is less than or equal to zero or elapsed time is greater than idle
  908. */
  909. bool idle()
  910. {
  911. unsigned int value = options["idle"].ToUInt();
  912. time_t now = time(NULL);
  913. return value == 0 || difftime(now, idle_time) >= value;
  914. }
  915. /**
  916. * Check if the last_active condition is met.
  917. *
  918. * @param context Channel or nick context
  919. * @return True if last_active is less than or equal to zero or elapsed time is greater than last_active
  920. */
  921. bool last_active(const CString& context)
  922. {
  923. unsigned int value = options["last_active"].ToUInt();
  924. time_t now = time(NULL);
  925. return value == 0
  926. || last_active_time.count(context) < 1
  927. || difftime(now, last_active_time[context]) >= value;
  928. }
  929. /**
  930. * Check if the last_notification condition is met.
  931. *
  932. * @param context Channel or nick context
  933. * @return True if last_notification is less than or equal to zero or elapsed time is greater than last_nofication
  934. */
  935. bool last_notification(const CString& context)
  936. {
  937. unsigned int value = options["last_notification"].ToUInt();
  938. time_t now = time(NULL);
  939. return value == 0
  940. || last_notification_time.count(context) < 1
  941. || difftime(now, last_notification_time[context]) >= value;
  942. }
  943. /**
  944. * Check if the nick_blacklist condition is met.
  945. *
  946. * @param nick Nick that sent the message
  947. * @return True if nick is not in the blacklist
  948. */
  949. bool nick_blacklist(const CNick& nick)
  950. {
  951. VCString blacklist;
  952. options["nick_blacklist"].Split(" ", blacklist, false);
  953. CString name = nick.GetNick().AsLower();
  954. for (VCString::iterator i = blacklist.begin(); i != blacklist.end(); i++)
  955. {
  956. CString value;
  957. // Expand substrings like %nick%
  958. if (m_pNetwork)
  959. {
  960. value = m_pNetwork->ExpandString(*i);
  961. }
  962. else
  963. {
  964. value = GetUser()->ExpandString(*i);
  965. }
  966. if (name.WildCmp(value.AsLower()))
  967. {
  968. return false;
  969. }
  970. }
  971. return true;
  972. }
  973. /**
  974. * Check if the network_blacklist condition is met.
  975. *
  976. * @param network Network that the message was received on
  977. * @return True if network is not in the blacklist
  978. */
  979. bool network_blacklist()
  980. {
  981. VCString blacklist;
  982. options["network_blacklist"].Split(" ", blacklist, false);
  983. CString name = (*m_pNetwork).GetName().AsLower();
  984. for (VCString::iterator i = blacklist.begin(); i != blacklist.end(); i++)
  985. {
  986. if (name.WildCmp((*i).AsLower()))
  987. {
  988. return false;
  989. }
  990. }
  991. return true;
  992. }
  993. /**
  994. * Check if the replied condition is met.
  995. *
  996. * @param context Channel or nick context
  997. * @return True if last_reply_time > last_notification_time or if replied is not "yes"
  998. */
  999. bool replied(const CString& context)
  1000. {
  1001. CString value = options["replied"].AsLower();
  1002. return value != "yes"
  1003. || last_notification_time[context] == 0
  1004. || last_notification_time[context] < last_reply_time[context];
  1005. }
  1006. /**
  1007. * Determine when to notify the user of a channel message.
  1008. *
  1009. * @param nick Nick that sent the message
  1010. * @param channel Channel the message was sent to
  1011. * @param message Message contents
  1012. * @return Notification should be sent
  1013. */
  1014. bool notify_channel(const CNick& nick, const CChan& channel, const CString& message)
  1015. {
  1016. CString context = channel.GetName();
  1017. CString expression = options["channel_conditions"].AsLower();
  1018. if (expression != "all")
  1019. {
  1020. return eval(expression, context, nick, message);
  1021. }
  1022. return away_only()
  1023. && client_count_less_than()
  1024. && highlight(message)
  1025. && idle()
  1026. && last_active(context)
  1027. && last_notification(context)
  1028. && nick_blacklist(nick)
  1029. && network_blacklist()
  1030. && replied(context)
  1031. && context_filter(context)
  1032. && true;
  1033. }
  1034. /**
  1035. * Determine when to notify the user of a private message.
  1036. *
  1037. * @param nick Nick that sent the message
  1038. * @return Notification should be sent
  1039. */
  1040. bool notify_pm(const CNick& nick, const CString& message)
  1041. {
  1042. CString context = nick.GetNick();
  1043. CString expression = options["query_conditions"].AsLower();
  1044. if (expression != "all")
  1045. {
  1046. return eval(expression, context, nick, message);
  1047. }
  1048. return away_only()
  1049. && client_count_less_than()
  1050. && idle()
  1051. && last_active(context)
  1052. && last_notification(context)
  1053. && nick_blacklist(nick)
  1054. && network_blacklist()
  1055. && replied(context)
  1056. && true;
  1057. }
  1058. protected:
  1059. /**
  1060. * Handle the plugin being loaded. Retrieve plugin config values.
  1061. *
  1062. * @param args Plugin arguments
  1063. * @param message Message to show the user after loading
  1064. */
  1065. bool OnLoad(const CString& args, CString& message)
  1066. {
  1067. for (MCString::iterator i = defaults.begin(); i != defaults.end(); i++)
  1068. {
  1069. CString value = GetNV(i->first);
  1070. if (value != "")
  1071. {
  1072. options[i->first] = value;
  1073. }
  1074. else
  1075. {
  1076. options[i->first] = defaults[i->first];
  1077. }
  1078. }
  1079. return true;
  1080. }
  1081. /**
  1082. * Handle channel messages.
  1083. *
  1084. * @param nick Nick that sent the message
  1085. * @param channel Channel the message was sent to
  1086. * @param message Message contents
  1087. */
  1088. EModRet OnChanMsg(CNick& nick, CChan& channel, CString& message)
  1089. {
  1090. if (notify_channel(nick, channel, message))
  1091. {
  1092. CString title = "Highlight";
  1093. send_message(message, title, channel.GetName(), nick);
  1094. }
  1095. return CONTINUE;
  1096. }
  1097. /**
  1098. * Handle channel actions.
  1099. *
  1100. * @param nick Nick that sent the action
  1101. * @param channel Channel the message was sent to
  1102. * @param message Message contents
  1103. */
  1104. EModRet OnChanAction(CNick& nick, CChan& channel, CString& message)
  1105. {
  1106. if (notify_channel(nick, channel, message))
  1107. {
  1108. CString title = "Highlight";
  1109. send_message(message, title, channel.GetName(), nick, "action");
  1110. }
  1111. return CONTINUE;
  1112. }
  1113. /**
  1114. * Handle channel notices.
  1115. *
  1116. * @param nick Nick that sent the notice
  1117. * @param channel Channel the notice was sent to
  1118. * @param message Notice contents
  1119. */
  1120. EModRet OnChanNotice(CNick& nick, CChan& channel, CString& message)
  1121. {
  1122. if (notify_channel(nick, channel, message))
  1123. {
  1124. CString title = "Channel Notice";
  1125. send_message(message, title, channel.GetName(), nick, "notice");
  1126. }
  1127. return CONTINUE;
  1128. }
  1129. /**
  1130. * Handle a private message.
  1131. *
  1132. * @param nick Nick that sent the message
  1133. * @param message Message contents
  1134. */
  1135. EModRet OnPrivMsg(CNick& nick, CString& message)
  1136. {
  1137. if (notify_pm(nick, message))
  1138. {
  1139. CString title = "Private Message";
  1140. send_message(message, title, nick.GetNick(), nick);
  1141. }
  1142. return CONTINUE;
  1143. }
  1144. /**
  1145. * Handle a private action.
  1146. *
  1147. * @param nick Nick that sent the action
  1148. * @param message Message contents
  1149. */
  1150. EModRet OnPrivAction(CNick& nick, CString& message)
  1151. {
  1152. if (notify_pm(nick, message))
  1153. {
  1154. CString title = "Private Message";
  1155. send_message(message, title, nick.GetNick(), nick, "action");
  1156. }
  1157. return CONTINUE;
  1158. }
  1159. /**
  1160. * Handle a private notice.
  1161. *
  1162. * @param nick Nick that sent the notice
  1163. * @param message Notice contents
  1164. */
  1165. EModRet OnPrivNotice(CNick& nick, CString& message)
  1166. {
  1167. if (notify_pm(nick, message))
  1168. {
  1169. CString title = "Private Notice";
  1170. send_message(message, title, nick.GetNick(), nick, "notice");
  1171. }
  1172. return CONTINUE;
  1173. }
  1174. /**
  1175. * Handle a message sent by the user.
  1176. *
  1177. * @param target Target channel or nick
  1178. * @param message Message contents
  1179. */
  1180. EModRet OnUserMsg(CString& target, CString& message)
  1181. {
  1182. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1183. return CONTINUE;
  1184. }
  1185. /**
  1186. * Handle an action sent by the user.
  1187. *
  1188. * @param target Target channel or nick
  1189. * @param message Message contents
  1190. */
  1191. EModRet OnUserAction(CString& target, CString& message)
  1192. {
  1193. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1194. return CONTINUE;
  1195. }
  1196. /**
  1197. * Handle a notice sent by the user.
  1198. *
  1199. * @param target Target channel or nick
  1200. * @param message Notice contents
  1201. */
  1202. EModRet OnUserNotice(CString& target, CString& message)
  1203. {
  1204. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1205. return CONTINUE;
  1206. }
  1207. /**
  1208. * Handle the user joining a channel.
  1209. *
  1210. * @param channel Channel name
  1211. * @param key Channel key
  1212. */
  1213. EModRet OnUserJoin(CString& channel, CString& key)
  1214. {
  1215. idle_time = time(NULL);
  1216. return CONTINUE;
  1217. }
  1218. /**
  1219. * Handle the user parting a channel.
  1220. *
  1221. * @param channel Channel name
  1222. * @param message Part message
  1223. */
  1224. EModRet OnUserPart(CString& channel, CString& message)
  1225. {
  1226. idle_time = time(NULL);
  1227. return CONTINUE;
  1228. }
  1229. /**
  1230. * Handle the user setting the channel topic.
  1231. *
  1232. * @param channel Channel name
  1233. * @param topic Topic message
  1234. */
  1235. EModRet OnUserTopic(CString& channel, CString& topic)
  1236. {
  1237. idle_time = time(NULL);
  1238. return CONTINUE;
  1239. }
  1240. /**
  1241. * Handle the user requesting the channel topic.
  1242. *
  1243. * @param channel Channel name
  1244. */
  1245. EModRet OnUserTopicRequest(CString& channel)
  1246. {
  1247. idle_time = time(NULL);
  1248. return CONTINUE;
  1249. }
  1250. /**
  1251. * Handle direct commands to the *push virtual user.
  1252. *
  1253. * @param command Command string
  1254. */
  1255. void OnModCommand(const CString& command)
  1256. {
  1257. VCString tokens;
  1258. CString::size_type token_count = command.Split(" ", tokens, false);
  1259. if (token_count < 1)
  1260. {
  1261. return;
  1262. }
  1263. CString action = tokens[0].AsLower();
  1264. // SET command
  1265. if (action == "set")
  1266. {
  1267. if (token_count < 3)
  1268. {
  1269. PutModule("Usage: set <option> <value>");
  1270. return;
  1271. }
  1272. CString option = tokens[1].AsLower();
  1273. CString value = command.Token(2, true, " ");
  1274. MCString::iterator pos = options.find(option);
  1275. if (pos == options.end())
  1276. {
  1277. PutModule("Error: invalid option name");
  1278. }
  1279. else
  1280. {
  1281. value.Trim();
  1282. if (option == "channel_conditions" || option == "query_conditions")
  1283. {
  1284. if (value != "all")
  1285. {
  1286. eval(value);
  1287. }
  1288. }
  1289. else if (option == "service")
  1290. {
  1291. value.MakeLower();
  1292. if (value == "pushbullet")
  1293. {
  1294. PutModule("Note: Pushbullet requires setting both 'target' (to device id) and 'secret' (to api key) options");
  1295. }
  1296. else if (value == "boxcar")
  1297. {
  1298. PutModule("Note: Boxcar requires setting the 'username' option");
  1299. }
  1300. else if (value == "boxcar2")
  1301. {
  1302. PutModule("Note: Boxcar 2 requires setting the 'secret' option");
  1303. }
  1304. else if (value == "nma")
  1305. {
  1306. PutModule("Note: NMA requires setting the 'secret' option");
  1307. }
  1308. else if (value == "pushover")
  1309. {
  1310. PutModule("Note: Pushover requires setting both the 'username' (to user key) and the 'secret' (to application api key) option");
  1311. }
  1312. else if (value == "pushsafer")
  1313. {
  1314. PutModule("Note: Pushsafer requires setting the 'private or alias key' option");
  1315. }
  1316. else if (value == "pushalot")
  1317. {
  1318. PutModule("Note: Pushalot requires setting the 'secret' (to user key) (to authorization token) option");
  1319. }
  1320. else if (value == "prowl")
  1321. {
  1322. PutModule("Note: Prowl requires setting the 'secret' option");
  1323. }
  1324. else if (value == "igloo")
  1325. {
  1326. PutModule("Note: Igloo requires adding your devices with device1-5");
  1327. }
  1328. else if (value == "supertoasty")
  1329. {
  1330. PutModule("Note: Supertoasty requires setting the 'secret' option with device id");
  1331. }
  1332. else if (value == "url")
  1333. {
  1334. PutModule("Note: URL requires setting the 'message_uri' option with the full URL");
  1335. }
  1336. else if (value == "faast")
  1337. {
  1338. PutModule("Note: Faast requires setting the secret to your apikey");
  1339. }
  1340. else if (value == "nexmo")
  1341. {
  1342. 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");
  1343. }
  1344. else if (value == "slack")
  1345. {
  1346. PutModule("Note: Slack requires setting 'secret' (from webhook) and 'target' (channel or username), optional 'username' (bot name)");
  1347. }
  1348. else if (value == "discord")
  1349. {
  1350. PutModule("Note: Discord requires setting 'secret' (from webhook), optional 'username' (bot name)");
  1351. }
  1352. else if (value == "pushjet")
  1353. {
  1354. PutModule("Note: Pushjet requires setting 'secret' (service key) option");
  1355. }
  1356. else if (value == "telegram")
  1357. {
  1358. PutModule("Note: Telegram requires setting both the 'secret' (api key) and 'target' (chat_id)");
  1359. }
  1360. else
  1361. {
  1362. PutModule("Error: unknown service name");
  1363. return;
  1364. }
  1365. }
  1366. options[option] = value;
  1367. SetNV(option, options[option]);
  1368. PutModule("Ok");
  1369. }
  1370. }
  1371. // APPEND command
  1372. else if (action == "append")
  1373. {
  1374. if (token_count < 3)
  1375. {
  1376. PutModule("Usage: append <option> <value>");
  1377. return;
  1378. }
  1379. CString option = tokens[1].AsLower();
  1380. CString value = command.Token(2, true, " ");
  1381. MCString::iterator pos = options.find(option);
  1382. if (pos == options.end())
  1383. {
  1384. PutModule("Error: invalid option name");
  1385. }
  1386. else if (option == "service")
  1387. {
  1388. PutModule("Error: cannot append to this option");
  1389. }
  1390. else
  1391. {
  1392. options[option] += " " + value;
  1393. options[option].Trim();
  1394. SetNV(option, options[option]);
  1395. PutModule("Ok");
  1396. }
  1397. }
  1398. // PREPEND command
  1399. else if (action == "prepend")
  1400. {
  1401. if (token_count < 3)
  1402. {
  1403. PutModule("Usage: prepend <option> <value>");
  1404. return;
  1405. }
  1406. CString option = tokens[1].AsLower();
  1407. CString value = command.Token(2, true, " ");
  1408. MCString::iterator pos = options.find(option);
  1409. if (pos == options.end())
  1410. {
  1411. PutModule("Error: invalid option name");
  1412. }
  1413. else if (option == "service")
  1414. {
  1415. PutModule("Error: cannot prepend to this option");
  1416. }
  1417. else
  1418. {
  1419. options[option] = value + " " + options[option];
  1420. options[option].Trim();
  1421. SetNV(option, options[option]);
  1422. PutModule("Ok");
  1423. }
  1424. }
  1425. // UNSET command
  1426. else if (action == "unset")
  1427. {
  1428. if (token_count != 2)
  1429. {
  1430. PutModule("Usage: unset <option>");
  1431. return;
  1432. }
  1433. CString option = tokens[1].AsLower();
  1434. MCString::iterator pos = options.find(option);
  1435. if (pos == options.end())
  1436. {
  1437. PutModule("Error: invalid option name");
  1438. }
  1439. else
  1440. {
  1441. options[option] = defaults[option];
  1442. DelNV(option);
  1443. PutModule("Ok");
  1444. }
  1445. }
  1446. // GET command
  1447. else if (action == "get")
  1448. {
  1449. if (token_count > 2)
  1450. {
  1451. PutModule("Usage: get [<option>]");
  1452. return;
  1453. }
  1454. if (token_count < 2)
  1455. {
  1456. CTable table;
  1457. table.AddColumn("Option");
  1458. table.AddColumn("Value");
  1459. for (MCString::iterator i = options.begin(); i != options.end(); i++)
  1460. {
  1461. table.AddRow();
  1462. table.SetCell("Option", i->first);
  1463. table.SetCell("Value", i->second);
  1464. }
  1465. PutModule(table);
  1466. return;
  1467. }
  1468. CString option = tokens[1].AsLower();
  1469. MCString::iterator pos = options.find(option);
  1470. if (pos == options.end())
  1471. {
  1472. PutModule("Error: invalid option name");
  1473. }
  1474. else
  1475. {
  1476. PutModule(option + CString(": ") + options[option]);
  1477. }
  1478. }
  1479. // SAVE command
  1480. else if (action == "save")
  1481. {
  1482. if (token_count < 2)
  1483. {
  1484. PutModule("Usage: save <filepath>");
  1485. }
  1486. CString file_path = command.Token(1, true, " ");
  1487. int status = options.WriteToDisk(file_path);
  1488. if (status == MCString::MCS_SUCCESS)
  1489. {
  1490. PutModule("Options saved to " + file_path);
  1491. }
  1492. else
  1493. {
  1494. switch (status)
  1495. {
  1496. case MCString::MCS_EOPEN:
  1497. case MCString::MCS_EWRITE:
  1498. case MCString::MCS_EWRITEFIL:
  1499. PutModule("Failed to save options to " + file_path);
  1500. break;
  1501. default:
  1502. PutModule("Failure");
  1503. break;
  1504. }
  1505. }
  1506. }
  1507. // LOAD command
  1508. else if (action == "load")
  1509. {
  1510. if (token_count < 2)
  1511. {
  1512. PutModule("Usage: load <filename>");
  1513. }
  1514. CString file_path = command.Token(1, true, " ");
  1515. if (!CFile::Exists(file_path))
  1516. {
  1517. PutModule("File does not exist: " + file_path);
  1518. return;
  1519. }
  1520. int status = options.ReadFromDisk(file_path);
  1521. if (status == MCString::MCS_SUCCESS)
  1522. {
  1523. PutModule("Options loaded from " + file_path);
  1524. // Restore any defaults that aren't in the loaded dictionary,
  1525. // and save loaded options to ZNC's data store
  1526. for (MCString::iterator i = defaults.begin(); i != defaults.end(); i++)
  1527. {
  1528. CString option = i->first;
  1529. MCString::iterator pos = options.find(option);
  1530. if (pos == options.end())
  1531. {
  1532. options[option] = defaults[option];
  1533. DelNV(option);
  1534. }
  1535. else
  1536. {
  1537. SetNV(option, options[option]);
  1538. }
  1539. }
  1540. }
  1541. else
  1542. {
  1543. switch (status)
  1544. {
  1545. case MCString::MCS_EOPEN:
  1546. case MCString::MCS_EREADFIL:
  1547. PutModule("Failed to read options from " + file_path);
  1548. break;
  1549. default:
  1550. PutModule("Failure");
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. // STATUS command
  1556. else if (action == "status")
  1557. {
  1558. CTable table;
  1559. table.AddColumn("Condition");
  1560. table.AddColumn("Status");
  1561. table.AddRow();
  1562. table.SetCell("Condition", "away");
  1563. table.SetCell("Status", GetNetwork()->IsIRCAway() ? "yes" : "no");
  1564. table.AddRow();
  1565. table.SetCell("Condition", "client_count");
  1566. table.SetCell("Status", CString(client_count()));
  1567. time_t now = time(NULL);
  1568. time_t ago = now - idle_time;
  1569. table.AddRow();
  1570. table.SetCell("Condition", "idle");
  1571. table.SetCell("Status", CString(ago) + " seconds");
  1572. table.AddRow();
  1573. table.SetCell("Condition", "network_blacklist");
  1574. // network_blacklist() is True if the network is not in a blacklist
  1575. table.SetCell("Status", network_blacklist() ? "no" : "yes");
  1576. if (token_count > 1)
  1577. {
  1578. CString context = tokens[1];
  1579. table.AddRow();
  1580. table.SetCell("Condition", "last_active");
  1581. if (last_active_time.count(context) < 1)
  1582. {
  1583. table.SetCell("Status", "n/a");
  1584. }
  1585. else
  1586. {
  1587. ago = now - last_active_time[context];
  1588. table.SetCell("Status", CString(ago) + " seconds");
  1589. }
  1590. table.AddRow();
  1591. table.SetCell("Condition", "last_notification");
  1592. if (last_notification_time.count(context) < 1)
  1593. {
  1594. table.SetCell("Status", "n/a");
  1595. }
  1596. else
  1597. {
  1598. ago = now - last_notification_time[context];
  1599. table.SetCell("Status", CString(ago) + " seconds");
  1600. }
  1601. table.AddRow();
  1602. table.SetCell("Condition", "replied");
  1603. table.SetCell("Status", replied(context) ? "yes" : "no");
  1604. }
  1605. PutModule(table);
  1606. }
  1607. // SUBSCRIBE command
  1608. else if (action == "subscribe")
  1609. {
  1610. // Set up the connection profile
  1611. CString service = options["service"];
  1612. bool use_post = true;
  1613. int use_port = 443;
  1614. bool use_ssl = true;
  1615. CString service_host;
  1616. CString service_url;
  1617. CString service_auth;
  1618. MCString params;
  1619. if (service == "boxcar")
  1620. {
  1621. if (options["username"] == "")
  1622. {
  1623. PutModule("Error: username not set");
  1624. return;
  1625. }
  1626. CString boxcar_api_key = "puSd2qp2gCDZO7nWkvb9";
  1627. service_host = "boxcar.io";
  1628. service_url = "/devices/providers/" + boxcar_api_key + "/notifications/subscribe";
  1629. params["email"] = options["username"];
  1630. }
  1631. else if (service == "airgram")
  1632. {
  1633. PutModule("Error: Airgram service shut down. Please configure a different notification provider.");
  1634. }
  1635. else
  1636. {
  1637. PutModule("Error: service does not support subscribe command");
  1638. return;
  1639. }
  1640. #ifdef USE_CURL
  1641. 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");
  1642. PutDebug("curl: HTTP status code " + CString(http_code));
  1643. if (!(http_code >= 200 && http_code < 300)) {
  1644. PutModule("Error: HTTP status code " + CString(http_code));
  1645. }
  1646. #else
  1647. // Create the socket connection, write to it, and add it to the queue
  1648. CPushSocket *sock = new CPushSocket(this);
  1649. sock->Connect(service_host, use_port, use_ssl);
  1650. sock->Request(use_post, service_host, service_url, params, service_auth);
  1651. AddSocket(sock);
  1652. #endif
  1653. PutModule("Ok");
  1654. }
  1655. // SEND command
  1656. else if (action == "send")
  1657. {
  1658. CString message = command.Token(1, true, " ", true);
  1659. send_message(message);
  1660. PutModule("Ok");
  1661. }
  1662. // HELP command
  1663. else if (action == "help")
  1664. {
  1665. PutModule("View the detailed documentation at https://github.com/jreese/znc-push/blob/master/README.md");
  1666. }
  1667. // VERSION command
  1668. else if (action == "version")
  1669. {
  1670. PutModule("znc-push " + CString(PUSHVERSION));
  1671. }
  1672. // EVAL command
  1673. else if (action == "eval")
  1674. {
  1675. CString value = command.Token(1, true, " ");
  1676. PutModule(eval(value) ? "true" : "false");
  1677. }
  1678. else
  1679. {
  1680. PutModule("Error: invalid command, try `help`");
  1681. }
  1682. }
  1683. };
  1684. /**
  1685. * Build a query string from a dictionary of request parameters.
  1686. *
  1687. * @param params Request parameters
  1688. * @return query string
  1689. */
  1690. CString build_query_string(MCString& params)
  1691. {
  1692. bool more = false;
  1693. CString query;
  1694. CString key;
  1695. CString value;
  1696. for (MCString::iterator param = params.begin(); param != params.end(); param++)
  1697. {
  1698. key = urlencode(param->first);
  1699. value = urlencode(param->second);
  1700. if (more)
  1701. {
  1702. query += "&" + key + "=" + value;
  1703. }
  1704. else
  1705. {
  1706. query += key + "=" + value;
  1707. more = true;
  1708. }
  1709. }
  1710. return query;
  1711. }
  1712. #ifdef USE_CURL
  1713. /**
  1714. * Send an HTTP request using libcurl.
  1715. *
  1716. * @param service_host Host domain
  1717. * @param service_url Host path
  1718. * @param service_auth Basic auth string
  1719. * @param params Request parameters
  1720. * @param port Port number
  1721. * @param use_ssl Use SSL
  1722. * @param use_post Use POST method
  1723. */
  1724. long make_curl_request(const CString& service_host, const CString& service_url,
  1725. const CString& service_auth, MCString& params, int port,
  1726. bool use_ssl, bool use_post,
  1727. const CString& proxy, bool proxy_ssl_verify,
  1728. bool debug)
  1729. {
  1730. CURL *curl;
  1731. CURLcode result;
  1732. long http_code;
  1733. curl = curl_easy_init();
  1734. CString user_agent = "ZNC Push/" + CString(PUSHVERSION);
  1735. CString url = CString(use_ssl ? "https" : "http") + "://" + service_host + service_url;
  1736. CString query = build_query_string(params);
  1737. if (!query.empty())
  1738. {
  1739. url = url + "?" + query;
  1740. }
  1741. if (debug)
  1742. {
  1743. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1744. }
  1745. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
  1746. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
  1747. curl_easy_setopt(curl, CURLOPT_URL, url.data());
  1748. curl_easy_setopt(curl, CURLOPT_PORT, port);
  1749. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());
  1750. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); // three seconds ought to be good enough for anyone, eh?
  1751. if (service_auth != "")
  1752. {
  1753. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  1754. curl_easy_setopt(curl, CURLOPT_USERPWD, service_auth.data());
  1755. }
  1756. if (use_post)
  1757. {
  1758. curl_easy_setopt(curl, CURLOPT_POST, 1);
  1759. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query.data());
  1760. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, query.length());
  1761. }
  1762. if (proxy != "") {
  1763. curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str());
  1764. if (!proxy_ssl_verify) {
  1765. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1766. }
  1767. }
  1768. result = curl_easy_perform(curl);
  1769. if (result != CURLE_OK) {
  1770. curl_easy_cleanup(curl);
  1771. return -1;
  1772. }
  1773. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
  1774. curl_easy_cleanup(curl);
  1775. return http_code;
  1776. }
  1777. #else
  1778. /**
  1779. * Send an HTTP request.
  1780. *
  1781. * @param post POST command
  1782. * @param host Host domain
  1783. * @param url Resource path
  1784. * @param parameters Query parameters
  1785. * @param auth Basic authentication string
  1786. */
  1787. void CPushSocket::Request(bool post, const CString& host, const CString& url, MCString& parameters, const CString& auth)
  1788. {
  1789. parent->PutDebug("Building notification to " + host + url + "...");
  1790. CString query = build_query_string(parameters);
  1791. // Request headers and POST body
  1792. CString request;
  1793. if (post)
  1794. {
  1795. request += "POST " + url + " HTTP/1.1" + crlf;
  1796. request += "Content-Type: application/x-www-form-urlencoded" + crlf;
  1797. request += "Content-Length: " + CString(query.length()) + crlf;
  1798. }
  1799. else
  1800. {
  1801. request += "GET " + url + "?" + query + " HTTP/1.1" + crlf;
  1802. }
  1803. request += "Host: " + host + crlf;
  1804. request += "Connection: close" + crlf;
  1805. request += "User-Agent: " + user_agent + crlf;
  1806. parent->PutDebug("User-Agent: " + user_agent);
  1807. if (auth != "")
  1808. {
  1809. CString auth_b64 = auth.Base64Encode_n();
  1810. request += "Authorization: Basic " + auth_b64 + crlf;
  1811. parent->PutDebug("Authorization: Basic " + auth_b64);
  1812. }
  1813. request += crlf;
  1814. if (post)
  1815. {
  1816. request += query;
  1817. }
  1818. parent->PutDebug("Query string: " + query);
  1819. Write(request);
  1820. parent->PutDebug("Request sending");
  1821. }
  1822. /**
  1823. * Read each line of data returned from the HTTP request.
  1824. */
  1825. void CPushSocket::ReadLine(const CString& data)
  1826. {
  1827. if (first)
  1828. {
  1829. CString status = data.Token(1);
  1830. CString message = data.Token(2, true);
  1831. parent->PutDebug("Status: " + status);
  1832. parent->PutDebug("Message: " + message);
  1833. first = false;
  1834. }
  1835. else
  1836. {
  1837. parent->PutDebug("Data: " + data);
  1838. }
  1839. }
  1840. void CPushSocket::Disconnected()
  1841. {
  1842. parent->PutDebug("Disconnected.");
  1843. Close(CSocket::CLT_AFTERWRITE);
  1844. }
  1845. #endif // USE_CURL
  1846. template<> void TModInfo<CPushMod>(CModInfo& Info) {
  1847. Info.AddType(CModInfo::UserModule);
  1848. Info.SetWikiPage("push");
  1849. }
  1850. NETWORKMODULEDEFS(CPushMod, "Send highlights and personal messages to a push notification service")