core.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. /*
  2. * sapphire-backend
  3. *
  4. * Copyright (C) 2018 Alyssa Rosenzweig
  5. * Copyright (C) 2018 libpurple authors
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
  20. *
  21. */
  22. #include <stdint.h>
  23. #include "purple.h"
  24. #include <assert.h>
  25. #include <glib.h>
  26. #include <signal.h>
  27. #include <string.h>
  28. #ifndef _WIN32
  29. #include <unistd.h>
  30. #else
  31. #include "win32/win32dep.h"
  32. #endif
  33. #include "core.h"
  34. #include "websocket.h"
  35. #include "event-loop.h"
  36. #include "json_compat.h"
  37. #define PLUGIN_SAVE_PREF "/purple/sapphire/plugins/saved"
  38. #define SAPPHIRE_PASSWORD_PREF "/purple/sapphire/password"
  39. #define UI_ID "sapphire"
  40. #define purple_serv_send_typing serv_send_typing
  41. #define purple_serv_join_chat serv_join_chat
  42. /* List of connected accounts */
  43. GSList *purple_accounts;
  44. /* List of SapphireChats, whether they are conversations yet or not */
  45. GSList *chats;
  46. /* Hash table of channel IDs to lists of unacked messages ready for replay */
  47. GHashTable *id_to_unacked_list;
  48. /* Hash table of chat IDs to PurpleChats */
  49. GHashTable *id_to_chat;
  50. /* Account ID to PurpleAccount */
  51. GHashTable *id_to_account;
  52. /* Blist Chat ID set */
  53. GHashTable *id_to_joined;
  54. /* All known buddies/other users are maintained in a hash table from network
  55. * serializable identifier to PurpleBuddy, since we can't transmit the buddy
  56. * object itself each time, this enables pass-by-reference */
  57. GHashTable *id_to_buddy;
  58. GHashTable *blist_id_to_conversation;
  59. gboolean sapphire_any_connected_clients = FALSE;
  60. /* Our internal tracking for chats, whether they are joined as
  61. * PurpleConversations or not. Smoothes over PurpleChat, PurpleConversation,
  62. * and room lists */
  63. typedef struct {
  64. const char *id; /* Unique, prpl-agnostic ID */
  65. const char *account_id; /* Account ID corresponding to account */
  66. const char *name; /* User visible name */
  67. const char *group; /* Group name, like from the blist */
  68. PurpleAccount *account;
  69. /* Bits needed to join, if roomlist */
  70. PurpleRoomlist *roomlist;
  71. PurpleRoomlistRoom *room;
  72. /* Corresponding conversation, if we have joined */
  73. PurpleConversation *conv;
  74. } SapphireChat;
  75. static gchar *
  76. sapphire_serialize_account_id(PurpleAccount *account);
  77. /* Creates a new heap-allocated SapphireChat. Must be freed later. */
  78. static SapphireChat *
  79. sapphire_new_chat(PurpleAccount *account, const char *id, const char *name, const char *group)
  80. {
  81. SapphireChat *schat = g_new0(SapphireChat, 1);
  82. schat->id = id;
  83. schat->account = account;
  84. schat->account_id = sapphire_serialize_account_id(account);
  85. schat->name = g_strdup(name);
  86. schat->group = g_strdup(group);
  87. return schat;
  88. }
  89. static gchar *
  90. sapphire_id_from_conv(PurpleConversation *chat);
  91. static SapphireChat *
  92. sapphire_chat_from_conv(PurpleConversation *conv)
  93. {
  94. return sapphire_new_chat(
  95. purple_conversation_get_account(conv),
  96. sapphire_id_from_conv(conv),
  97. purple_conversation_get_name(conv),
  98. "Chats");
  99. }
  100. /* Functions to upload icons to the proxy */
  101. GHashTable *sent_icons;
  102. static void
  103. sapphire_send_icon(const gchar *name, const gchar *ext, gconstpointer data, size_t size, const gchar *hash)
  104. {
  105. if (purple_strequal(g_hash_table_lookup(sent_icons, name), hash)) {
  106. /* Don't duplicate. */
  107. return;
  108. }
  109. /* If there is an active connection, send this icon. Otherwise, save
  110. * it to be sent later */
  111. gchar *base64 = g_base64_encode(data, size);
  112. JsonObject *obj = json_object_new();
  113. json_object_set_string_member(obj, "op", "icon");
  114. json_object_set_string_member(obj, "name", name);
  115. json_object_set_string_member(obj, "ext", ext);
  116. json_object_set_string_member(obj, "base64", base64);
  117. gchar *str = json_object_to_string(obj);
  118. gchar *str_prefixed = g_strdup_printf(">%s", str);
  119. /* Assume that it needs to save the string. Callee will g_free it itself in the off-chance it doesn't need it anymore */
  120. sapphire_send_raw_packet(str_prefixed);
  121. /* Mark that the icon is sent so we don't try later */
  122. g_hash_table_insert(sent_icons, g_strdup(name), g_strdup(hash));
  123. g_free(str);
  124. g_free(str_prefixed);
  125. g_free(base64);
  126. json_object_unref(obj);
  127. }
  128. void
  129. sapphire_add_buddy_icon(const gchar *name, PurpleBuddyIcon *icon)
  130. {
  131. size_t size;
  132. gconstpointer data = purple_buddy_icon_get_data(icon, &size);
  133. sapphire_send_icon(name, purple_buddy_icon_get_extension(icon), data, size, purple_buddy_icon_get_checksum(icon));
  134. }
  135. void
  136. sapphire_add_stored_image(const gchar *name, PurpleStoredImage *icon)
  137. {
  138. sapphire_send_icon(name, purple_imgstore_get_extension(icon), purple_imgstore_get_data(icon), purple_imgstore_get_size(icon), purple_imgstore_get_filename(icon));
  139. }
  140. /* Generic purple related helpers */
  141. static PurpleStatus *
  142. sapphire_status_for_buddy(PurpleBuddy *buddy)
  143. {
  144. PurplePresence *presence = purple_buddy_get_presence(buddy);
  145. return purple_presence_get_active_status(presence);
  146. }
  147. static PurplePluginProtocolInfo *
  148. sapphire_info_for_connection(PurpleConnection *connection)
  149. {
  150. PurplePlugin *prpl = purple_connection_get_prpl(connection);
  151. return PURPLE_PLUGIN_PROTOCOL_INFO(prpl);
  152. }
  153. static PurpleConvIm *
  154. sapphire_im_for_name(PurpleAccount *account, const char *name)
  155. {
  156. PurpleConversation *conv = purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM, name, account);
  157. if (conv == NULL) {
  158. /* If not found, create it */
  159. conv = purple_conversation_new(PURPLE_CONV_TYPE_IM, account, name);
  160. }
  161. return purple_conversation_get_im_data(conv);
  162. }
  163. /* Search for a PurpleConversation, either as a chat or an IM. Returns NULL if
  164. * not found */
  165. static PurpleConversation *
  166. sapphire_conversation_for_id(const gchar *id)
  167. {
  168. PurpleConversation *as_chat = g_hash_table_lookup(blist_id_to_conversation, id);
  169. if (as_chat)
  170. return as_chat;
  171. PurpleBuddy *buddy = g_hash_table_lookup(id_to_buddy, id);
  172. if (buddy) {
  173. PurpleAccount *account = purple_buddy_get_account(buddy);
  174. const gchar *name = purple_buddy_get_name(buddy);
  175. return purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM, name, account);
  176. }
  177. return NULL;
  178. }
  179. /* Helper to serialize and broadcast */
  180. static void
  181. sapphire_send(JsonObject *msg)
  182. {
  183. gchar *str = json_object_to_string(msg);
  184. sapphire_send_raw_packet(str);
  185. g_free(str);
  186. }
  187. static PurpleTypingState
  188. sapphire_decode_typing_state(int s_state);
  189. static PurpleConversation *
  190. sapphire_find_conversation(const gchar *chat);
  191. static JsonArray *
  192. sapphire_serialize_chat_users(SapphireChat *chat);
  193. static PurpleBuddy *
  194. sapphire_decode_buddy(JsonObject *data)
  195. {
  196. const gchar *buddy_id = json_object_get_string_member(data, "buddy");
  197. if (!buddy_id)
  198. return NULL;
  199. /* Find the associated buddy */
  200. PurpleBuddy *buddy = g_hash_table_lookup(id_to_buddy, buddy_id);
  201. if (!buddy) {
  202. fprintf(stderr, "Bad buddy id %s\n", buddy_id);
  203. return NULL;
  204. }
  205. return buddy;
  206. }
  207. static PurpleAccount *
  208. sapphire_decode_account(JsonObject *data)
  209. {
  210. const gchar *account_id = json_object_get_string_member(data, "account");
  211. return g_hash_table_lookup(id_to_account, account_id);
  212. }
  213. void
  214. sapphire_push_connected(void);
  215. void
  216. sapphire_process_message(Connection *conn, JsonObject *data)
  217. {
  218. const gchar *op = json_object_get_string_member(data, "op");
  219. if (purple_strequal(op, "world")) {
  220. /* Proxy asking for a copy of the world */
  221. /* We now know someone is listening */
  222. sapphire_any_connected_clients = TRUE;
  223. /* Flag the new connection in the push notification module */
  224. sapphire_push_connected();
  225. /* Setup accounts if needed */
  226. sapphire_enable_accounts_by_connections();
  227. /* Send the world itself */
  228. sapphire_send_world(conn);
  229. } else if (purple_strequal(op, "ghost")) {
  230. /* Proxy informing us we've been ghosted */
  231. sapphire_any_connected_clients = FALSE;
  232. } else if (purple_strequal(op, "message")) {
  233. /* Send an outgoing IM */
  234. const gchar *content = json_object_get_string_member(data, "content");
  235. /* Content is HTML, possibly OTR-encrypted so we can't do processing */
  236. gchar *marked = g_strdup(content);
  237. if (json_object_has_member(data, "buddy")) {
  238. PurpleBuddy *buddy = sapphire_decode_buddy(data);
  239. PurpleAccount *buddy_account = purple_buddy_get_account(buddy);
  240. const gchar *buddy_name = purple_buddy_get_name(buddy);
  241. purple_conv_im_send(sapphire_im_for_name(buddy_account, buddy_name), marked);
  242. } else if (json_object_has_member(data, "chat")) {
  243. const gchar *chat = json_object_get_string_member(data, "chat");
  244. PurpleConversation *conv = sapphire_find_conversation(chat);
  245. PurpleConvChat *conv_chat = purple_conversation_get_chat_data(conv);
  246. purple_conv_chat_send(conv_chat, marked);
  247. } else {
  248. fprintf(stderr, "No recipient specified in message\n");
  249. return;
  250. }
  251. g_free(marked);
  252. } else if (purple_strequal(op, "typing")) {
  253. /* Our buddy typing status changed */
  254. int s_state = json_object_get_int_member(data, "state");
  255. PurpleTypingState state = sapphire_decode_typing_state(s_state);
  256. PurpleBuddy *buddy = sapphire_decode_buddy(data);
  257. if (!buddy) {
  258. fprintf(stderr, "No buddy\n");
  259. return;
  260. }
  261. PurpleAccount *buddy_account = purple_buddy_get_account(buddy);
  262. const gchar *buddy_name = purple_buddy_get_name(buddy);
  263. PurpleConnection *connection = purple_account_get_connection(buddy_account);
  264. purple_serv_send_typing(connection, buddy_name, state);
  265. } else if (purple_strequal(op, "joinChat")) {
  266. /* Join a MUC */
  267. const gchar *id = json_object_get_string_member(data, "id");
  268. SapphireChat *chat = g_hash_table_lookup(id_to_chat, id);
  269. if (!chat) {
  270. printf("Chat not found %s\n", id);
  271. return;
  272. }
  273. gboolean is_subscribed = g_hash_table_contains(conn->subscribed_ids, id);
  274. if (g_hash_table_contains(id_to_joined, id)) {
  275. purple_roomlist_room_join(chat->roomlist, chat->room);
  276. g_hash_table_add(id_to_joined, g_strdup(id));
  277. } else if (!is_subscribed) {
  278. /* If we already joined but not in this connection, just send back details */
  279. const gchar *topic = purple_conv_chat_get_topic(PURPLE_CONV_CHAT(chat->conv));
  280. JsonArray *users = sapphire_serialize_chat_users(chat);
  281. JsonObject *data = json_object_new();
  282. json_object_set_string_member(data, "op", "joined");
  283. json_object_set_string_member(data, "chat", id);
  284. json_object_set_string_member(data, "topic", topic);
  285. json_object_set_array_member(data, "members", users);
  286. sapphire_send(data);
  287. json_object_unref(data);
  288. }
  289. if (!is_subscribed) {
  290. /* We want to know about this room */
  291. g_hash_table_add(conn->subscribed_ids, g_strdup(id));
  292. }
  293. } else if (purple_strequal(op, "topic")) {
  294. const gchar *chat = json_object_get_string_member(data, "chat");
  295. const gchar *topic = json_object_get_string_member(data, "topic");
  296. PurpleConversation *conv = g_hash_table_lookup(blist_id_to_conversation, chat);
  297. PurpleConvChat *conv_chat = purple_conversation_get_chat_data(conv);
  298. int id = purple_conv_chat_get_id(conv_chat);
  299. PurpleAccount *account = purple_conversation_get_account(conv);
  300. PurpleConnection *connection = purple_account_get_connection(account);
  301. PurplePluginProtocolInfo *prpl_info = sapphire_info_for_connection(connection);
  302. if (prpl_info && prpl_info->set_chat_topic)
  303. prpl_info->set_chat_topic(connection, id, topic);
  304. else
  305. fprintf(stderr, "Set chat topic unimplemented\n");
  306. } else if (purple_strequal(op, "markAsRead")) {
  307. const gchar *id = json_object_get_string_member(data, "id");
  308. /* Free the unacked list entries */
  309. GList *unacked_list = g_hash_table_lookup(id_to_unacked_list, id);
  310. for (GList *it = unacked_list; it != NULL; it = it->next) {
  311. JsonObject *msg = (JsonObject *) it->data;
  312. json_object_unref(msg);
  313. }
  314. /* Free the list itself */
  315. g_list_free(unacked_list);
  316. /* And remove it from the hash table */
  317. g_hash_table_remove(id_to_unacked_list, id);
  318. /* Fake a PURPLE_CONV_UPDATE_UNSEEN signal, so that the room gets
  319. * marked as read.
  320. */
  321. PurpleConversation *conv = sapphire_conversation_for_id(id);
  322. if (!conv) {
  323. fprintf(stderr, "Conversation not found in markAsRead %s\n", id);
  324. return;
  325. }
  326. purple_conversation_update(conv, PURPLE_CONV_UPDATE_UNSEEN);
  327. } else if (purple_strequal(op, "requestBuddy")) {
  328. /* Request to add a buddy */
  329. const gchar *id = json_object_get_string_member(data, "id");
  330. const gchar *alias = json_object_get_string_member(data, "alias");
  331. const gchar *invite = json_object_get_string_member(data, "invite");
  332. PurpleAccount *account = sapphire_decode_account(data);
  333. PurpleBuddy *buddy = purple_buddy_new(account, id, alias);
  334. purple_blist_add_buddy(buddy, NULL, NULL, NULL);
  335. purple_account_add_buddy_with_invite(account, buddy, invite);
  336. } else if (purple_strequal(op, "changeAvatar")) {
  337. /* Request to change our avatar */
  338. PurpleAccount *account = sapphire_decode_account(data);
  339. const gchar *base64 = json_object_get_string_member(data, "base64");
  340. size_t len;
  341. guchar *l_data = g_base64_decode(base64, &len);
  342. PurpleStoredImage *icon = purple_buddy_icons_set_account_icon(account, l_data, len);
  343. /* Update the cache */
  344. const gchar *raw_acct = json_object_get_string_member(data, "account");
  345. sapphire_add_stored_image(raw_acct, icon);
  346. /* Respond that we did it! */
  347. JsonObject *resp = json_object_new();
  348. json_object_set_string_member(resp, "op", "changeAvatar");
  349. json_object_set_string_member(resp, "id", raw_acct);
  350. sapphire_send(resp);
  351. json_object_unref(resp);
  352. } else {
  353. fprintf(stderr, "Unknown op %s\n", op);
  354. }
  355. }
  356. /*** Conversation uiops ***/
  357. static gchar *
  358. sapphire_id_from_parts(PurpleAccount *account, const gchar *id);
  359. static void
  360. sapphire_signed_on(PurpleAccount *account, gpointer null)
  361. {
  362. PurpleConnection *connection = purple_account_get_connection(account);
  363. /* Upsert the account ID */
  364. gchar *acct_id = sapphire_serialize_account_id(account);
  365. if (g_hash_table_contains(id_to_account, acct_id)) {
  366. /* Wait. We already did this account. Bail! TODO: Sync */
  367. g_free(acct_id);
  368. return;
  369. }
  370. g_hash_table_insert(id_to_account, acct_id, account);
  371. /* For type-1 prpls where the openness of a chat determines whether we
  372. * receive events (e.g. IRC), open up all chats as early as possible */
  373. PurpleBlistNode *node;
  374. for ( node = purple_blist_get_root();
  375. node != NULL;
  376. node = purple_blist_node_next(node, TRUE)) {
  377. if (PURPLE_BLIST_NODE_IS_CHAT(node)) {
  378. PurpleChat *chat = PURPLE_CHAT(node);
  379. if (purple_chat_get_account(chat) != account) continue;
  380. GHashTable *components = purple_chat_get_components(chat);
  381. purple_serv_join_chat(connection, components);
  382. }
  383. }
  384. /* For type-2 prpls where we fetch from the room list (e.g. Discord),
  385. * fetch now but do not open yet, since we don't want to spam the
  386. * servers */
  387. if (purple_strequal(account->protocol_id, "prpl-eionrobb-discord")) {
  388. PurpleRoomlist *roomlist = purple_roomlist_get_list(connection);
  389. /* We're persisting the roomlist until later */
  390. purple_roomlist_ref(roomlist);
  391. gboolean in_progress = purple_roomlist_get_in_progress(roomlist);
  392. if (in_progress) {
  393. fprintf(stderr, "In progress room list, aborting\n");
  394. return;
  395. }
  396. /* Check the field headings to figure out what to display (name) and index by (ID) */
  397. GList *field_headings = purple_roomlist_get_fields(roomlist);
  398. int index_id = -1, index_name = -1;
  399. int field_idx = 0;
  400. for (; field_headings != NULL; field_headings = field_headings->next, ++field_idx) {
  401. PurpleRoomlistField *field = (PurpleRoomlistField *) field_headings->data;
  402. const char *label = purple_roomlist_field_get_label(field);
  403. gboolean hidden = purple_roomlist_field_get_hidden(field);
  404. if (index_id == -1 && hidden) {
  405. index_id = field_idx;
  406. } else if (index_name == -1 && purple_strequal(label, "Name")) {
  407. index_name = field_idx;
  408. } else {
  409. /* Useless field */
  410. }
  411. }
  412. /* Now, scan the rooms */
  413. GList *rooms = roomlist->rooms; /* XXX: purple3 */
  414. for (; rooms != NULL; rooms = rooms->next) {
  415. PurpleRoomlistRoom *room = (PurpleRoomlistRoom *) rooms->data;
  416. PurpleRoomlistRoomType type = purple_roomlist_room_get_type(room);
  417. /* Skip over categories */
  418. if (type != PURPLE_ROOMLIST_ROOMTYPE_ROOM)
  419. continue;
  420. /* ...but do fetch our category name! */
  421. PurpleRoomlistRoom *parent = purple_roomlist_room_get_parent(room);
  422. const char *group_name = parent ? purple_roomlist_room_get_name(parent) : "Rooms";
  423. GList *fields = purple_roomlist_room_get_fields(room);
  424. const char *id = NULL;
  425. const char *display_name = NULL;
  426. for (int idx = 0; fields != NULL; fields = fields->next, ++idx) {
  427. gchar *value = (gchar *) fields->data;
  428. if (idx == index_id)
  429. id = value;
  430. if (idx == index_name)
  431. display_name = value;
  432. }
  433. /* XXX: Do magic from purple-discord to format ID */
  434. guint64 gid = g_ascii_strtoull(id, NULL, 10);
  435. int nid = ABS((gint) gid);
  436. gchar *snid = g_strdup_printf("%d", nid);
  437. gchar *sapphic_id = sapphire_id_from_parts(account, snid);
  438. g_free(snid);
  439. /* Save the chat */
  440. SapphireChat *schat = sapphire_new_chat(account, g_strdup(sapphic_id), display_name, group_name);
  441. schat->roomlist = roomlist;
  442. schat->room = room;
  443. chats = g_slist_prepend(chats, schat);
  444. /* No need to g_strdup(sapphic_id) since we already have the exclusive reference */
  445. g_hash_table_insert(id_to_chat, sapphic_id, schat);
  446. }
  447. }
  448. }
  449. static void
  450. sapphire_account_enabled(PurpleAccount *account, gpointer null)
  451. {
  452. printf("Account enabled: %s %s\n", account->username, account->protocol_id);
  453. }
  454. /* Serializes the actual content of a status */
  455. static void
  456. sapphire_serialize_status(JsonObject *data, PurpleStatus *status)
  457. {
  458. JsonObject *obj = json_object_new();
  459. const gchar *id = purple_status_get_id(status);
  460. const gchar *name = purple_status_get_name(status);
  461. const gchar *message = purple_status_get_attr_string(status, "message");
  462. json_object_set_string_member(obj, "id", id);
  463. json_object_set_string_member(obj, "name", name);
  464. if (message != NULL)
  465. json_object_set_string_member(obj, "message", message);
  466. json_object_set_object_member(data, "status", obj);
  467. }
  468. /* Serializes a buddy "by reference", by hashing the buddy. Requires a
  469. * corresponding `buddy` op to be meaningful for the client. Requires
  470. * disambiguating by account, prpl, etc as well as just the name.
  471. * Simultaneously "upserts" the buddy into the global hash table for later
  472. * access.
  473. *
  474. * Result: serialized string, heap allocated. Must be g_free'd later.
  475. */
  476. static gchar *
  477. sapphire_serialize_user_id(PurpleAccount *account, const gchar *name)
  478. {
  479. const gchar *prpl = purple_account_get_protocol_id(account);
  480. const gchar *account_id = purple_account_get_username(account);
  481. /* Smush together the features into a unique ID. TODO: Hash */
  482. gchar *smushed = g_strdup_printf("%s|%s|%s", prpl, account_id, name);
  483. return smushed;
  484. }
  485. static gchar *
  486. sapphire_serialize_buddy_id(PurpleBuddy *buddy)
  487. {
  488. /* Get distinguishing features */
  489. PurpleAccount *p_account = purple_buddy_get_account(buddy);
  490. const gchar *name = purple_normalize(p_account, purple_buddy_get_name(buddy));
  491. gchar *smushed = sapphire_serialize_user_id(p_account, name);
  492. /* Upsert. TODO: Will PurpleBuddy get garbage collected on us? */
  493. if (!g_hash_table_lookup(id_to_buddy, smushed)) {
  494. g_hash_table_replace(id_to_buddy, g_strdup(smushed), buddy);
  495. }
  496. return smushed;
  497. }
  498. /* Resolve from bare nickname who to actual ID */
  499. static gchar *
  500. sapphire_serialize_chat_user_id(PurpleConversation *conv, const gchar *who)
  501. {
  502. PurpleAccount *account = purple_conversation_get_account(conv);
  503. PurpleConnection *connection = purple_account_get_connection(account);
  504. PurplePluginProtocolInfo *prpl_info = sapphire_info_for_connection(connection);
  505. if (prpl_info && prpl_info->get_cb_real_name) {
  506. /* Get the user's intra-protocol canonical name */
  507. PurpleConvChat *conv_chat = purple_conversation_get_chat_data(conv);
  508. int id = purple_conv_chat_get_id(conv_chat);
  509. gchar *real_name = prpl_info->get_cb_real_name(connection, id, who);
  510. gchar *normalized = g_strdup(purple_normalize(account, real_name));
  511. /* Check if it's, uh, us */
  512. const char *username = purple_normalize(account, purple_account_get_username(account));
  513. const char *display_name = purple_connection_get_display_name(connection);
  514. if (purple_strequal(username, normalized) || purple_strequal(display_name, normalized)) {
  515. g_free(normalized);
  516. return sapphire_serialize_account_id(account);
  517. }
  518. /* Serialize it formally for protocol independence */
  519. gchar *out = sapphire_serialize_user_id(account, normalized);
  520. g_free(normalized);
  521. g_free(real_name);
  522. return out;
  523. } else {
  524. printf("Bailing on %s\n", who);
  525. return g_strdup(who);
  526. }
  527. }
  528. static void
  529. sapphire_serialize_buddy(JsonObject *data, PurpleBuddy *buddy)
  530. {
  531. gchar *id = sapphire_serialize_buddy_id(buddy);
  532. json_object_set_string_member(data, "buddy", id);
  533. g_free(id);
  534. }
  535. static void
  536. sapphire_serialize_chat_buddy(JsonObject *data, PurpleConversation *conv, const char *who, PurpleConvChatBuddyFlags flags)
  537. {
  538. gchar *user_id = sapphire_serialize_chat_user_id(conv, who);
  539. json_object_set_string_member(data, "id", user_id);
  540. json_object_set_string_member(data, "alias", who);
  541. json_object_set_int_member(data, "flags", flags);
  542. g_free(user_id);
  543. }
  544. /* Add missed messages to buddy/chat object if applicable */
  545. static void
  546. sapphire_serialize_unacked_messages(JsonObject *obj, const gchar *id)
  547. {
  548. GList *lst = g_hash_table_lookup(id_to_unacked_list, id);
  549. if (!lst)
  550. return;
  551. /* Pop missed messages in reverse order */
  552. GList *it;
  553. JsonArray *unacked = json_array_new();
  554. for (it = lst; it != NULL; it = it->next) {
  555. JsonObject *msg = (JsonObject *) it->data;
  556. json_array_add_object_element(unacked, msg);
  557. }
  558. json_object_set_array_member(obj, "unacked", unacked);
  559. }
  560. static JsonArray *
  561. sapphire_serialize_chat_users(SapphireChat *chat)
  562. {
  563. JsonArray *jusers = json_array_new();
  564. if (chat->conv) {
  565. PurpleConvChat *conv_chat = purple_conversation_get_chat_data(chat->conv);
  566. for (GList *l = purple_conv_chat_get_users(conv_chat); l != NULL; l = l->next) {
  567. JsonObject *juser = json_object_new();
  568. PurpleConvChatBuddy *cb = (PurpleConvChatBuddy *) l->data;
  569. const gchar *who = purple_conv_chat_cb_get_name(cb);
  570. PurpleConvChatBuddyFlags flags = purple_conv_chat_user_get_flags(conv_chat, who);
  571. sapphire_serialize_chat_buddy(juser, chat->conv, who, flags);
  572. json_array_add_object_element(jusers, juser);
  573. }
  574. }
  575. return jusers;
  576. }
  577. /* Serializes the unopened chat pieces, not the conversation bits which have a
  578. * rather more complex path */
  579. static JsonObject *
  580. sapphire_serialize_chat(SapphireChat *chat)
  581. {
  582. JsonObject *obj = json_object_new();
  583. json_object_set_string_member(obj, "id", chat->id);
  584. json_object_set_string_member(obj, "name", chat->name);
  585. json_object_set_string_member(obj, "group", chat->group);
  586. json_object_set_string_member(obj, "account", chat->account_id);
  587. sapphire_serialize_unacked_messages(obj, chat->id);
  588. return obj;
  589. }
  590. /* Creates pass-by-reference ID for account.
  591. *
  592. * Return: ID as a string (must be freed by caller)
  593. */
  594. static gchar *
  595. sapphire_serialize_account_id(PurpleAccount *account)
  596. {
  597. /* Get features */
  598. const gchar *prpl = purple_account_get_protocol_id(account);
  599. const gchar *username = purple_account_get_username(account);
  600. /* Smush prpl with username to form an ID */
  601. return g_strdup_printf("%s|%s", prpl, username);
  602. }
  603. /* Serialize actual chat ID */
  604. static gchar *
  605. sapphire_id_from_conv(PurpleConversation *chat)
  606. {
  607. PurpleAccount *account = purple_conversation_get_account(chat);
  608. gchar *acct = sapphire_serialize_account_id(account);
  609. PurpleConvChat *conv_chat = purple_conversation_get_chat_data(chat);
  610. int id = purple_conv_chat_get_id(conv_chat);
  611. gchar *full_id = g_strdup_printf("%s|%d", acct, id);
  612. g_free(acct);
  613. return full_id;
  614. }
  615. /* Find a chat by ID */
  616. static SapphireChat *
  617. sapphire_find_chat(const gchar *id, gboolean use_id)
  618. {
  619. for (GSList *it = chats; it != NULL; it = it->next) {
  620. SapphireChat *candidate = (SapphireChat *) it->data;
  621. gboolean match = FALSE;
  622. if (use_id) {
  623. match = purple_strequal(candidate->id, id);
  624. } else if (candidate->conv) {
  625. /* Ignore the provided ID and compute it ourselves */
  626. gchar *chat = sapphire_id_from_conv(candidate->conv);
  627. match = purple_strequal(id, chat);
  628. g_free(chat);
  629. } else {
  630. fprintf(stderr, "ERROR: ID ignored but NULL conv\n");
  631. return NULL;
  632. }
  633. if (match)
  634. return candidate;
  635. }
  636. return NULL;
  637. }
  638. /* Find conversation by ID, the fast way or the slow way.. */
  639. static PurpleConversation *
  640. sapphire_find_conversation(const gchar *chat)
  641. {
  642. PurpleConversation *conv = g_hash_table_lookup(blist_id_to_conversation, chat);
  643. if (conv)
  644. return conv;
  645. /* Not in the hash table -- so iterate */
  646. SapphireChat *schat = sapphire_find_chat(chat, FALSE);
  647. return schat ? schat->conv : NULL;
  648. }
  649. static gchar *
  650. sapphire_id_from_parts(PurpleAccount *account, const gchar *id)
  651. {
  652. gchar *acct = sapphire_serialize_account_id(account);
  653. return g_strdup_printf("%s|%s", acct, id);
  654. }
  655. /* By contrast, this routine serializes a buddy by value, including the ID
  656. * generated by the previous function as well as the actual metadata */
  657. static JsonObject *
  658. sapphire_serialize_buddy_object(PurpleBuddy *buddy)
  659. {
  660. JsonObject *json = json_object_new();
  661. PurpleGroup *group = purple_buddy_get_group(buddy);
  662. const gchar *name = purple_buddy_get_name(buddy);
  663. const gchar *alias = purple_buddy_get_contact_alias(buddy);
  664. const gchar *group_name = purple_group_get_name(group);
  665. gchar *id = sapphire_serialize_buddy_id(buddy);
  666. /* We might have an icon. If so, get it ready for later access, but do
  667. * not send it here. Merely record if there is an icon or not */
  668. PurpleAccount *account = purple_buddy_get_account(buddy);
  669. PurpleBuddyIcon *icon = purple_buddy_icons_find(account, name);
  670. if (icon != NULL) {
  671. purple_buddy_icon_ref(icon);
  672. sapphire_add_buddy_icon(id, icon);
  673. }
  674. json_object_set_boolean_member(json, "hasIcon", icon != NULL);
  675. json_object_set_string_member(json, "id", id);
  676. json_object_set_string_member(json, "name", name);
  677. json_object_set_string_member(json, "alias", alias);
  678. json_object_set_string_member(json, "group", group_name);
  679. gchar *accountID = sapphire_serialize_account_id(account);
  680. if (accountID) {
  681. json_object_set_string_member(json, "account", accountID);
  682. g_free(accountID);
  683. }
  684. sapphire_serialize_status(json, sapphire_status_for_buddy(buddy));
  685. /* Include the ID of the buddy itself */
  686. sapphire_serialize_buddy(json, buddy);
  687. g_free(id);
  688. return json;
  689. }
  690. /* Serialize the account itself for personal information */
  691. static JsonObject *
  692. sapphire_serialize_account(PurpleAccount *account)
  693. {
  694. JsonObject *json = json_object_new();
  695. const gchar *prpl = purple_account_get_protocol_id(account);
  696. const gchar *prpl_name = purple_account_get_protocol_name(account);
  697. const gchar *username = purple_account_get_username(account);
  698. const gchar *alias = purple_account_get_alias(account);
  699. json_object_set_string_member(json, "prpl", prpl);
  700. json_object_set_string_member(json, "prplName", prpl_name);
  701. json_object_set_string_member(json, "name", username);
  702. json_object_set_string_member(json, "alias", alias);
  703. gchar *id = sapphire_serialize_account_id(account);
  704. json_object_set_string_member(json, "id", id);
  705. /* Add our own icon, if applicable, to the store */
  706. PurpleStoredImage *icon =
  707. purple_buddy_icons_find_account_icon(account);
  708. if (icon)
  709. sapphire_add_stored_image(id, icon);
  710. json_object_set_boolean_member(json, "hasIcon", icon != NULL);
  711. g_free(id);
  712. return json;
  713. }
  714. /* Sends the entire world to a new connection. For this, we need to send:
  715. *
  716. * - information about our accounts
  717. * - the buddy list
  718. * - rooms we're in
  719. * - missed messages
  720. *
  721. * Essentially, everything needed for the initial client render.
  722. *
  723. * We do _not_ need to send anything that's not immediately accessible; for
  724. * instance, we can avoid sending the users in present rooms that are not on
  725. * our buddy list, deferring to when we explicitly open the room
  726. *
  727. */
  728. void
  729. sapphire_send_world(Connection *conn)
  730. {
  731. /* Initialize connected state */
  732. conn->subscribed_ids = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  733. JsonObject *data = json_object_new();
  734. json_object_set_string_member(data, "op", "world");
  735. /* Iterate the buddy list of connected accounts to include buddies */
  736. JsonArray *jbuddies = json_array_new();
  737. JsonArray *jaccounts = json_array_new();
  738. JsonArray *jchats = json_array_new();
  739. GSList *acct;
  740. for (acct = purple_accounts; acct != NULL; acct = acct->next) {
  741. PurpleAccount *account = (PurpleAccount *) acct->data;
  742. /* Add buddies from account */
  743. GSList *blist = purple_find_buddies(account, NULL);
  744. for (GSList *it = blist; it != NULL; it = it->next) {
  745. PurpleBuddy *buddy = (PurpleBuddy *) it->data;
  746. JsonObject *bud = sapphire_serialize_buddy_object(buddy);
  747. const gchar *bid = json_object_get_string_member(bud, "buddy");
  748. sapphire_serialize_unacked_messages(bud, bid);
  749. json_array_add_object_element(jbuddies, bud);
  750. }
  751. /* Add metadata for the account itself */
  752. JsonObject *j_account = sapphire_serialize_account(account);
  753. json_array_add_object_element(jaccounts, j_account);
  754. g_slist_free(blist);
  755. }
  756. /* Send chats */
  757. for (GSList *it = chats; it != NULL; it = it->next) {
  758. SapphireChat *schat = (SapphireChat *) it->data;
  759. json_array_add_object_element(jchats, sapphire_serialize_chat(schat));
  760. }
  761. /* TODO: What if one is.. both? */
  762. json_object_set_array_member(data, "buddies", jbuddies);
  763. json_object_set_array_member(data, "chats", jchats);
  764. json_object_set_array_member(data, "accounts", jaccounts);
  765. sapphire_send(data);
  766. json_object_unref(data);
  767. }
  768. static void
  769. sapphire_buddy_status_changed(PurpleBuddy *buddy, gpointer null)
  770. {
  771. JsonObject *data = json_object_new();
  772. json_object_set_string_member(data, "op", "buddyStatus");
  773. sapphire_serialize_status(data, sapphire_status_for_buddy(buddy));
  774. sapphire_serialize_buddy(data, buddy);
  775. sapphire_send(data);
  776. json_object_unref(data);
  777. }
  778. static void
  779. sapphire_serialize_typing_state(JsonObject *data, PurpleTypingState state)
  780. {
  781. /* While we could pass is, that risks future libpurple updates causing
  782. * breakage */
  783. int s_state =
  784. (state == PURPLE_NOT_TYPING) ? 0 :
  785. (state == PURPLE_TYPING) ? 1 :
  786. (state == PURPLE_TYPED) ? 2 :
  787. -1;
  788. json_object_set_int_member(data, "state", s_state);
  789. }
  790. static PurpleTypingState
  791. sapphire_decode_typing_state(int s_state)
  792. {
  793. return (s_state == 0) ? PURPLE_NOT_TYPING :
  794. (s_state == 1) ? PURPLE_TYPING :
  795. (s_state == 2) ? PURPLE_TYPED :
  796. PURPLE_NOT_TYPING;
  797. }
  798. static void
  799. sapphire_buddy_typing_changed(PurpleAccount *account, const char *name, gpointer null)
  800. {
  801. JsonObject *data = json_object_new();
  802. json_object_set_string_member(data, "op", "typing");
  803. PurpleBuddy *buddy = purple_find_buddy(account, name);
  804. sapphire_serialize_buddy(data, buddy);
  805. PurpleConvIm *im = sapphire_im_for_name(account, name);
  806. PurpleTypingState state = purple_conv_im_get_typing_state(im);
  807. sapphire_serialize_typing_state(data, state);
  808. sapphire_send(data);
  809. json_object_unref(data);
  810. }
  811. /* Push notification infrastrcture -- has a push notification been sent since
  812. * the last login? We default to TRUE to avoid sporadic push notifications
  813. * before the first connection*/
  814. gboolean sapphire_already_pushed = TRUE;
  815. /* We got a connection, so we're clear for another push */
  816. void
  817. sapphire_push_connected(void)
  818. {
  819. sapphire_already_pushed = FALSE;
  820. }
  821. /* Send a push notification with the given content. This wrapper function
  822. * determines whether the notification should actually be pushed, handling
  823. * state appropriately. Actual medium-specific sending is delegated. */
  824. extern gboolean sapphire_any_connected_clients;
  825. void
  826. sapphire_push_notification(const gchar *content)
  827. {
  828. /* Push notifications can only be sent if:
  829. *
  830. * 0. Push notifications are enabled (TODO)
  831. * 1. There are no connected clients
  832. * 2. There has not been another push notification sent
  833. *
  834. * Check these criteria
  835. */
  836. if (sapphire_any_connected_clients) return;
  837. if (sapphire_already_pushed) return;
  838. /* We've passed the criteria, so send the notification via the proxy */
  839. JsonObject *resp = json_object_new();
  840. json_object_set_string_member(resp, "op", "push");
  841. json_object_set_string_member(resp, "content", content);
  842. gchar *str = json_object_to_string(resp);
  843. gchar *str_prefixed = g_strdup_printf(">%s", str);
  844. sapphire_send_raw_packet(str_prefixed);
  845. json_object_unref(resp);
  846. g_free(str_prefixed);
  847. g_free(str);
  848. /* Record that we pushed something */
  849. sapphire_already_pushed = TRUE;
  850. }
  851. static void
  852. sapphire_received_message(PurpleAccount *account, const char *who, const char *message, PurpleConversation *conv,
  853. PurpleMessageFlags flags, gpointer null)
  854. {
  855. /* Find the buddy since the arguments as-is are difficult to work with */
  856. PurpleBuddy *buddy = NULL;
  857. /* Whether channel_id needs a g_free */
  858. gboolean should_free_channel_id = TRUE;
  859. gchar *channel_id;
  860. JsonObject *data = json_object_new();
  861. json_object_set_string_member(data, "op", "message");
  862. /* Serialization depends on the type of "buffer" in use; we don't
  863. * smooth out the incongruence between IMs and chats until we're in
  864. * backend.js on the client */
  865. PurpleConversationType type = purple_conversation_get_type(conv);
  866. if (type == PURPLE_CONV_TYPE_IM) {
  867. /* Serialize the buddy we're talking to */
  868. buddy = purple_find_buddy(account, who);
  869. sapphire_serialize_buddy(data, buddy);
  870. channel_id = sapphire_serialize_buddy_id(buddy);
  871. } else if (type == PURPLE_CONV_TYPE_CHAT) {
  872. /* Serialize the chat itself */
  873. channel_id = sapphire_id_from_conv(conv);
  874. json_object_set_string_member(data, "chat", channel_id);
  875. if (flags & PURPLE_MESSAGE_SYSTEM) {
  876. json_object_set_string_member(data, "who", "system");
  877. } else {
  878. /* And just the ID of who sent it. */
  879. gchar *user_id = sapphire_serialize_chat_user_id(conv, who);
  880. json_object_set_string_member(data, "who", user_id);
  881. g_free(user_id);
  882. /* ...in case the user is offline and not a buddy, also supply an alias */
  883. json_object_set_string_member(data, "alias", who);
  884. }
  885. } else {
  886. fprintf(stderr, "Wat? nonbuddy, non chat?\n");
  887. }
  888. //json_object_set_int_member(data, "time", mtime);
  889. json_object_set_int_member(data, "flags", flags);
  890. /* Since we might be OTR-protected, the backend can't do anything with the plaintext */
  891. json_object_set_string_member(data, "content", message);
  892. /* So, if there are connected clients, we broadcast to them. Otherwise, we need to
  893. * store the message, so we can replay messages later for when we
  894. * connect. It's okay if the lookup fails and we null, g_list functions
  895. * don't mind. Additionally, if this is the first message like this,
  896. * we'll need to send a push notification. */
  897. if (sapphire_any_connected_clients) {
  898. /* Broadcast */
  899. gchar *str = json_object_to_string(data);
  900. sapphire_send_raw_packet(str);
  901. } else {
  902. /* Save the message */
  903. if (type == PURPLE_CONV_TYPE_IM) {
  904. GList *unacked_list = g_hash_table_lookup(id_to_unacked_list, channel_id);
  905. unacked_list = g_list_prepend(unacked_list, json_object_ref(data));
  906. g_hash_table_replace(id_to_unacked_list, channel_id, unacked_list);
  907. should_free_channel_id = FALSE;
  908. } else {
  909. /* TODO: Chats. At the moment, these can accumulate
  910. * huge amounts of memory, so disabling for now, mk? */
  911. }
  912. }
  913. /* Send a notification for IMs. The push notification module will
  914. * determine if it's necessary */
  915. if (type == PURPLE_CONV_TYPE_IM) {
  916. const char *alias = purple_buddy_get_alias(buddy);
  917. gchar *notification = g_strdup_printf("Psst, %s messaged you via Sapphire\n", alias);
  918. sapphire_push_notification(notification);
  919. g_free(notification);
  920. }
  921. if (should_free_channel_id)
  922. g_free(channel_id);
  923. json_object_unref(data);
  924. }
  925. static void
  926. sapphire_topic_changed(PurpleConversation *conv, const char *who, const char *topic, gpointer null)
  927. {
  928. JsonObject *data = json_object_new();
  929. gchar *chat_id = sapphire_id_from_conv(conv);
  930. json_object_set_string_member(data, "op", "topic");
  931. json_object_set_string_member(data, "who", who);
  932. json_object_set_string_member(data, "topic", topic);
  933. json_object_set_string_member(data, "chat", chat_id);
  934. sapphire_send(data);
  935. json_object_unref(data);
  936. g_free(chat_id);
  937. }
  938. /* A buddy joined in a room we're subscribed to -- but that doesn't mean the
  939. * client needs to know. Only send the joined event to clients that have opened
  940. * the corresponding conversation */
  941. extern GList *authenticated_connections;
  942. static void
  943. sapphire_buddy_joined(PurpleConversation *conv, const char *who, PurpleConvChatBuddyFlags flags, gboolean new_arrival, gpointer null)
  944. {
  945. JsonObject *data = json_object_new();
  946. gchar *chat_id = sapphire_id_from_conv(conv);
  947. json_object_set_string_member(data, "op", "joined");
  948. json_object_set_string_member(data, "chat", chat_id);
  949. /* Send a single element worth of users :( */
  950. JsonArray *lst = json_array_new();
  951. JsonObject *buddy = json_object_new();
  952. sapphire_serialize_chat_buddy(buddy, conv, who, flags);
  953. json_array_add_object_element(lst, buddy);
  954. json_object_set_array_member(data, "members", lst);
  955. sapphire_send(data);
  956. g_free(chat_id);
  957. json_object_unref(data);
  958. }
  959. static void
  960. sapphire_joined_chat(PurpleConversation *conv, gpointer null)
  961. {
  962. /* Try to use the existing chat */
  963. gchar *id = sapphire_id_from_conv(conv);
  964. SapphireChat *schat = sapphire_find_chat(id, TRUE);
  965. if (!schat) {
  966. /* Surprise! Create a new chat */
  967. schat = sapphire_chat_from_conv(conv);
  968. schat->conv = conv;
  969. chats = g_slist_append(chats, schat);
  970. } else {
  971. /* Associate with the conv */
  972. schat->conv = conv;
  973. }
  974. g_hash_table_insert(blist_id_to_conversation, id, conv);
  975. /* It's joined! */
  976. if (!g_hash_table_contains(id_to_joined, id)) {
  977. g_hash_table_add(id_to_joined, g_strdup(id));
  978. g_hash_table_insert(id_to_chat, g_strdup(id), schat);
  979. }
  980. }
  981. /* Certain prpls, particularly those for third-party protocols, should be
  982. * disabled when not in active use. This function, called from the socket
  983. * handling when a client connects or disconnects, checks if there are active
  984. * connections. If there are, relevant prpls are enabled; if not, they are
  985. * disabled. */
  986. static gboolean
  987. sapphire_prpl_defer_connects(const gchar *protocol_id)
  988. {
  989. return purple_strequal(protocol_id, "prpl-eionrobb-discord");
  990. }
  991. void
  992. sapphire_enable_accounts_by_connections(void)
  993. {
  994. gboolean should_enable = sapphire_any_connected_clients;
  995. for (GSList *it = purple_accounts; it != NULL; it = it->next) {
  996. PurpleAccount *account = (PurpleAccount *) it->data;
  997. const gchar *protocol_id = purple_account_get_protocol_id(account);
  998. /* Check if the protocol has this quirk */
  999. if (!sapphire_prpl_defer_connects(protocol_id))
  1000. continue;
  1001. /* It does -- so check which direction we need to go */
  1002. gboolean enab = purple_account_get_enabled(account, UI_ID);
  1003. if (should_enable != enab) {
  1004. purple_account_set_enabled(account, UI_ID, should_enable);
  1005. }
  1006. }
  1007. }
  1008. #ifdef _WIN32
  1009. #include <windows.h>
  1010. extern BOOL SetDllDirectoryA(LPCSTR lpPathName);
  1011. typedef void (WINAPI* LPFNSETDLLDIRECTORY)(LPCSTR);
  1012. static LPFNSETDLLDIRECTORY MySetDllDirectory = NULL;
  1013. #endif
  1014. static void
  1015. init_libpurple(void)
  1016. {
  1017. #ifdef _WIN32
  1018. purple_util_set_user_dir("./.purple");
  1019. HMODULE hmod;
  1020. if ((hmod = GetModuleHandleW(L"kernel32.dll"))) {
  1021. MySetDllDirectory = (LPFNSETDLLDIRECTORY) GetProcAddress(
  1022. hmod, "SetDllDirectoryA");
  1023. if (!MySetDllDirectory)
  1024. printf("SetDllDirectory not supported\n");
  1025. } else
  1026. printf("Error getting kernel32.dll module handle\n");
  1027. /* For Windows XP SP1+ / Server 2003 we use SetDllDirectory to avoid dll hell */
  1028. if (MySetDllDirectory) {
  1029. printf("Using SetDllDirectory\n");
  1030. MySetDllDirectory("C:/Program Files (x86)/Pidgin/");
  1031. }
  1032. #endif
  1033. gchar *search_path = g_build_filename(purple_user_dir(), "plugins", NULL);
  1034. purple_plugins_add_search_path(search_path);
  1035. g_free(search_path);
  1036. #ifdef _WIN32
  1037. purple_plugins_add_search_path("C:/Program Files (x86)/Pidgin/plugins/");
  1038. purple_plugins_add_search_path("C:/Program\\ Files\\ \\(x86\\)/Pidgin/");
  1039. purple_plugins_add_search_path("C:/Program\\ Files\\ \\(x86\\)/Pidgin/plugins/");
  1040. #endif
  1041. purple_debug_set_enabled(FALSE);
  1042. sapphire_set_eventloop();
  1043. if (!purple_core_init(UI_ID)) {
  1044. fprintf(stderr,
  1045. "libpurple initialization failed. Dumping core.\n"
  1046. "Please report this!\n");
  1047. abort();
  1048. }
  1049. purple_set_blist(purple_blist_new());
  1050. purple_blist_load();
  1051. purple_prefs_load();
  1052. purple_plugins_load_saved(PLUGIN_SAVE_PREF);
  1053. purple_pounces_load();
  1054. }
  1055. static void
  1056. sapphire_connect_signals(void)
  1057. {
  1058. static int handle;
  1059. purple_signal_connect(purple_accounts_get_handle(), "account-signed-on", &handle,
  1060. PURPLE_CALLBACK(sapphire_signed_on), NULL);
  1061. purple_signal_connect(purple_accounts_get_handle(), "account-enabled", &handle,
  1062. PURPLE_CALLBACK(sapphire_account_enabled), NULL);
  1063. purple_signal_connect(purple_blist_get_handle(), "buddy-signed-on", &handle,
  1064. PURPLE_CALLBACK(sapphire_buddy_status_changed), NULL);
  1065. purple_signal_connect(purple_blist_get_handle(), "buddy-signed-off", &handle,
  1066. PURPLE_CALLBACK(sapphire_buddy_status_changed), NULL);
  1067. purple_signal_connect(purple_blist_get_handle(), "buddy-status-changed", &handle,
  1068. PURPLE_CALLBACK(sapphire_buddy_status_changed), NULL);
  1069. purple_signal_connect(purple_conversations_get_handle(), "wrote-im-msg", &handle,
  1070. PURPLE_CALLBACK(sapphire_received_message), NULL);
  1071. purple_signal_connect(purple_conversations_get_handle(), "wrote-chat-msg", &handle,
  1072. PURPLE_CALLBACK(sapphire_received_message), NULL);
  1073. purple_signal_connect(purple_conversations_get_handle(), "buddy-typing", &handle,
  1074. PURPLE_CALLBACK(sapphire_buddy_typing_changed), NULL);
  1075. purple_signal_connect(purple_conversations_get_handle(), "buddy-typed", &handle,
  1076. PURPLE_CALLBACK(sapphire_buddy_typing_changed), NULL);
  1077. purple_signal_connect(purple_conversations_get_handle(), "buddy-typing-stopped", &handle,
  1078. PURPLE_CALLBACK(sapphire_buddy_typing_changed), NULL);
  1079. purple_signal_connect(purple_conversations_get_handle(), "chat-joined", &handle,
  1080. PURPLE_CALLBACK(sapphire_joined_chat), NULL);
  1081. purple_signal_connect(purple_conversations_get_handle(), "chat-buddy-joined", &handle,
  1082. PURPLE_CALLBACK(sapphire_buddy_joined), NULL);
  1083. purple_signal_connect(purple_conversations_get_handle(), "chat-topic-changed", &handle,
  1084. PURPLE_CALLBACK(sapphire_topic_changed), NULL);
  1085. }
  1086. int main(int argc, char *argv[])
  1087. {
  1088. GMainLoop *loop;
  1089. PurpleSavedStatus *status;
  1090. #ifndef _WIN32
  1091. /* libpurple's built-in DNS resolution forks processes to perform
  1092. * blocking lookups without blocking the main process. It does not
  1093. * handle SIGCHLD itself, so if the UI does not you quickly get an army
  1094. * of zombie subprocesses marching around.
  1095. */
  1096. signal(SIGCHLD, SIG_IGN);
  1097. #endif
  1098. #ifdef _WIN32
  1099. g_thread_init(NULL);
  1100. #endif
  1101. g_set_prgname("Sapphire");
  1102. g_set_application_name("Sapphire");
  1103. loop = g_main_loop_new(NULL, FALSE);
  1104. g_main_loop_ref(loop);
  1105. gboolean jailed = (argc >= 2) && (purple_strequal(argv[1], "--jailed"));
  1106. if (jailed) {
  1107. /* If we're running in firejail, we can't use a .purple, since
  1108. * the hidden nature will cause permission errors. Instead, use
  1109. * an opaque name */
  1110. purple_util_set_user_dir("./purple");
  1111. }
  1112. init_libpurple();
  1113. /* Initialize global hash tables */
  1114. id_to_buddy = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  1115. id_to_unacked_list = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  1116. id_to_chat = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  1117. id_to_account = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  1118. id_to_joined = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  1119. blist_id_to_conversation = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
  1120. sent_icons = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
  1121. sapphire_connect_signals();
  1122. sapphire_init_websocket();
  1123. g_main_context_iteration(g_main_loop_get_context(loop), FALSE);
  1124. GList *l;
  1125. /* Fetch account and enable it */
  1126. for (l = purple_accounts_get_all(); l != NULL; l = l->next) {
  1127. PurpleAccount *candidate = (PurpleAccount *)l->data;
  1128. const gchar *protocol_id = purple_account_get_protocol_id(candidate);
  1129. if (purple_strequal(protocol_id, "prpl-jabber") || purple_strequal(protocol_id, "prpl-eionrobb-discord")) {
  1130. purple_accounts = g_slist_append(purple_accounts, candidate);
  1131. purple_account_set_enabled(candidate, UI_ID, !sapphire_prpl_defer_connects(protocol_id));
  1132. } else {
  1133. purple_account_set_enabled(candidate, UI_ID, FALSE);
  1134. }
  1135. }
  1136. if (!purple_accounts) {
  1137. fprintf(stderr, "No accounts found\n");
  1138. return 1;
  1139. }
  1140. /* Now, to connect the account(s), create a status and activate it. */
  1141. status = purple_savedstatus_new(NULL, PURPLE_STATUS_AVAILABLE);
  1142. purple_savedstatus_activate(status);
  1143. g_main_loop_run(loop);
  1144. return 0;
  1145. }