Blame view

libpurple/purpleline.cpp 18.7 KB
2fcd68c7   Matti Virkkunen   Show history begi...
1
  #include <algorithm>
9d4cbc44   Matti Virkkunen   Split fetchOperat...
2
  #include <functional>
0fa93df6   Matti Virkkunen   Added support for...
3
  #include <memory>
dc8f9a72   Matti Virkkunen   Log in and get pr...
4
  
dc68d3dd   Matti Virkkunen   More error handli...
5
6
  #include <time.h>
  
5892b95c   Matti Virkkunen   Added /open comma...
7
8
9
  #include <glib.h>
  #include <glib/gstdio.h>
  
82987920   Matti Virkkunen   Implemented sendi...
10
  #include <cmds.h>
a4d82423   Matti Virkkunen   Implemented recei...
11
  #include <connection.h>
f7bd89a8   Matti Virkkunen   Implemented text ...
12
  #include <conversation.h>
dc8f9a72   Matti Virkkunen   Log in and get pr...
13
  #include <debug.h>
a4d82423   Matti Virkkunen   Implemented recei...
14
15
16
  #include <eventloop.h>
  #include <notify.h>
  #include <request.h>
dc8f9a72   Matti Virkkunen   Log in and get pr...
17
  #include <sslconn.h>
53a2cd4a   Matti Virkkunen   Un/escape markup ...
18
  #include <util.h>
dc8f9a72   Matti Virkkunen   Log in and get pr...
19
  
93706fc9   Matti Virkkunen   Refactored Thrift...
20
  #include "purpleline.hpp"
64d14eab   Matti Virkkunen   Implement account...
21
22
  #include "wrapper.hpp"
  
61ed212d   Matti Virkkunen   Split purpleline....
23
  std::string markup_escape(std::string const &text) {
53a2cd4a   Matti Virkkunen   Un/escape markup ...
24
25
26
27
28
29
30
      gchar *escaped = purple_markup_escape_text(text.c_str(), text.size());
      std::string result(escaped);
      g_free(escaped);
  
      return result;
  }
  
61ed212d   Matti Virkkunen   Split purpleline....
31
  std::string markup_unescape(std::string const &markup) {
53a2cd4a   Matti Virkkunen   Un/escape markup ...
32
33
34
35
36
37
38
      gchar *unescaped = purple_unescape_html(markup.c_str());
      std::string result(unescaped);
      g_free(unescaped);
  
      return result;
  }
  
61ed212d   Matti Virkkunen   Split purpleline....
39
  std::string url_encode(std::string const &str) {
025aed6e   Matti Virkkunen   Display location ...
40
41
42
      return purple_url_encode(str.c_str());
  }
  
fc604ce8   Matti Virkkunen   Added initial sup...
43
44
45
  PurpleLine::PurpleLine(PurpleConnection *conn, PurpleAccount *acct) :
      conn(conn),
      acct(acct),
0ac35486   Matti Virkkunen   Use libpurple HTT...
46
      http(acct),
0fa93df6   Matti Virkkunen   Added support for...
47
      os_http(acct, conn, LINE_OS_SERVER, 443, false),
9d4cbc44   Matti Virkkunen   Split fetchOperat...
48
49
      poller(*this),
      pin_verifier(*this),
0d8a5e28   Matti Virkkunen   Even more buddy l...
50
      next_purple_id(1)
20733774   Matti Virkkunen   Initial commit - ...
51
  {
0ac35486   Matti Virkkunen   Use libpurple HTT...
52
      c_out = boost::make_shared<ThriftClient>(acct, conn, LINE_LOGIN_PATH);
8e9e45af   Matti Virkkunen   Force keep-alive ...
53
      os_http.set_auto_reconnect(true);
b34f8916   Matti Virkkunen   Replaced wrappers...
54
  }
80901ba6   Matti Virkkunen   Fetch contacts an...
55
  
b34f8916   Matti Virkkunen   Replaced wrappers...
56
  PurpleLine::~PurpleLine() {
93706fc9   Matti Virkkunen   Refactored Thrift...
57
      c_out->close();
20733774   Matti Virkkunen   Initial commit - ...
58
59
  }
  
fc604ce8   Matti Virkkunen   Added initial sup...
60
  const char *PurpleLine::list_icon(PurpleAccount *, PurpleBuddy *) {
20733774   Matti Virkkunen   Initial commit - ...
61
62
63
      return "line";
  }
  
b34f8916   Matti Virkkunen   Replaced wrappers...
64
  GList *PurpleLine::status_types(PurpleAccount *) {
ede54633   Matti Virkkunen   More buddy list h...
65
66
      const char *attr_id = "message", *attr_name = "What's Up?";
  
fc604ce8   Matti Virkkunen   Added initial sup...
67
      GList *types = nullptr;
20733774   Matti Virkkunen   Initial commit - ...
68
69
      PurpleStatusType *t;
  
ede54633   Matti Virkkunen   More buddy list h...
70
71
72
73
74
75
76
77
78
79
80
81
82
83
      // Friends
      t = purple_status_type_new_with_attrs(
          PURPLE_STATUS_AVAILABLE, nullptr, nullptr,
          TRUE, TRUE, FALSE,
          attr_id, attr_name, purple_value_new(PURPLE_TYPE_STRING),
          nullptr);
      types = g_list_append(types, t);
  
      // Temporary friends
      t = purple_status_type_new_with_attrs(
          PURPLE_STATUS_UNAVAILABLE, "temporary", "Temporary",
          TRUE, TRUE, FALSE,
          attr_id, attr_name, purple_value_new(PURPLE_TYPE_STRING),
          nullptr);
20733774   Matti Virkkunen   Initial commit - ...
84
85
      types = g_list_append(types, t);
  
ede54633   Matti Virkkunen   More buddy list h...
86
87
88
89
90
91
      // Not actually used because LINE doesn't report online status, but this is apparently required.
      t = purple_status_type_new_with_attrs(
          PURPLE_STATUS_OFFLINE, nullptr, nullptr,
          TRUE, TRUE, FALSE,
          attr_id, attr_name, purple_value_new(PURPLE_TYPE_STRING),
          nullptr);
20733774   Matti Virkkunen   Initial commit - ...
92
93
94
95
96
      types = g_list_append(types, t);
  
      return types;
  }
  
5892b95c   Matti Virkkunen   Added /open comma...
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
  std::string PurpleLine::get_tmp_dir(bool create) {
      std::string name = "line-" + profile.mid;
  
      for (char c: name) {
          if (!(c == '-' || std::isalpha(c) || std::isdigit(c))) {
              name = "line";
              break;
          }
      }
  
      gchar *dir_p = g_build_filename(
          g_get_tmp_dir(),
          name.c_str(),
          nullptr);
  
      if (create)
          g_mkdir_with_parents(dir_p, 0700);
  
      std::string dir(dir_p);
  
      g_free(dir_p);
  
      return dir;
  }
  
ede54633   Matti Virkkunen   More buddy list h...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
  char *PurpleLine::status_text(PurpleBuddy *buddy) {
      PurplePresence *presence = purple_buddy_get_presence(buddy);
      PurpleStatus *status = purple_presence_get_active_status(presence);
  
      const char *msg = purple_status_get_attr_string(status, "message");
      if (msg && msg[0])
          return g_markup_escape_text(msg, -1);
  
      return nullptr;
  }
  
  void PurpleLine::tooltip_text(PurpleBuddy *buddy, PurpleNotifyUserInfo *user_info, gboolean full) {
      purple_notify_user_info_add_pair_plaintext(user_info,
          "Name", purple_buddy_get_alias(buddy));
  
      //purple_notify_user_info_add_pair_plaintext(user_info,
      //    "User ID", purple_buddy_get_name(buddy));
  
      if (purple_blist_node_get_bool(PURPLE_BLIST_NODE(buddy), "official_account"))
          purple_notify_user_info_add_pair_plaintext(user_info, "Official account", "Yes");
  
      if (PURPLE_BLIST_NODE_HAS_FLAG(buddy, PURPLE_BLIST_NODE_FLAG_NO_SAVE)) {
0d8a5e28   Matti Virkkunen   Even more buddy l...
144
145
146
          // This breaks?
          //purple_notify_user_info_add_section_break(user_info);
  
ede54633   Matti Virkkunen   More buddy list h...
147
148
          purple_notify_user_info_add_pair_plaintext(user_info,
              "Temporary",
0d8a5e28   Matti Virkkunen   Even more buddy l...
149
              "You are currently in a conversation with this contact, "
ede54633   Matti Virkkunen   More buddy list h...
150
151
                  "but they are not on your friend list.");
      }
f7bd89a8   Matti Virkkunen   Implemented text ...
152
153
  }
  
b34f8916   Matti Virkkunen   Replaced wrappers...
154
155
  void PurpleLine::login(PurpleAccount *acct) {
      PurpleConnection *conn = purple_account_get_connection(acct);
dc8f9a72   Matti Virkkunen   Log in and get pr...
156
  
b34f8916   Matti Virkkunen   Replaced wrappers...
157
158
      PurpleLine *plugin = new PurpleLine(conn, acct);
      conn->proto_data = (void *)plugin;
20733774   Matti Virkkunen   Initial commit - ...
159
  
38a0988d   Matti Virkkunen   Implemented leavi...
160
161
      plugin->connect_signals();
  
a29acd28   Matti Virkkunen   Split login sync ...
162
      plugin->login_start();
b34f8916   Matti Virkkunen   Replaced wrappers...
163
  }
20733774   Matti Virkkunen   Initial commit - ...
164
  
b34f8916   Matti Virkkunen   Replaced wrappers...
165
  void PurpleLine::close() {
38a0988d   Matti Virkkunen   Implemented leavi...
166
167
      disconnect_signals();
  
5892b95c   Matti Virkkunen   Added /open comma...
168
169
170
171
172
173
174
      if (temp_files.size()) {
          for (std::string &path: temp_files)
              g_unlink(path.c_str());
  
          g_rmdir(get_tmp_dir().c_str());
      }
  
b34f8916   Matti Virkkunen   Replaced wrappers...
175
176
      delete this;
  }
dc8f9a72   Matti Virkkunen   Log in and get pr...
177
  
38a0988d   Matti Virkkunen   Implemented leavi...
178
179
180
181
182
183
184
  void PurpleLine::connect_signals() {
      purple_signal_connect(
          purple_blist_get_handle(),
          "blist-node-removed",
          (void *)this,
          PURPLE_CALLBACK(WRAPPER_TYPE(PurpleLine::signal_blist_node_removed, signal)),
          (void *)this);
87e4db97   Matti Virkkunen   Fetch recent mess...
185
186
187
188
189
190
191
  
      purple_signal_connect(
          purple_conversations_get_handle(),
          "conversation-created",
          (void *)this,
          PURPLE_CALLBACK(WRAPPER_TYPE(PurpleLine::signal_conversation_created, signal)),
          (void *)this);
2fcd68c7   Matti Virkkunen   Show history begi...
192
193
194
195
196
197
198
  
      purple_signal_connect(
          purple_conversations_get_handle(),
          "deleting-conversation",
          (void *)this,
          PURPLE_CALLBACK(WRAPPER_TYPE(PurpleLine::signal_deleting_conversation, signal)),
          (void *)this);
38a0988d   Matti Virkkunen   Implemented leavi...
199
200
201
202
203
204
205
206
  }
  
  void PurpleLine::disconnect_signals() {
      purple_signal_disconnect(
          purple_blist_get_handle(),
          "blist-node-removed",
          (void *)this,
          PURPLE_CALLBACK(WRAPPER_TYPE(PurpleLine::signal_blist_node_removed, signal)));
87e4db97   Matti Virkkunen   Fetch recent mess...
207
208
209
210
211
212
  
      purple_signal_disconnect(
          purple_conversations_get_handle(),
          "conversation-created",
          (void *)this,
          PURPLE_CALLBACK(WRAPPER_TYPE(PurpleLine::signal_conversation_created, signal)));
2fcd68c7   Matti Virkkunen   Show history begi...
213
214
215
216
217
218
219
  
  
      purple_signal_disconnect(
          purple_conversations_get_handle(),
          "deleting-conversation",
          (void *)this,
          PURPLE_CALLBACK(WRAPPER_TYPE(PurpleLine::signal_deleting_conversation, signal)));
38a0988d   Matti Virkkunen   Implemented leavi...
220
221
  }
  
5892b95c   Matti Virkkunen   Added /open comma...
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
  std::string PurpleLine::conv_attachment_add(PurpleConversation *conv,
      line::ContentType::type type, std::string id)
  {
      auto atts = (std::vector<Attachment> *)purple_conversation_get_data(conv, "line-attachments");
      if (!atts) {
          atts = new std::vector<Attachment>();
          purple_conversation_set_data(conv, "line-attachments", atts);
      }
  
      atts->emplace_back(type, id);
  
      return std::to_string(atts->size());
  }
  
  PurpleLine::Attachment *PurpleLine::conv_attachment_get(PurpleConversation *conv, std::string token)
  {
      int index;
  
      try {
          index = std::stoi(token);
      } catch (...) {
          return nullptr;
      }
  
      auto atts = (std::vector<Attachment> *)purple_conversation_get_data(conv, "line-attachments");
  
      return (atts && index <= (int)atts->size()) ? &(*atts)[index - 1] : nullptr;
  }
  
239fea72   Matti Virkkunen   Implemented synci...
251
252
253
254
  line::Contact &PurpleLine::get_up_to_date_contact(line::Contact &c) {
      return (contacts.count(c.mid) != 0) ? contacts[c.mid] : c;
  }
  
0fa93df6   Matti Virkkunen   Added support for...
255
256
  int PurpleLine::send_message(std::string to, const char *markup) {
      // Parse markup and send message as parts if it contains images
fc604ce8   Matti Virkkunen   Added initial sup...
257
  
0fa93df6   Matti Virkkunen   Added support for...
258
      bool any_sent = false;
fc604ce8   Matti Virkkunen   Added initial sup...
259
  
0fa93df6   Matti Virkkunen   Added support for...
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
      for (const char *p = markup; p && *p; ) {
          const char *start, *end;
          GData *attributes;
  
          bool img_found = purple_markup_find_tag("IMG", p, &start, &end, &attributes);
  
          std::string text;
  
          if (img_found) {
              // Image found but there's text before it, store it
  
              text = std::string(p, start - p);
              p = end + 1;
          } else {
              // No image found, store the rest of the text
  
              text = std::string(p);
  
              // Break the loop
  
              p = NULL;
          }
  
          // If the text is not all whitespace, send it as a text message
          if (text.find_first_not_of("\t\n\r ") != std::string::npos)
          {
              line::Message msg;
  
              msg.contentType = line::ContentType::NONE;
86d3ba75   Matti Virkkunen   Avoid new reserve...
289
              msg.from_ = profile.mid;
0fa93df6   Matti Virkkunen   Added support for...
290
291
292
293
294
295
296
297
298
              msg.to = to;
              msg.text = markup_unescape(text);
  
              send_message(msg);
  
              any_sent = true;
          }
  
          if (img_found) {
0fa93df6   Matti Virkkunen   Added support for...
299
300
301
302
303
304
305
306
307
308
309
              int image_id = std::stoi((char *)g_datalist_get_data(&attributes, "id"));
              g_datalist_clear(&attributes);
  
              std::stringstream ss;
              ss << "(img ID: " << image_id << ")";
  
              PurpleStoredImage *img = purple_imgstore_find_by_id(image_id);
              if (!img) {
                  purple_debug_warning("line", "Tried to send non-existent image: %d\n", image_id);
                  continue;
              }
82987920   Matti Virkkunen   Implemented sendi...
310
  
0fa93df6   Matti Virkkunen   Added support for...
311
312
313
314
315
316
317
              std::string img_data(
                  (const char *)purple_imgstore_get_data(img),
                  purple_imgstore_get_size(img));
  
              line::Message msg;
  
              msg.contentType = line::ContentType::IMAGE;
86d3ba75   Matti Virkkunen   Avoid new reserve...
318
              msg.from_ = profile.mid;
0fa93df6   Matti Virkkunen   Added support for...
319
320
321
322
323
324
325
326
327
328
329
              msg.to = to;
  
              send_message(msg, [this, img_data](line::Message &msg_back) {
                  upload_media(msg_back.id, "image", img_data);
              });
  
              any_sent = true;
          }
      }
  
      return any_sent ? 1 : 0;
82987920   Matti Virkkunen   Implemented sendi...
330
331
  }
  
0fa93df6   Matti Virkkunen   Added support for...
332
333
334
335
  void PurpleLine::send_message(
      line::Message &msg,
      std::function<void(line::Message &)> callback)
  {
82987920   Matti Virkkunen   Implemented sendi...
336
337
      std::string to(msg.to);
  
93706fc9   Matti Virkkunen   Refactored Thrift...
338
      c_out->send_sendMessage(0, msg);
0fa93df6   Matti Virkkunen   Added support for...
339
      c_out->send([this, to, callback]() {
fc604ce8   Matti Virkkunen   Added initial sup...
340
          line::Message msg_back;
dc68d3dd   Matti Virkkunen   More error handli...
341
342
343
  
          try {
              c_out->recv_sendMessage(msg_back);
16e4631b   Matti Virkkunen   Changed names to ...
344
          } catch (line::TalkException &err) {
57dc98eb   Matti Virkkunen   Handle failed sen...
345
              std::string msg = "Failed to send message: " + err.reason;
dc68d3dd   Matti Virkkunen   More error handli...
346
  
57dc98eb   Matti Virkkunen   Handle failed sen...
347
              PurpleConversation *conv = purple_find_conversation_with_account(
0d8a5e28   Matti Virkkunen   Even more buddy l...
348
349
350
                  PURPLE_CONV_TYPE_ANY,
                  to.c_str(),
                  acct);
dc68d3dd   Matti Virkkunen   More error handli...
351
352
353
354
355
  
              if (conv) {
                  purple_conversation_write(
                      conv,
                      "",
57dc98eb   Matti Virkkunen   Handle failed sen...
356
                      msg.c_str(),
dc68d3dd   Matti Virkkunen   More error handli...
357
358
                      (PurpleMessageFlags)PURPLE_MESSAGE_ERROR,
                      time(NULL));
57dc98eb   Matti Virkkunen   Handle failed sen...
359
              } else {
38a0988d   Matti Virkkunen   Implemented leavi...
360
                  notify_error(msg);
dc68d3dd   Matti Virkkunen   More error handli...
361
362
              }
  
57dc98eb   Matti Virkkunen   Handle failed sen...
363
              return;
dc68d3dd   Matti Virkkunen   More error handli...
364
365
          }
  
0d8a5e28   Matti Virkkunen   Even more buddy l...
366
367
          // Kludge >_>
          if (to[0] == 'u')
dc68d3dd   Matti Virkkunen   More error handli...
368
              push_recent_message(msg_back.id);
0fa93df6   Matti Virkkunen   Added support for...
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
  
          if (callback)
              callback(msg_back);
      });
  }
  
  void PurpleLine::upload_media(std::string message_id, std::string type, std::string data) {
      std::string boundary;
  
      do {
          gchar *random_string = purple_uuid_random();
          boundary = random_string;
          g_free(random_string);
      } while (data.find(boundary) != std::string::npos);
  
      std::stringstream body;
  
      body
          << "--" << boundary << "\r\n"
          << "Content-Disposition: form-data; name=\"params\"\r\n"
          << "\r\n"
          << "{"
          << "\"name\":\"media\","
          << "\"oid\":\"" << message_id << "\","
          << "\"size\":\"" << data.size() << "\","
          << "\"type\":\"" << type << "\","
          << "\"ver\":\"1.0\""
          << "}"
          << "\r\n--" << boundary << "\r\n"
          << "Content-Disposition: form-data; name=\"file\"; filename=\"media\"\r\n"
          << "Content-Type: image/jpeg\r\n"
          << "\r\n"
          << data
          << "\r\n--" << boundary << "--\r\n";
  
      std::string content_type = std::string("multipart/form-data; boundary=") + boundary;
  
      os_http.write_virt((const uint8_t *)body.str().c_str(), body.tellp());
  
      os_http.request("POST", "/talk/m/upload.nhn", content_type, [this]() {
          if (os_http.status_code() != 201) {
              purple_debug_warning(
                  "line",
                  "Couldn't upload message media. Status: %d\n",
                  os_http.status_code());
          }
fc604ce8   Matti Virkkunen   Added initial sup...
415
      });
fc604ce8   Matti Virkkunen   Added initial sup...
416
417
  }
  
0fa93df6   Matti Virkkunen   Added support for...
418
419
420
421
422
423
  void PurpleLine::push_recent_message(std::string id) {
      recent_messages.push_back(id);
      if (recent_messages.size() > 50)
          recent_messages.pop_front();
  }
  
dc68d3dd   Matti Virkkunen   More error handli...
424
  int PurpleLine::send_im(const char *who, const char *message, PurpleMessageFlags flags) {
0fa93df6   Matti Virkkunen   Added support for...
425
      return send_message(who, message);
0d8a5e28   Matti Virkkunen   Even more buddy l...
426
427
  }
  
38a0988d   Matti Virkkunen   Implemented leavi...
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
  void PurpleLine::remove_buddy(PurpleBuddy *buddy, PurpleGroup *) {
      c_out->send_updateContactSetting(
          0,
          purple_buddy_get_name(buddy),
          line::ContactSetting::CONTACT_SETTING_DELETE,
          "true");
      c_out->send([this]{
          try {
              c_out->recv_updateContactSetting();
          } catch (line::TalkException &err) {
              notify_error(std::string("Couldn't delete buddy: ") + err.reason);
          }
      });
  }
  
38a0988d   Matti Virkkunen   Implemented leavi...
443
  void PurpleLine::signal_blist_node_removed(PurpleBlistNode *node) {
ddbfb998   Matti Virkkunen   Ignore chats from...
444
445
446
447
448
      if (!(PURPLE_BLIST_NODE_IS_CHAT(node)
          && purple_chat_get_account(PURPLE_CHAT(node)) == acct))
      {
          return;
      }
38a0988d   Matti Virkkunen   Implemented leavi...
449
  
ddbfb998   Matti Virkkunen   Ignore chats from...
450
      GHashTable *components = purple_chat_get_components(PURPLE_CHAT(node));
38a0988d   Matti Virkkunen   Implemented leavi...
451
  
ddbfb998   Matti Virkkunen   Ignore chats from...
452
453
      char *id_ptr = (char *)g_hash_table_lookup(components, "id");
      if (!id_ptr) {
26f65110   Matti Virkkunen   Add missing linef...
454
          purple_debug_warning("line", "Tried to remove a chat with no id.\n");
ddbfb998   Matti Virkkunen   Ignore chats from...
455
456
          return;
      }
38a0988d   Matti Virkkunen   Implemented leavi...
457
  
ddbfb998   Matti Virkkunen   Ignore chats from...
458
      std::string id(id_ptr);
38a0988d   Matti Virkkunen   Implemented leavi...
459
  
ddbfb998   Matti Virkkunen   Ignore chats from...
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
      ChatType type = get_chat_type((char *)g_hash_table_lookup(components, "type"));
  
      if (type == ChatType::ROOM) {
          c_out->send_leaveRoom(0, id);
          c_out->send([this]{
              try {
                  c_out->recv_leaveRoom();
              } catch (line::TalkException &err) {
                  notify_error(std::string("Couldn't leave from chat: ") + err.reason);
              }
          });
      } else if (type == ChatType::GROUP) {
          c_out->send_leaveGroup(0, id);
          c_out->send([this]{
              try {
                  c_out->recv_leaveGroup();
              } catch (line::TalkException &err) {
                  notify_error(std::string("Couldn't leave from group: ") + err.reason);
              }
          });
      } else {
26f65110   Matti Virkkunen   Add missing linef...
481
          purple_debug_warning("line", "Tried to remove a chat with no type.\n");
ddbfb998   Matti Virkkunen   Ignore chats from...
482
          return;
38a0988d   Matti Virkkunen   Implemented leavi...
483
484
485
      }
  }
  
87e4db97   Matti Virkkunen   Fetch recent mess...
486
487
488
489
  void PurpleLine::signal_conversation_created(PurpleConversation *conv) {
      if (purple_conversation_get_account(conv) != acct)
          return;
  
2fcd68c7   Matti Virkkunen   Show history begi...
490
491
492
      // Start queuing messages while the history is fetched
      purple_conversation_set_data(conv, "line-message-queue", new std::vector<line::Message>());
  
2a2bec32   Matti Virkkunen   Don't show empty ...
493
      fetch_conversation_history(conv, 10, false);
4834479b   Matti Virkkunen   Add /history comm...
494
495
  }
  
2a2bec32   Matti Virkkunen   Don't show empty ...
496
  void PurpleLine::fetch_conversation_history(PurpleConversation *conv, int count, bool requested) {
87e4db97   Matti Virkkunen   Fetch recent mess...
497
498
499
      PurpleConversationType type = conv->type;
      std::string name(purple_conversation_get_name(conv));
  
4834479b   Matti Virkkunen   Add /history comm...
500
501
502
503
504
505
      int64_t end_seq = -1;
  
      int64_t *end_seq_p = (int64_t *)purple_conversation_get_data(conv, "line-end-seq");
      if (end_seq_p)
          end_seq = *end_seq_p;
  
318f26bd   Matti Virkkunen   Add logging for h...
506
507
508
509
      purple_debug_info("line",
          "Fetching history: end_seq=%" G_GINT64_FORMAT " , count=%d, requested=%d\n",
          end_seq, count, requested);
  
4834479b   Matti Virkkunen   Add /history comm...
510
511
512
513
514
      if (end_seq != -1)
          c_out->send_getPreviousMessages(name, end_seq - 1, count);
      else
          c_out->send_getRecentMessages(name, count);
  
2a2bec32   Matti Virkkunen   Don't show empty ...
515
      c_out->send([this, requested, type, name, end_seq]() {
4834479b   Matti Virkkunen   Add /history comm...
516
517
          int64_t new_end_seq = end_seq;
  
87e4db97   Matti Virkkunen   Fetch recent mess...
518
          std::vector<line::Message> recent_msgs;
4834479b   Matti Virkkunen   Add /history comm...
519
520
521
522
523
  
          if (end_seq != -1)
              c_out->recv_getPreviousMessages(recent_msgs);
          else
              c_out->recv_getRecentMessages(recent_msgs);
87e4db97   Matti Virkkunen   Fetch recent mess...
524
525
526
527
528
  
          PurpleConversation *conv = purple_find_conversation_with_account(type, name.c_str(), acct);
          if (!conv)
              return; // Conversation died while fetching messages
  
2fcd68c7   Matti Virkkunen   Show history begi...
529
530
531
532
533
          auto *queue = (std::vector<line::Message> *)
              purple_conversation_get_data(conv, "line-message-queue");
  
          purple_conversation_set_data(conv, "line-message-queue", nullptr);
  
2a2bec32   Matti Virkkunen   Don't show empty ...
534
535
          // Find least seq value from messages for future history queries
          for (line::Message &msg: recent_msgs) {
4834479b   Matti Virkkunen   Add /history comm...
536
537
538
539
540
541
542
543
              if (msg.contentMetadata.count("seq")) {
                  try {
                      int64_t seq = std::stoll(msg.contentMetadata["seq"]);
  
                      if (new_end_seq == -1 || seq < new_end_seq)
                          new_end_seq = seq;
                  } catch (...) { /* ignore parse error */ }
              }
2a2bec32   Matti Virkkunen   Don't show empty ...
544
          }
4834479b   Matti Virkkunen   Add /history comm...
545
  
2a2bec32   Matti Virkkunen   Don't show empty ...
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
          if (queue) {
              // If there's a message queue, remove any already-queued messages in the recent message
              // list to prevent them showing up twice.
  
              recent_msgs.erase(
                  std::remove_if(
                      recent_msgs.begin(),
                      recent_msgs.end(),
                      [&queue](line::Message &rm) {
                          auto r = find_if(
                              queue->begin(),
                              queue->end(),
                              [&rm](line::Message &qm) { return qm.id == rm.id; });
  
                          return (r != queue->end());
                      }),
                  recent_msgs.end());
          }
2fcd68c7   Matti Virkkunen   Show history begi...
564
  
2a2bec32   Matti Virkkunen   Don't show empty ...
565
566
567
568
569
570
571
572
573
          if (recent_msgs.size()) {
              purple_conversation_write(
                  conv,
                  "",
                  "<strong>Message history</strong>",
                  (PurpleMessageFlags)PURPLE_MESSAGE_RAW,
                  time(NULL));
  
              for (auto msgi = recent_msgs.rbegin(); msgi != recent_msgs.rend(); msgi++)
61ed212d   Matti Virkkunen   Split purpleline....
574
                  write_message(*msgi, true);
2a2bec32   Matti Virkkunen   Don't show empty ...
575
576
577
578
579
580
581
582
583
584
  
              purple_conversation_write(
                  conv,
                  "",
                  "<hr>",
                  (PurpleMessageFlags)PURPLE_MESSAGE_RAW,
                  time(NULL));
          } else {
              if (requested) {
                  // If history was requested by the user and there is none, let the user know
2fcd68c7   Matti Virkkunen   Show history begi...
585
  
2a2bec32   Matti Virkkunen   Don't show empty ...
586
587
588
589
590
591
592
                  purple_conversation_write(
                      conv,
                      "",
                      "<strong>No more history</strong>",
                      (PurpleMessageFlags)PURPLE_MESSAGE_RAW,
                      time(NULL));
              }
2fcd68c7   Matti Virkkunen   Show history begi...
593
594
          }
  
2fcd68c7   Matti Virkkunen   Show history begi...
595
596
597
          // If there's a message queue, play it back now
          if (queue) {
              for (line::Message &msg: *queue)
61ed212d   Matti Virkkunen   Split purpleline....
598
                  write_message(msg, false);
2fcd68c7   Matti Virkkunen   Show history begi...
599
600
  
              delete queue;
87e4db97   Matti Virkkunen   Fetch recent mess...
601
          }
4834479b   Matti Virkkunen   Add /history comm...
602
603
604
605
606
607
  
          int64_t *end_seq_p = (int64_t *)purple_conversation_get_data(conv, "line-end-seq");
          if (end_seq_p)
              delete end_seq_p;
  
          purple_conversation_set_data(conv, "line-end-seq", new int64_t(new_end_seq));
318f26bd   Matti Virkkunen   Add logging for h...
608
609
  
          purple_debug_info("line", "History done: new_end_seq=%" G_GINT64_FORMAT "\n", new_end_seq);
87e4db97   Matti Virkkunen   Fetch recent mess...
610
611
612
      });
  }
  
2fcd68c7   Matti Virkkunen   Show history begi...
613
614
615
616
  void PurpleLine::signal_deleting_conversation(PurpleConversation *conv) {
      if (purple_conversation_get_account(conv) != acct)
          return;
  
5892b95c   Matti Virkkunen   Added /open comma...
617
      auto queue = (std::vector<line::Message> *)
2fcd68c7   Matti Virkkunen   Show history begi...
618
619
620
621
622
623
          purple_conversation_get_data(conv, "line-message-queue");
  
      if (queue) {
          purple_conversation_set_data(conv, "line-message-queue", nullptr);
          delete queue;
      }
4834479b   Matti Virkkunen   Add /history comm...
624
625
626
627
628
629
  
      int64_t *end_seq_p = (int64_t *)purple_conversation_get_data(conv, "line-end-seq");
      if (end_seq_p) {
          purple_conversation_set_data(conv, "line-end-seq", nullptr);
          delete end_seq_p;
      }
5892b95c   Matti Virkkunen   Added /open comma...
630
631
632
633
634
635
  
      auto atts = (std::vector<Attachment> *)purple_conversation_get_data(conv, "line-attachments");
      if (atts) {
          purple_conversation_set_data(conv, "line-attachments", nullptr);
          delete atts;
      }
2fcd68c7   Matti Virkkunen   Show history begi...
636
637
  }
  
38a0988d   Matti Virkkunen   Implemented leavi...
638
639
640
641
642
643
  void PurpleLine::notify_error(std::string msg) {
      purple_notify_error(
          (void *)conn,
          "LINE error",
          msg.c_str(),
          nullptr);
89f93032   Matti Virkkunen   Implement find_bl...
644
  }