push.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  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 a private message.
  1124. *
  1125. * @param nick Nick that sent the message
  1126. * @param message Message contents
  1127. */
  1128. EModRet OnPrivMsg(CNick& nick, CString& message)
  1129. {
  1130. if (notify_pm(nick, message))
  1131. {
  1132. CString title = "Private Message";
  1133. send_message(message, title, nick.GetNick(), nick);
  1134. }
  1135. return CONTINUE;
  1136. }
  1137. /**
  1138. * Handle a private action.
  1139. *
  1140. * @param nick Nick that sent the action
  1141. * @param message Message contents
  1142. */
  1143. EModRet OnPrivAction(CNick& nick, CString& message)
  1144. {
  1145. if (notify_pm(nick, message))
  1146. {
  1147. CString title = "Private Message";
  1148. send_message(message, title, nick.GetNick(), nick, "action");
  1149. }
  1150. return CONTINUE;
  1151. }
  1152. /**
  1153. * Handle a message sent by the user.
  1154. *
  1155. * @param target Target channel or nick
  1156. * @param message Message contents
  1157. */
  1158. EModRet OnUserMsg(CString& target, CString& message)
  1159. {
  1160. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1161. return CONTINUE;
  1162. }
  1163. /**
  1164. * Handle an action sent by the user.
  1165. *
  1166. * @param target Target channel or nick
  1167. * @param message Message contents
  1168. */
  1169. EModRet OnUserAction(CString& target, CString& message)
  1170. {
  1171. last_reply_time[target] = last_active_time[target] = idle_time = time(NULL);
  1172. return CONTINUE;
  1173. }
  1174. /**
  1175. * Handle the user joining a channel.
  1176. *
  1177. * @param channel Channel name
  1178. * @param key Channel key
  1179. */
  1180. EModRet OnUserJoin(CString& channel, CString& key)
  1181. {
  1182. idle_time = time(NULL);
  1183. return CONTINUE;
  1184. }
  1185. /**
  1186. * Handle the user parting a channel.
  1187. *
  1188. * @param channel Channel name
  1189. * @param message Part message
  1190. */
  1191. EModRet OnUserPart(CString& channel, CString& message)
  1192. {
  1193. idle_time = time(NULL);
  1194. return CONTINUE;
  1195. }
  1196. /**
  1197. * Handle the user setting the channel topic.
  1198. *
  1199. * @param channel Channel name
  1200. * @param topic Topic message
  1201. */
  1202. EModRet OnUserTopic(CString& channel, CString& topic)
  1203. {
  1204. idle_time = time(NULL);
  1205. return CONTINUE;
  1206. }
  1207. /**
  1208. * Handle the user requesting the channel topic.
  1209. *
  1210. * @param channel Channel name
  1211. */
  1212. EModRet OnUserTopicRequest(CString& channel)
  1213. {
  1214. idle_time = time(NULL);
  1215. return CONTINUE;
  1216. }
  1217. /**
  1218. * Handle direct commands to the *push virtual user.
  1219. *
  1220. * @param command Command string
  1221. */
  1222. void OnModCommand(const CString& command)
  1223. {
  1224. VCString tokens;
  1225. CString::size_type token_count = command.Split(" ", tokens, false);
  1226. if (token_count < 1)
  1227. {
  1228. return;
  1229. }
  1230. CString action = tokens[0].AsLower();
  1231. // SET command
  1232. if (action == "set")
  1233. {
  1234. if (token_count < 3)
  1235. {
  1236. PutModule("Usage: set <option> <value>");
  1237. return;
  1238. }
  1239. CString option = tokens[1].AsLower();
  1240. CString value = command.Token(2, true, " ");
  1241. MCString::iterator pos = options.find(option);
  1242. if (pos == options.end())
  1243. {
  1244. PutModule("Error: invalid option name");
  1245. }
  1246. else
  1247. {
  1248. value.Trim();
  1249. if (option == "channel_conditions" || option == "query_conditions")
  1250. {
  1251. if (value != "all")
  1252. {
  1253. eval(value);
  1254. }
  1255. }
  1256. else if (option == "service")
  1257. {
  1258. value.MakeLower();
  1259. if (value == "pushbullet")
  1260. {
  1261. PutModule("Note: Pushbullet requires setting both 'target' (to device id) and 'secret' (to api key) options");
  1262. }
  1263. else if (value == "boxcar")
  1264. {
  1265. PutModule("Note: Boxcar requires setting the 'username' option");
  1266. }
  1267. else if (value == "boxcar2")
  1268. {
  1269. PutModule("Note: Boxcar 2 requires setting the 'secret' option");
  1270. }
  1271. else if (value == "nma")
  1272. {
  1273. PutModule("Note: NMA requires setting the 'secret' option");
  1274. }
  1275. else if (value == "pushover")
  1276. {
  1277. PutModule("Note: Pushover requires setting both the 'username' (to user key) and the 'secret' (to application api key) option");
  1278. }
  1279. else if (value == "pushsafer")
  1280. {
  1281. PutModule("Note: Pushsafer requires setting the 'private or alias key' option");
  1282. }
  1283. else if (value == "pushalot")
  1284. {
  1285. PutModule("Note: Pushalot requires setting the 'secret' (to user key) (to authorization token) option");
  1286. }
  1287. else if (value == "prowl")
  1288. {
  1289. PutModule("Note: Prowl requires setting the 'secret' option");
  1290. }
  1291. else if (value == "igloo")
  1292. {
  1293. PutModule("Note: Igloo requires adding your devices with device1-5");
  1294. }
  1295. else if (value == "supertoasty")
  1296. {
  1297. PutModule("Note: Supertoasty requires setting the 'secret' option with device id");
  1298. }
  1299. else if (value == "url")
  1300. {
  1301. PutModule("Note: URL requires setting the 'message_uri' option with the full URL");
  1302. }
  1303. else if (value == "faast")
  1304. {
  1305. PutModule("Note: Faast requires setting the secret to your apikey");
  1306. }
  1307. else if (value == "nexmo")
  1308. {
  1309. 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");
  1310. }
  1311. else if (value == "slack")
  1312. {
  1313. PutModule("Note: Slack requires setting 'secret' (from webhook) and 'target' (channel or username), optional 'username' (bot name)");
  1314. }
  1315. else if (value == "discord")
  1316. {
  1317. PutModule("Note: Discord requires setting 'secret' (from webhook), optional 'username' (bot name)");
  1318. }
  1319. else if (value == "pushjet")
  1320. {
  1321. PutModule("Note: Pushjet requires setting 'secret' (service key) option");
  1322. }
  1323. else if (value == "telegram")
  1324. {
  1325. PutModule("Note: Telegram requires setting both the 'secret' (api key) and 'target' (chat_id)");
  1326. }
  1327. else
  1328. {
  1329. PutModule("Error: unknown service name");
  1330. return;
  1331. }
  1332. }
  1333. options[option] = value;
  1334. SetNV(option, options[option]);
  1335. PutModule("Ok");
  1336. }
  1337. }
  1338. // APPEND command
  1339. else if (action == "append")
  1340. {
  1341. if (token_count < 3)
  1342. {
  1343. PutModule("Usage: append <option> <value>");
  1344. return;
  1345. }
  1346. CString option = tokens[1].AsLower();
  1347. CString value = command.Token(2, true, " ");
  1348. MCString::iterator pos = options.find(option);
  1349. if (pos == options.end())
  1350. {
  1351. PutModule("Error: invalid option name");
  1352. }
  1353. else if (option == "service")
  1354. {
  1355. PutModule("Error: cannot append to this option");
  1356. }
  1357. else
  1358. {
  1359. options[option] += " " + value;
  1360. options[option].Trim();
  1361. SetNV(option, options[option]);
  1362. PutModule("Ok");
  1363. }
  1364. }
  1365. // PREPEND command
  1366. else if (action == "prepend")
  1367. {
  1368. if (token_count < 3)
  1369. {
  1370. PutModule("Usage: prepend <option> <value>");
  1371. return;
  1372. }
  1373. CString option = tokens[1].AsLower();
  1374. CString value = command.Token(2, true, " ");
  1375. MCString::iterator pos = options.find(option);
  1376. if (pos == options.end())
  1377. {
  1378. PutModule("Error: invalid option name");
  1379. }
  1380. else if (option == "service")
  1381. {
  1382. PutModule("Error: cannot prepend to this option");
  1383. }
  1384. else
  1385. {
  1386. options[option] = value + " " + options[option];
  1387. options[option].Trim();
  1388. SetNV(option, options[option]);
  1389. PutModule("Ok");
  1390. }
  1391. }
  1392. // UNSET command
  1393. else if (action == "unset")
  1394. {
  1395. if (token_count != 2)
  1396. {
  1397. PutModule("Usage: unset <option>");
  1398. return;
  1399. }
  1400. CString option = tokens[1].AsLower();
  1401. MCString::iterator pos = options.find(option);
  1402. if (pos == options.end())
  1403. {
  1404. PutModule("Error: invalid option name");
  1405. }
  1406. else
  1407. {
  1408. options[option] = defaults[option];
  1409. DelNV(option);
  1410. PutModule("Ok");
  1411. }
  1412. }
  1413. // GET command
  1414. else if (action == "get")
  1415. {
  1416. if (token_count > 2)
  1417. {
  1418. PutModule("Usage: get [<option>]");
  1419. return;
  1420. }
  1421. if (token_count < 2)
  1422. {
  1423. CTable table;
  1424. table.AddColumn("Option");
  1425. table.AddColumn("Value");
  1426. for (MCString::iterator i = options.begin(); i != options.end(); i++)
  1427. {
  1428. table.AddRow();
  1429. table.SetCell("Option", i->first);
  1430. table.SetCell("Value", i->second);
  1431. }
  1432. PutModule(table);
  1433. return;
  1434. }
  1435. CString option = tokens[1].AsLower();
  1436. MCString::iterator pos = options.find(option);
  1437. if (pos == options.end())
  1438. {
  1439. PutModule("Error: invalid option name");
  1440. }
  1441. else
  1442. {
  1443. PutModule(option + CString(": ") + options[option]);
  1444. }
  1445. }
  1446. // SAVE command
  1447. else if (action == "save")
  1448. {
  1449. if (token_count < 2)
  1450. {
  1451. PutModule("Usage: save <filepath>");
  1452. }
  1453. CString file_path = command.Token(1, true, " ");
  1454. int status = options.WriteToDisk(file_path);
  1455. if (status == MCString::MCS_SUCCESS)
  1456. {
  1457. PutModule("Options saved to " + file_path);
  1458. }
  1459. else
  1460. {
  1461. switch (status)
  1462. {
  1463. case MCString::MCS_EOPEN:
  1464. case MCString::MCS_EWRITE:
  1465. case MCString::MCS_EWRITEFIL:
  1466. PutModule("Failed to save options to " + file_path);
  1467. break;
  1468. default:
  1469. PutModule("Failure");
  1470. break;
  1471. }
  1472. }
  1473. }
  1474. // LOAD command
  1475. else if (action == "load")
  1476. {
  1477. if (token_count < 2)
  1478. {
  1479. PutModule("Usage: load <filename>");
  1480. }
  1481. CString file_path = command.Token(1, true, " ");
  1482. if (!CFile::Exists(file_path))
  1483. {
  1484. PutModule("File does not exist: " + file_path);
  1485. return;
  1486. }
  1487. int status = options.ReadFromDisk(file_path);
  1488. if (status == MCString::MCS_SUCCESS)
  1489. {
  1490. PutModule("Options loaded from " + file_path);
  1491. // Restore any defaults that aren't in the loaded dictionary,
  1492. // and save loaded options to ZNC's data store
  1493. for (MCString::iterator i = defaults.begin(); i != defaults.end(); i++)
  1494. {
  1495. CString option = i->first;
  1496. MCString::iterator pos = options.find(option);
  1497. if (pos == options.end())
  1498. {
  1499. options[option] = defaults[option];
  1500. DelNV(option);
  1501. }
  1502. else
  1503. {
  1504. SetNV(option, options[option]);
  1505. }
  1506. }
  1507. }
  1508. else
  1509. {
  1510. switch (status)
  1511. {
  1512. case MCString::MCS_EOPEN:
  1513. case MCString::MCS_EREADFIL:
  1514. PutModule("Failed to read options from " + file_path);
  1515. break;
  1516. default:
  1517. PutModule("Failure");
  1518. break;
  1519. }
  1520. }
  1521. }
  1522. // STATUS command
  1523. else if (action == "status")
  1524. {
  1525. CTable table;
  1526. table.AddColumn("Condition");
  1527. table.AddColumn("Status");
  1528. table.AddRow();
  1529. table.SetCell("Condition", "away");
  1530. table.SetCell("Status", GetNetwork()->IsIRCAway() ? "yes" : "no");
  1531. table.AddRow();
  1532. table.SetCell("Condition", "client_count");
  1533. table.SetCell("Status", CString(client_count()));
  1534. time_t now = time(NULL);
  1535. time_t ago = now - idle_time;
  1536. table.AddRow();
  1537. table.SetCell("Condition", "idle");
  1538. table.SetCell("Status", CString(ago) + " seconds");
  1539. table.AddRow();
  1540. table.SetCell("Condition", "network_blacklist");
  1541. // network_blacklist() is True if the network is not in a blacklist
  1542. table.SetCell("Status", network_blacklist() ? "no" : "yes");
  1543. if (token_count > 1)
  1544. {
  1545. CString context = tokens[1];
  1546. table.AddRow();
  1547. table.SetCell("Condition", "last_active");
  1548. if (last_active_time.count(context) < 1)
  1549. {
  1550. table.SetCell("Status", "n/a");
  1551. }
  1552. else
  1553. {
  1554. ago = now - last_active_time[context];
  1555. table.SetCell("Status", CString(ago) + " seconds");
  1556. }
  1557. table.AddRow();
  1558. table.SetCell("Condition", "last_notification");
  1559. if (last_notification_time.count(context) < 1)
  1560. {
  1561. table.SetCell("Status", "n/a");
  1562. }
  1563. else
  1564. {
  1565. ago = now - last_notification_time[context];
  1566. table.SetCell("Status", CString(ago) + " seconds");
  1567. }
  1568. table.AddRow();
  1569. table.SetCell("Condition", "replied");
  1570. table.SetCell("Status", replied(context) ? "yes" : "no");
  1571. }
  1572. PutModule(table);
  1573. }
  1574. // SUBSCRIBE command
  1575. else if (action == "subscribe")
  1576. {
  1577. // Set up the connection profile
  1578. CString service = options["service"];
  1579. bool use_post = true;
  1580. int use_port = 443;
  1581. bool use_ssl = true;
  1582. CString service_host;
  1583. CString service_url;
  1584. CString service_auth;
  1585. MCString params;
  1586. if (service == "boxcar")
  1587. {
  1588. if (options["username"] == "")
  1589. {
  1590. PutModule("Error: username not set");
  1591. return;
  1592. }
  1593. CString boxcar_api_key = "puSd2qp2gCDZO7nWkvb9";
  1594. service_host = "boxcar.io";
  1595. service_url = "/devices/providers/" + boxcar_api_key + "/notifications/subscribe";
  1596. params["email"] = options["username"];
  1597. }
  1598. else if (service == "airgram")
  1599. {
  1600. PutModule("Error: Airgram service shut down. Please configure a different notification provider.");
  1601. }
  1602. else
  1603. {
  1604. PutModule("Error: service does not support subscribe command");
  1605. return;
  1606. }
  1607. #ifdef USE_CURL
  1608. 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");
  1609. PutDebug("curl: HTTP status code " + CString(http_code));
  1610. if (!(http_code >= 200 && http_code < 300)) {
  1611. PutModule("Error: HTTP status code " + CString(http_code));
  1612. }
  1613. #else
  1614. // Create the socket connection, write to it, and add it to the queue
  1615. CPushSocket *sock = new CPushSocket(this);
  1616. sock->Connect(service_host, use_port, use_ssl);
  1617. sock->Request(use_post, service_host, service_url, params, service_auth);
  1618. AddSocket(sock);
  1619. #endif
  1620. PutModule("Ok");
  1621. }
  1622. // SEND command
  1623. else if (action == "send")
  1624. {
  1625. CString message = command.Token(1, true, " ", true);
  1626. send_message(message);
  1627. PutModule("Ok");
  1628. }
  1629. // HELP command
  1630. else if (action == "help")
  1631. {
  1632. PutModule("View the detailed documentation at https://github.com/jreese/znc-push/blob/master/README.md");
  1633. }
  1634. // VERSION command
  1635. else if (action == "version")
  1636. {
  1637. PutModule("znc-push " + CString(PUSHVERSION));
  1638. }
  1639. // EVAL command
  1640. else if (action == "eval")
  1641. {
  1642. CString value = command.Token(1, true, " ");
  1643. PutModule(eval(value) ? "true" : "false");
  1644. }
  1645. else
  1646. {
  1647. PutModule("Error: invalid command, try `help`");
  1648. }
  1649. }
  1650. };
  1651. /**
  1652. * Build a query string from a dictionary of request parameters.
  1653. *
  1654. * @param params Request parameters
  1655. * @return query string
  1656. */
  1657. CString build_query_string(MCString& params)
  1658. {
  1659. bool more = false;
  1660. CString query;
  1661. CString key;
  1662. CString value;
  1663. for (MCString::iterator param = params.begin(); param != params.end(); param++)
  1664. {
  1665. key = urlencode(param->first);
  1666. value = urlencode(param->second);
  1667. if (more)
  1668. {
  1669. query += "&" + key + "=" + value;
  1670. }
  1671. else
  1672. {
  1673. query += key + "=" + value;
  1674. more = true;
  1675. }
  1676. }
  1677. return query;
  1678. }
  1679. #ifdef USE_CURL
  1680. /**
  1681. * Send an HTTP request using libcurl.
  1682. *
  1683. * @param service_host Host domain
  1684. * @param service_url Host path
  1685. * @param service_auth Basic auth string
  1686. * @param params Request parameters
  1687. * @param port Port number
  1688. * @param use_ssl Use SSL
  1689. * @param use_post Use POST method
  1690. */
  1691. long make_curl_request(const CString& service_host, const CString& service_url,
  1692. const CString& service_auth, MCString& params, int port,
  1693. bool use_ssl, bool use_post,
  1694. const CString& proxy, bool proxy_ssl_verify,
  1695. bool debug)
  1696. {
  1697. CURL *curl;
  1698. CURLcode result;
  1699. long http_code;
  1700. curl = curl_easy_init();
  1701. CString user_agent = "ZNC Push/" + CString(PUSHVERSION);
  1702. CString url = CString(use_ssl ? "https" : "http") + "://" + service_host + service_url;
  1703. CString query = build_query_string(params);
  1704. if (!query.empty())
  1705. {
  1706. url = url + "?" + query;
  1707. }
  1708. if (debug)
  1709. {
  1710. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1711. }
  1712. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
  1713. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
  1714. curl_easy_setopt(curl, CURLOPT_URL, url.data());
  1715. curl_easy_setopt(curl, CURLOPT_PORT, port);
  1716. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent.c_str());
  1717. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); // three seconds ought to be good enough for anyone, eh?
  1718. if (service_auth != "")
  1719. {
  1720. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  1721. curl_easy_setopt(curl, CURLOPT_USERPWD, service_auth.data());
  1722. }
  1723. if (use_post)
  1724. {
  1725. curl_easy_setopt(curl, CURLOPT_POST, 1);
  1726. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query.data());
  1727. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, query.length());
  1728. }
  1729. if (proxy != "") {
  1730. curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str());
  1731. if (!proxy_ssl_verify) {
  1732. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1733. }
  1734. }
  1735. result = curl_easy_perform(curl);
  1736. if (result != CURLE_OK) {
  1737. curl_easy_cleanup(curl);
  1738. return -1;
  1739. }
  1740. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
  1741. curl_easy_cleanup(curl);
  1742. return http_code;
  1743. }
  1744. #else
  1745. /**
  1746. * Send an HTTP request.
  1747. *
  1748. * @param post POST command
  1749. * @param host Host domain
  1750. * @param url Resource path
  1751. * @param parameters Query parameters
  1752. * @param auth Basic authentication string
  1753. */
  1754. void CPushSocket::Request(bool post, const CString& host, const CString& url, MCString& parameters, const CString& auth)
  1755. {
  1756. parent->PutDebug("Building notification to " + host + url + "...");
  1757. CString query = build_query_string(parameters);
  1758. // Request headers and POST body
  1759. CString request;
  1760. if (post)
  1761. {
  1762. request += "POST " + url + " HTTP/1.1" + crlf;
  1763. request += "Content-Type: application/x-www-form-urlencoded" + crlf;
  1764. request += "Content-Length: " + CString(query.length()) + crlf;
  1765. }
  1766. else
  1767. {
  1768. request += "GET " + url + "?" + query + " HTTP/1.1" + crlf;
  1769. }
  1770. request += "Host: " + host + crlf;
  1771. request += "Connection: close" + crlf;
  1772. request += "User-Agent: " + user_agent + crlf;
  1773. parent->PutDebug("User-Agent: " + user_agent);
  1774. if (auth != "")
  1775. {
  1776. CString auth_b64 = auth.Base64Encode_n();
  1777. request += "Authorization: Basic " + auth_b64 + crlf;
  1778. parent->PutDebug("Authorization: Basic " + auth_b64);
  1779. }
  1780. request += crlf;
  1781. if (post)
  1782. {
  1783. request += query;
  1784. }
  1785. parent->PutDebug("Query string: " + query);
  1786. Write(request);
  1787. parent->PutDebug("Request sending");
  1788. }
  1789. /**
  1790. * Read each line of data returned from the HTTP request.
  1791. */
  1792. void CPushSocket::ReadLine(const CString& data)
  1793. {
  1794. if (first)
  1795. {
  1796. CString status = data.Token(1);
  1797. CString message = data.Token(2, true);
  1798. parent->PutDebug("Status: " + status);
  1799. parent->PutDebug("Message: " + message);
  1800. first = false;
  1801. }
  1802. else
  1803. {
  1804. parent->PutDebug("Data: " + data);
  1805. }
  1806. }
  1807. void CPushSocket::Disconnected()
  1808. {
  1809. parent->PutDebug("Disconnected.");
  1810. Close(CSocket::CLT_AFTERWRITE);
  1811. }
  1812. #endif // USE_CURL
  1813. template<> void TModInfo<CPushMod>(CModInfo& Info) {
  1814. Info.AddType(CModInfo::UserModule);
  1815. Info.SetWikiPage("push");
  1816. }
  1817. NETWORKMODULEDEFS(CPushMod, "Send highlights and personal messages to a push notification service")