source: protocols/twitter/twitter_lib.c @ 3f44e43

Last change on this file since 3f44e43 was 537d9b9, checked in by dequis <dx@…>, at 2016-11-20T08:40:36Z

Merge master up to commit '9f03c47' into parson

  • Property mode set to 100644
File size: 47.0 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Simple module to facilitate twitter functionality.                       *
5*                                                                           *
6*  Copyright 2009-2010 Geert Mulders <g.c.w.m.mulders@gmail.com>            *
7*  Copyright 2010-2013 Wilmer van der Gaast <wilmer@gaast.net>              *
8*                                                                           *
9*  This library is free software; you can redistribute it and/or            *
10*  modify it under the terms of the GNU Lesser General Public               *
11*  License as published by the Free Software Foundation, version            *
12*  2.1.                                                                     *
13*                                                                           *
14*  This library is distributed in the hope that it will be useful,          *
15*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
16*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
17*  Lesser General Public License for more details.                          *
18*                                                                           *
19*  You should have received a copy of the GNU Lesser General Public License *
20*  along with this library; if not, write to the Free Software Foundation,  *
21*  Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA           *
22*                                                                           *
23****************************************************************************/
24
25/* For strptime(): */
26#if (__sun)
27#else
28#define _XOPEN_SOURCE
29#endif
30
31#include "twitter_http.h"
32#include "twitter.h"
33#include "bitlbee.h"
34#include "url.h"
35#include "misc.h"
36#include "base64.h"
37#include "twitter_lib.h"
38#include "parson.h"
39#include <ctype.h>
40#include <errno.h>
41
42#define TXL_STATUS 1
43#define TXL_USER 2
44#define TXL_ID 3
45
46struct twitter_xml_list {
47        int type;
48        gint64 next_cursor;
49        GSList *list;
50};
51
52struct twitter_xml_user {
53        guint64 uid;
54        char *name;
55        char *screen_name;
56};
57
58struct twitter_xml_status {
59        time_t created_at;
60        char *text;
61        struct twitter_xml_user *user;
62        guint64 id, rt_id; /* Usually equal, with RTs id == *original* id */
63        guint64 reply_to;
64        gboolean from_filter;
65};
66
67#define JSON_O_FOREACH(o, k, v) \
68    const char *k; const JSON_Value *v; int __i; \
69    for (__i = 0; json_object_get_tuple(o, __i, &k, &v); __i++)
70
71/**
72 * Frees a twitter_xml_user struct.
73 */
74static void txu_free(struct twitter_xml_user *txu)
75{
76        if (txu == NULL) {
77                return;
78        }
79
80        g_free(txu->name);
81        g_free(txu->screen_name);
82        g_free(txu);
83}
84
85/**
86 * Frees a twitter_xml_status struct.
87 */
88static void txs_free(struct twitter_xml_status *txs)
89{
90        if (txs == NULL) {
91                return;
92        }
93
94        g_free(txs->text);
95        txu_free(txs->user);
96        g_free(txs);
97}
98
99/**
100 * Free a twitter_xml_list struct.
101 * type is the type of list the struct holds.
102 */
103static void txl_free(struct twitter_xml_list *txl)
104{
105        GSList *l;
106
107        if (txl == NULL) {
108                return;
109        }
110
111        for (l = txl->list; l; l = g_slist_next(l)) {
112                if (txl->type == TXL_STATUS) {
113                        txs_free((struct twitter_xml_status *) l->data);
114                } else if (txl->type == TXL_ID) {
115                        g_free(l->data);
116                } else if (txl->type == TXL_USER) {
117                        txu_free(l->data);
118                }
119        }
120
121        g_slist_free(txl->list);
122        g_free(txl);
123}
124
125/**
126 * Compare status elements
127 */
128static gint twitter_compare_elements(gconstpointer a, gconstpointer b)
129{
130        struct twitter_xml_status *a_status = (struct twitter_xml_status *) a;
131        struct twitter_xml_status *b_status = (struct twitter_xml_status *) b;
132
133        if (a_status->created_at < b_status->created_at) {
134                return -1;
135        } else if (a_status->created_at > b_status->created_at) {
136                return 1;
137        } else {
138                return 0;
139        }
140}
141
142/**
143 * Add a buddy if it is not already added, set the status to logged in.
144 */
145static void twitter_add_buddy(struct im_connection *ic, char *name, const char *fullname)
146{
147        struct twitter_data *td = ic->proto_data;
148
149        // Check if the buddy is already in the buddy list.
150        if (!bee_user_by_handle(ic->bee, ic, name)) {
151                // The buddy is not in the list, add the buddy and set the status to logged in.
152                imcb_add_buddy(ic, name, NULL);
153                imcb_rename_buddy(ic, name, fullname);
154                if (td->flags & TWITTER_MODE_CHAT) {
155                        /* Necessary so that nicks always get translated to the
156                           exact Twitter username. */
157                        imcb_buddy_nick_hint(ic, name, name);
158                        if (td->timeline_gc) {
159                                imcb_chat_add_buddy(td->timeline_gc, name);
160                        }
161                } else if (td->flags & TWITTER_MODE_MANY) {
162                        imcb_buddy_status(ic, name, OPT_LOGGED_IN, NULL, NULL);
163                }
164        }
165}
166
167/* Warning: May return a malloc()ed value, which will be free()d on the next
168   call. Only for short-term use. NOT THREADSAFE!  */
169char *twitter_parse_error(struct http_request *req)
170{
171        static char *ret = NULL;
172        JSON_Value *root, *err;
173
174        g_free(ret);
175        ret = NULL;
176
177        if (req->body_size > 0) {
178                root = json_parse_string(req->reply_body);
179                err = json_object_get_value(json_object(root), "errors");
180                if (err && json_type(err) == JSONArray &&
181                    (err = json_array_get_value(json_array(err), 0)) &&
182                    json_type(err) == JSONObject) {
183                        const char *msg = json_object_get_string(json_object(err), "message");
184                        if (msg) {
185                                ret = g_strdup_printf("%s (%s)", req->status_string, msg);
186                        }
187                }
188                json_value_free(root);
189        }
190
191        return ret ? ret : req->status_string;
192}
193
194/* WATCH OUT: This function might or might not destroy your connection.
195   Sub-optimal indeed, but just be careful when this returns NULL! */
196static JSON_Value *twitter_parse_response(struct im_connection *ic, struct http_request *req)
197{
198        gboolean logging_in = !(ic->flags & OPT_LOGGED_IN);
199        gboolean periodic;
200        struct twitter_data *td = ic->proto_data;
201        JSON_Value *ret;
202        char path[64] = "", *s;
203
204        if ((s = strchr(req->request, ' '))) {
205                path[sizeof(path) - 1] = '\0';
206                strncpy(path, s + 1, sizeof(path) - 1);
207                if ((s = strchr(path, '?')) || (s = strchr(path, ' '))) {
208                        *s = '\0';
209                }
210        }
211
212        /* Kinda nasty. :-( Trying to suppress error messages, but only
213           for periodic (i.e. mentions/timeline) queries. */
214        periodic = strstr(path, "timeline") || strstr(path, "mentions");
215
216        if (req->status_code == 401 && logging_in) {
217                /* IIRC Twitter once had an outage where they were randomly
218                   throwing 401s so I'll keep treating this one as fatal
219                   only during login. */
220                imcb_error(ic, "Authentication failure (%s)",
221                           twitter_parse_error(req));
222                imc_logout(ic, FALSE);
223                return NULL;
224        } else if (req->status_code != 200) {
225                // It didn't go well, output the error and return.
226                if (!periodic || logging_in || ++td->http_fails >= 5) {
227                        twitter_log(ic, "Error: Could not retrieve %s: %s",
228                                    path, twitter_parse_error(req));
229                }
230
231                if (logging_in) {
232                        imc_logout(ic, TRUE);
233                }
234                return NULL;
235        } else {
236                td->http_fails = 0;
237        }
238
239        if ((ret = json_parse_string(req->reply_body)) == NULL) {
240                imcb_error(ic, "Could not retrieve %s: %s",
241                           path, "XML parse error");
242        }
243        return ret;
244}
245
246static void twitter_http_get_friends_ids(struct http_request *req);
247static void twitter_http_get_mutes_ids(struct http_request *req);
248static void twitter_http_get_noretweets_ids(struct http_request *req);
249
250/**
251 * Get the friends ids.
252 */
253void twitter_get_friends_ids(struct im_connection *ic, gint64 next_cursor)
254{
255        // Primitive, but hey! It works...
256        char *args[2];
257
258        args[0] = "cursor";
259        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
260        twitter_http(ic, TWITTER_FRIENDS_IDS_URL, twitter_http_get_friends_ids, ic, 0, args, 2);
261
262        g_free(args[1]);
263}
264
265/**
266 * Get the muted users ids.
267 */
268void twitter_get_mutes_ids(struct im_connection *ic, gint64 next_cursor)
269{
270        char *args[2];
271
272        args[0] = "cursor";
273        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
274        twitter_http(ic, TWITTER_MUTES_IDS_URL, twitter_http_get_mutes_ids, ic, 0, args, 2);
275
276        g_free(args[1]);
277}
278
279/**
280 * Get the ids for users from whom we should ignore retweets.
281 */
282void twitter_get_noretweets_ids(struct im_connection *ic, gint64 next_cursor)
283{
284        char *args[2];
285
286        args[0] = "cursor";
287        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
288        twitter_http(ic, TWITTER_NORETWEETS_IDS_URL, twitter_http_get_noretweets_ids, ic, 0, args, 2);
289
290        g_free(args[1]);
291}
292
293/**
294 * Fill a list of ids.
295 */
296static gboolean twitter_xt_get_friends_id_list(JSON_Value *node, struct twitter_xml_list *txl)
297{
298        JSON_Array *c;
299        int i;
300
301        // Set the list type.
302        txl->type = TXL_ID;
303
304        if (!(c = json_object_get_array(json_object(node), "ids"))) {
305                return FALSE;
306        }
307
308        for (i = 0; i < json_array_get_count(c); i++) {
309                jint id = json_array_get_integer(c, i);
310
311                txl->list = g_slist_prepend(txl->list,
312                                            g_strdup_printf("%lld", id));
313        }
314
315        JSON_Value *next = json_object_get_value(json_object(node), "next_cursor");
316        if (next && json_type(next) == JSONInteger) {
317                txl->next_cursor = json_integer(next);
318        } else {
319                txl->next_cursor = -1;
320        }
321
322        return TRUE;
323}
324
325static void twitter_get_users_lookup(struct im_connection *ic);
326
327/**
328 * Callback for getting the friends ids.
329 */
330static void twitter_http_get_friends_ids(struct http_request *req)
331{
332        struct im_connection *ic;
333        JSON_Value *parsed;
334        struct twitter_xml_list *txl;
335        struct twitter_data *td;
336
337        ic = req->data;
338
339        // Check if the connection is still active.
340        if (!g_slist_find(twitter_connections, ic)) {
341                return;
342        }
343
344        td = ic->proto_data;
345
346        // Parse the data.
347        if (!(parsed = twitter_parse_response(ic, req))) {
348                return;
349        }
350
351        txl = g_new0(struct twitter_xml_list, 1);
352        txl->list = td->follow_ids;
353
354        twitter_xt_get_friends_id_list(parsed, txl);
355        json_value_free(parsed);
356
357        td->follow_ids = txl->list;
358        if (txl->next_cursor) {
359                /* These were just numbers. Up to 4000 in a response AFAIK so if we get here
360                   we may be using a spammer account. \o/ */
361                twitter_get_friends_ids(ic, txl->next_cursor);
362        } else {
363                /* Now to convert all those numbers into names.. */
364                twitter_get_users_lookup(ic);
365        }
366
367        txl->list = NULL;
368        txl_free(txl);
369}
370
371/**
372 * Callback for getting the mutes ids.
373 */
374static void twitter_http_get_mutes_ids(struct http_request *req)
375{
376        struct im_connection *ic = req->data;
377        JSON_Value *parsed;
378        struct twitter_xml_list *txl;
379        struct twitter_data *td;
380
381        // Check if the connection is stil active
382        if (!g_slist_find(twitter_connections, ic)) {
383                return;
384        }
385
386        td = ic->proto_data;
387
388        if (req->status_code != 200) {
389                /* Fail silently */
390                return;
391        }
392
393        // Parse the data.
394        if (!(parsed = twitter_parse_response(ic, req))) {
395                return;
396        }
397
398        txl = g_new0(struct twitter_xml_list, 1);
399        txl->list = td->mutes_ids;
400
401        /* mute ids API response is similar enough to friends response
402           to reuse this method */
403        twitter_xt_get_friends_id_list(parsed, txl);
404        json_value_free(parsed);
405
406        td->mutes_ids = txl->list;
407        if (txl->next_cursor) {
408                /* Recurse while there are still more pages */
409                twitter_get_mutes_ids(ic, txl->next_cursor);
410        }
411
412        txl->list = NULL;
413        txl_free(txl);
414}
415
416/**
417 * Callback for getting the no-retweets ids.
418 */
419static void twitter_http_get_noretweets_ids(struct http_request *req)
420{
421        struct im_connection *ic = req->data;
422        JSON_Value *parsed;
423        struct twitter_xml_list *txl;
424        struct twitter_data *td;
425
426        // Check if the connection is stil active
427        if (!g_slist_find(twitter_connections, ic)) {
428                return;
429        }
430
431        if (req->status_code != 200) {
432                /* Fail silently */
433                return;
434        }
435
436        td = ic->proto_data;
437
438        // Parse the data.
439        if (!(parsed = twitter_parse_response(ic, req))) {
440                return;
441        }
442
443        txl = g_new0(struct twitter_xml_list, 1);
444        txl->list = td->noretweets_ids;
445       
446        // Process the retweet ids
447        txl->type = TXL_ID;
448        if (json_type(parsed) == JSONArray) {
449                JSON_Array *arr = json_array(parsed);
450                unsigned int i;
451                for (i = 0; i < json_array_get_count(arr); i++) {
452                        jint id = json_array_get_integer(arr, i);
453                        txl->list = g_slist_prepend(txl->list,
454                                                    g_strdup_printf("%lld", id));
455                }
456        }
457
458        json_value_free(parsed);
459        td->noretweets_ids = txl->list;
460
461        txl->list = NULL;
462        txl_free(txl);
463}
464
465static gboolean twitter_xt_get_users(JSON_Value *node, struct twitter_xml_list *txl);
466static void twitter_http_get_users_lookup(struct http_request *req);
467
468static void twitter_get_users_lookup(struct im_connection *ic)
469{
470        struct twitter_data *td = ic->proto_data;
471        char *args[2] = {
472                "user_id",
473                NULL,
474        };
475        GString *ids = g_string_new("");
476        int i;
477
478        /* We can request up to 100 users at a time. */
479        for (i = 0; i < 100 && td->follow_ids; i++) {
480                g_string_append_printf(ids, ",%s", (char *) td->follow_ids->data);
481                g_free(td->follow_ids->data);
482                td->follow_ids = g_slist_remove(td->follow_ids, td->follow_ids->data);
483        }
484        if (ids->len > 0) {
485                args[1] = ids->str + 1;
486                /* POST, because I think ids can be up to 1KB long. */
487                twitter_http(ic, TWITTER_USERS_LOOKUP_URL, twitter_http_get_users_lookup, ic, 1, args, 2);
488        } else {
489                /* We have all users. Continue with login. (Get statuses.) */
490                td->flags |= TWITTER_HAVE_FRIENDS;
491                twitter_login_finish(ic);
492        }
493        g_string_free(ids, TRUE);
494}
495
496/**
497 * Callback for getting (twitter)friends...
498 *
499 * Be afraid, be very afraid! This function will potentially add hundreds of "friends". "Who has
500 * hundreds of friends?" you wonder? You probably not, since you are reading the source of
501 * BitlBee... Get a life and meet new people!
502 */
503static void twitter_http_get_users_lookup(struct http_request *req)
504{
505        struct im_connection *ic = req->data;
506        JSON_Value *parsed;
507        struct twitter_xml_list *txl;
508        GSList *l = NULL;
509        struct twitter_xml_user *user;
510
511        // Check if the connection is still active.
512        if (!g_slist_find(twitter_connections, ic)) {
513                return;
514        }
515
516        // Get the user list from the parsed xml feed.
517        if (!(parsed = twitter_parse_response(ic, req))) {
518                return;
519        }
520
521        txl = g_new0(struct twitter_xml_list, 1);
522        txl->list = NULL;
523
524        twitter_xt_get_users(parsed, txl);
525        json_value_free(parsed);
526
527        // Add the users as buddies.
528        for (l = txl->list; l; l = g_slist_next(l)) {
529                user = l->data;
530                twitter_add_buddy(ic, user->screen_name, user->name);
531        }
532
533        // Free the structure.
534        txl_free(txl);
535
536        twitter_get_users_lookup(ic);
537}
538
539struct twitter_xml_user *twitter_xt_get_user(const JSON_Object *node)
540{
541        struct twitter_xml_user *txu;
542       
543        if (!node)
544                return NULL;
545
546        txu = g_new0(struct twitter_xml_user, 1);
547        txu->name = g_strdup(json_object_get_string(node, "name"));
548        txu->screen_name = g_strdup(json_object_get_string(node, "screen_name"));
549        txu->uid = json_object_get_integer(node, "id");
550
551        return txu;
552}
553
554/**
555 * Function to fill a twitter_xml_list struct.
556 * It sets:
557 *  - all <user>s from the <users> element.
558 */
559static gboolean twitter_xt_get_users(JSON_Value *node, struct twitter_xml_list *txl)
560{
561        struct twitter_xml_user *txu;
562        int i;
563
564        // Set the type of the list.
565        txl->type = TXL_USER;
566
567        if (json_type(node) != JSONArray) {
568                return FALSE;
569        }
570       
571        // The root <users> node should hold the list of users <user>
572        // Walk over the nodes children.
573        JSON_Array *arr = json_array(node);
574        for (i = 0; i < json_array_get_count(arr); i++) {
575                JSON_Object *o = json_array_get_object(arr, i);
576                if (!o)
577                        continue;
578                txu = twitter_xt_get_user(o);
579                if (txu) {
580                        txl->list = g_slist_prepend(txl->list, txu);
581                }
582        }
583
584        return TRUE;
585}
586
587#ifdef __GLIBC__
588#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S %z %Y"
589#else
590#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S +0000 %Y"
591#endif
592
593static void expand_entities(char **text, const JSON_Object *node, const JSON_Object *extended_node);
594
595/**
596 * Function to fill a twitter_xml_status struct.
597 * It sets:
598 *  - the status text and
599 *  - the created_at timestamp and
600 *  - the status id and
601 *  - the user in a twitter_xml_user struct.
602 */
603static struct twitter_xml_status *twitter_xt_get_status(const JSON_Object *node)
604{
605        struct twitter_xml_status *txs = {0};
606        const JSON_Object *rt = NULL;
607        const JSON_Value *text_value = NULL;
608        const JSON_Object *extended_node = NULL;
609
610        if (!node) {
611                return FALSE;
612        }
613        txs = g_new0(struct twitter_xml_status, 1);
614
615        JSON_O_FOREACH(node, k, v) {
616                if (strcmp("text", k) == 0 && json_type(v) == JSONString && text_value == NULL) {
617                        text_value = v;
618                } else if (strcmp("full_text", k) == 0 && json_type(v) == JSONString) {
619                        text_value = v;
620                } else if (strcmp("extended_tweet", k) == 0 && json_type(v) == JSONObject) {
621                        text_value = json_object_get_value(json_object(v), "full_text");
622                        extended_node = json_object(v);
623                } else if (strcmp("retweeted_status", k) == 0 && (rt = json_object(v))) {
624                        // Handling below.
625                } else if (strcmp("created_at", k) == 0 && json_type(v) == JSONString) {
626                        struct tm parsed;
627
628                        /* Very sensitive to changes to the formatting of
629                           this field. :-( Also assumes the timezone used
630                           is UTC since C time handling functions suck. */
631                        if (strptime(json_string(v), TWITTER_TIME_FORMAT, &parsed) != NULL) {
632                                txs->created_at = mktime_utc(&parsed);
633                        }
634                } else if (strcmp("user", k) == 0 && json_type(v) == JSONObject) {
635                        txs->user = twitter_xt_get_user(json_object(v));
636                } else if (strcmp("id", k) == 0 && json_type(v) == JSONInteger) {
637                        txs->rt_id = txs->id = json_integer(v);
638                } else if (strcmp("in_reply_to_status_id", k) == 0 && json_type(v) == JSONInteger) {
639                        txs->reply_to = json_integer(v);
640                }
641        }
642
643        /* If it's a (truncated) retweet, get the original. Even if the API claims it
644           wasn't truncated because it may be lying. */
645        if (rt) {
646                struct twitter_xml_status *rtxs = twitter_xt_get_status(rt);
647                if (rtxs) {
648                        txs->text = g_strdup_printf("RT @%s: %s", rtxs->user->screen_name, rtxs->text);
649                        txs->id = rtxs->id;
650                        txs_free(rtxs);
651                }
652        } else if (text_value && json_type(text_value) == JSONString) {
653                txs->text = g_strdup(json_string(text_value));
654                strip_html(txs->text);
655                expand_entities(&txs->text, node, extended_node);
656        }
657
658        if (txs->text && txs->user && txs->id) {
659                return txs;
660        }
661
662        txs_free(txs);
663        return NULL;
664}
665
666/**
667 * Function to fill a twitter_xml_status struct (DM variant).
668 */
669static struct twitter_xml_status *twitter_xt_get_dm(const JSON_Object *node)
670{
671        struct twitter_xml_status *txs;
672
673        if (!node) {
674                return FALSE;
675        }
676        txs = g_new0(struct twitter_xml_status, 1);
677
678        JSON_O_FOREACH(node, k, v) {
679                if (strcmp("text", k) == 0 && (txs->text = g_strdup(json_string(v)))) {
680                        strip_html(txs->text);
681                } else if (strcmp("created_at", k) == 0 && json_type(v) == JSONString) {
682                        struct tm parsed;
683
684                        /* Very sensitive to changes to the formatting of
685                           this field. :-( Also assumes the timezone used
686                           is UTC since C time handling functions suck. */
687                        if (strptime(json_string(v), TWITTER_TIME_FORMAT, &parsed) != NULL) {
688                                txs->created_at = mktime_utc(&parsed);
689                        }
690                } else if (strcmp("sender", k) == 0 && json_type(v) == JSONObject) {
691                        txs->user = twitter_xt_get_user(json_object(v));
692                } else if (strcmp("id", k) == 0 && json_type(v) == JSONInteger) {
693                        txs->id = json_integer(v);
694                }
695        }
696
697        expand_entities(&txs->text, node, NULL);
698
699        if (txs->text && txs->user && txs->id) {
700                return txs;
701        }
702
703        txs_free(txs);
704        return NULL;
705}
706
707static void expand_entities(char **text, const JSON_Object *node, const JSON_Object *extended_node)
708{
709        JSON_Object *entities, *extended_entities, *quoted;
710        char *quote_url = NULL, *quote_text = NULL;
711
712        if (!(entities = json_object_get_object(node, "entities")))
713                return;
714        if ((quoted = json_object_get_object(node, "quoted_status"))) {
715                /* New "retweets with comments" feature. Note that this info
716                 * seems to be included in the streaming API only! Grab the
717                 * full message and try to insert it when we run into the
718                 * Tweet entity. */
719                struct twitter_xml_status *txs = twitter_xt_get_status(quoted);
720                quote_text = g_strdup_printf("@%s: %s", txs->user->screen_name, txs->text);
721                quote_url = g_strdup_printf("%s/status/%" G_GUINT64_FORMAT, txs->user->screen_name, txs->id);
722                txs_free(txs);
723        } else {
724                quoted = NULL;
725        }
726
727        if (extended_node) {
728                extended_entities = json_object_get_object(extended_node, "entities");
729                if (extended_entities) {
730                        entities = extended_entities;
731                }
732        }
733
734        JSON_O_FOREACH(entities, k, v) {
735                int i;
736
737                if (json_type(v) != JSONArray) {
738                        continue;
739                }
740                if (strcmp(k, "urls") != 0 && strcmp(k, "media") != 0) {
741                        continue;
742                }
743
744                for (i = 0; i < json_array_get_count(json_array(v)); i++) {
745                        const char *format = "%s%s <%s>%s";
746                        JSON_Object *r = json_array_get_object(json_array(v), i);
747
748                        if (!r) {
749                                continue;
750                        }
751
752                        const char *kort = json_object_get_string(r, "url");
753                        const char *disp = json_object_get_string(r, "display_url");
754                        const char *full = json_object_get_string(r, "expanded_url");
755                        char *pos, *new;
756
757                        if (!kort || !disp || !(pos = strstr(*text, kort))) {
758                                continue;
759                        }
760                        if (quote_url && strstr(full, quote_url)) {
761                                format = "%s<%s> [%s]%s";
762                                disp = quote_text;
763                        }
764
765                        *pos = '\0';
766                        new = g_strdup_printf(format, *text, kort,
767                                              disp, pos + strlen(kort));
768
769                        g_free(*text);
770                        *text = new;
771                }
772        }
773        g_free(quote_text);
774        g_free(quote_url);
775}
776
777/**
778 * Function to fill a twitter_xml_list struct.
779 * It sets:
780 *  - all <status>es within the <status> element and
781 *  - the next_cursor.
782 */
783static gboolean twitter_xt_get_status_list(struct im_connection *ic, const JSON_Value *node,
784                                           struct twitter_xml_list *txl)
785{
786        struct twitter_xml_status *txs;
787        int i;
788
789        // Set the type of the list.
790        txl->type = TXL_STATUS;
791
792        if (json_type(node) != JSONArray) {
793                return FALSE;
794        }
795
796        // The root <statuses> node should hold the list of statuses <status>
797        // Walk over the nodes children.
798        for (i = 0; i < json_array_get_count(json_array(node)); i++) {
799                txs = twitter_xt_get_status(json_array_get_object(json_array(node), i));
800                if (!txs) {
801                        continue;
802                }
803
804                txl->list = g_slist_prepend(txl->list, txs);
805        }
806
807        return TRUE;
808}
809
810/* Will log messages either way. Need to keep track of IDs for stream deduping.
811   Plus, show_ids is on by default and I don't see why anyone would disable it. */
812static char *twitter_msg_add_id(struct im_connection *ic,
813                                struct twitter_xml_status *txs, const char *prefix)
814{
815        struct twitter_data *td = ic->proto_data;
816        int reply_to = -1;
817        bee_user_t *bu;
818
819        if (txs->reply_to) {
820                int i;
821                for (i = 0; i < TWITTER_LOG_LENGTH; i++) {
822                        if (td->log[i].id == txs->reply_to) {
823                                reply_to = i;
824                                break;
825                        }
826                }
827        }
828
829        if (txs->user && txs->user->screen_name &&
830            (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
831                struct twitter_user_data *tud = bu->data;
832
833                if (txs->id > tud->last_id) {
834                        tud->last_id = txs->id;
835                        tud->last_time = txs->created_at;
836                }
837        }
838
839        td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH;
840        td->log[td->log_id].id = txs->id;
841        td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name);
842
843        /* This is all getting hairy. :-( If we RT'ed something ourselves,
844           remember OUR id instead so undo will work. In other cases, the
845           original tweet's id should be remembered for deduplicating. */
846        if (g_strcasecmp(txs->user->screen_name, td->user) == 0) {
847                td->log[td->log_id].id = txs->rt_id;
848                /* More useful than NULL. */
849                td->log[td->log_id].bu = &twitter_log_local_user;
850        }
851
852        if (set_getbool(&ic->acc->set, "show_ids")) {
853                if (reply_to != -1) {
854                        return g_strdup_printf("\002[\002%02x->%02x\002]\002 %s%s",
855                                               td->log_id, reply_to, prefix, txs->text);
856                } else {
857                        return g_strdup_printf("\002[\002%02x\002]\002 %s%s",
858                                               td->log_id, prefix, txs->text);
859                }
860        } else {
861                if (*prefix) {
862                        return g_strconcat(prefix, txs->text, NULL);
863                } else {
864                        return NULL;
865                }
866        }
867}
868
869/**
870 * Function that is called to see the filter statuses in groupchat windows.
871 */
872static void twitter_status_show_filter(struct im_connection *ic, struct twitter_xml_status *status)
873{
874        struct twitter_data *td = ic->proto_data;
875        char *msg = twitter_msg_add_id(ic, status, "");
876        struct twitter_filter *tf;
877        GSList *f;
878        GSList *l;
879
880        for (f = td->filters; f; f = g_slist_next(f)) {
881                tf = f->data;
882
883                switch (tf->type) {
884                case TWITTER_FILTER_TYPE_FOLLOW:
885                        if (status->user->uid != tf->uid) {
886                                continue;
887                        }
888                        break;
889
890                case TWITTER_FILTER_TYPE_TRACK:
891                        if (strcasestr(status->text, tf->text) == NULL) {
892                                continue;
893                        }
894                        break;
895
896                default:
897                        continue;
898                }
899
900                for (l = tf->groupchats; l; l = g_slist_next(l)) {
901                        imcb_chat_msg(l->data, status->user->screen_name,
902                                      msg ? msg : status->text, 0, 0);
903                }
904        }
905
906        g_free(msg);
907}
908
909/**
910 * Function that is called to see the statuses in a groupchat window.
911 */
912static void twitter_status_show_chat(struct im_connection *ic, struct twitter_xml_status *status)
913{
914        struct twitter_data *td = ic->proto_data;
915        struct groupchat *gc;
916        gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0;
917        char *msg;
918
919        // Create a new groupchat if it does not exsist.
920        gc = twitter_groupchat_init(ic);
921
922        if (!me) {
923                /* MUST be done before twitter_msg_add_id() to avoid #872. */
924                twitter_add_buddy(ic, status->user->screen_name, status->user->name);
925        }
926        msg = twitter_msg_add_id(ic, status, "");
927
928        // Say it!
929        if (me) {
930                imcb_chat_log(gc, "You: %s", msg ? msg : status->text);
931        } else {
932                imcb_chat_msg(gc, status->user->screen_name,
933                              msg ? msg : status->text, 0, status->created_at);
934        }
935
936        g_free(msg);
937}
938
939/**
940 * Function that is called to see statuses as private messages.
941 */
942static void twitter_status_show_msg(struct im_connection *ic, struct twitter_xml_status *status)
943{
944        struct twitter_data *td = ic->proto_data;
945        char from[MAX_STRING] = "";
946        char *prefix = NULL, *text = NULL;
947        gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0;
948
949        if (td->flags & TWITTER_MODE_ONE) {
950                g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user);
951                from[MAX_STRING - 1] = '\0';
952        }
953
954        if (td->flags & TWITTER_MODE_ONE) {
955                prefix = g_strdup_printf("\002<\002%s\002>\002 ",
956                                         status->user->screen_name);
957        } else if (!me) {
958                twitter_add_buddy(ic, status->user->screen_name, status->user->name);
959        } else {
960                prefix = g_strdup("You: ");
961        }
962
963        text = twitter_msg_add_id(ic, status, prefix ? prefix : "");
964
965        imcb_buddy_msg(ic,
966                       *from ? from : status->user->screen_name,
967                       text ? text : status->text, 0, status->created_at);
968
969        g_free(text);
970        g_free(prefix);
971}
972
973static void twitter_status_show(struct im_connection *ic, struct twitter_xml_status *status)
974{
975        struct twitter_data *td = ic->proto_data;
976        char *last_id_str;
977        char *uid_str;
978
979        if (status->user == NULL || status->text == NULL) {
980                return;
981        }
982       
983        /* Check this is not a tweet that should be muted */
984        uid_str = g_strdup_printf("%" G_GUINT64_FORMAT, status->user->uid);
985
986        if (g_slist_find_custom(td->mutes_ids, uid_str, (GCompareFunc)strcmp)) {
987                g_free(uid_str);
988                return;
989        }
990        if (status->id != status->rt_id && g_slist_find_custom(td->noretweets_ids, uid_str, (GCompareFunc)strcmp)) {
991                g_free(uid_str);
992                return;
993        }
994
995        /* Grrrr. Would like to do this during parsing, but can't access
996           settings from there. */
997        if (set_getbool(&ic->acc->set, "strip_newlines")) {
998                strip_newlines(status->text);
999        }
1000
1001        if (status->from_filter) {
1002                twitter_status_show_filter(ic, status);
1003        } else if (td->flags & TWITTER_MODE_CHAT) {
1004                twitter_status_show_chat(ic, status);
1005        } else {
1006                twitter_status_show_msg(ic, status);
1007        }
1008
1009        // Update the timeline_id to hold the highest id, so that by the next request
1010        // we won't pick up the updates already in the list.
1011        td->timeline_id = MAX(td->timeline_id, status->rt_id);
1012
1013        last_id_str = g_strdup_printf("%" G_GUINT64_FORMAT, td->timeline_id);
1014        set_setstr(&ic->acc->set, "_last_tweet", last_id_str);
1015        g_free(last_id_str);
1016        g_free(uid_str);
1017}
1018
1019static gboolean twitter_stream_handle_object(struct im_connection *ic, JSON_Object *o, gboolean from_filter);
1020
1021static void twitter_http_stream(struct http_request *req)
1022{
1023        struct im_connection *ic = req->data;
1024        struct twitter_data *td;
1025        JSON_Value *parsed;
1026        int len = 0;
1027        char c, *nl;
1028        gboolean from_filter;
1029
1030        if (!g_slist_find(twitter_connections, ic)) {
1031                return;
1032        }
1033
1034        td = ic->proto_data;
1035
1036        if ((req->flags & HTTPC_EOF) || !req->reply_body) {
1037                if (req == td->stream) {
1038                        td->stream = NULL;
1039                } else if (req == td->filter_stream) {
1040                        td->filter_stream = NULL;
1041                }
1042
1043                imcb_error(ic, "Stream closed (%s)", req->status_string);
1044                if (req->status_code == 401) {
1045                        imcb_error(ic, "Check your system clock.");
1046                }
1047                imc_logout(ic, TRUE);
1048                return;
1049        }
1050
1051        if (req == td->stream) {
1052                ic->flags |= OPT_PONGED;
1053        }
1054
1055        /* MUST search for CRLF, not just LF:
1056           https://dev.twitter.com/docs/streaming-apis/processing#Parsing_responses */
1057        if (!(nl = strstr(req->reply_body, "\r\n"))) {
1058                return;
1059        }
1060
1061        len = nl - req->reply_body;
1062        if (len > 0) {
1063                c = req->reply_body[len];
1064                req->reply_body[len] = '\0';
1065
1066                if ((parsed = json_parse_string(req->reply_body))) {
1067                        from_filter = (req == td->filter_stream);
1068                        twitter_stream_handle_object(ic, json_object(parsed), from_filter);
1069                }
1070                json_value_free(parsed);
1071                req->reply_body[len] = c;
1072        }
1073
1074        http_flush_bytes(req, len + 2);
1075
1076        /* One notification might bring multiple events! */
1077        if (req->body_size > 0) {
1078                twitter_http_stream(req);
1079        }
1080}
1081
1082static gboolean twitter_stream_handle_event(struct im_connection *ic, JSON_Object *o);
1083static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs);
1084
1085static gboolean twitter_stream_handle_object(struct im_connection *ic, JSON_Object *o, gboolean from_filter)
1086{
1087        struct twitter_data *td = ic->proto_data;
1088        struct twitter_xml_status *txs;
1089        JSON_Object *c;
1090
1091        if ((txs = twitter_xt_get_status(o))) {
1092                txs->from_filter = from_filter;
1093                gboolean ret = twitter_stream_handle_status(ic, txs);
1094                txs_free(txs);
1095                return ret;
1096        } else if ((c = json_object_get_object(o, "direct_message")) &&
1097                   (txs = twitter_xt_get_dm(c))) {
1098                if (g_strcasecmp(txs->user->screen_name, td->user) != 0) {
1099                        imcb_buddy_msg(ic, txs->user->screen_name,
1100                                       txs->text, 0, txs->created_at);
1101                }
1102                txs_free(txs);
1103                return TRUE;
1104        } else if (json_object_get_string(o, "event")) {
1105                twitter_stream_handle_event(ic, o);
1106                return TRUE;
1107        } else if ((c = json_object_get_object(o, "disconnect"))) {
1108                /* HACK: Because we're inside an event handler, we can't just
1109                   disconnect here. Instead, just change the HTTP status string
1110                   into a Twitter status string. */
1111                char *reason = g_strdup(json_object_get_string(c, "reason"));
1112                if (reason) {
1113                        g_free(td->stream->status_string);
1114                        td->stream->status_string = reason;
1115                }
1116                return TRUE;
1117        }
1118        return FALSE;
1119}
1120
1121static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs)
1122{
1123        struct twitter_data *td = ic->proto_data;
1124        int i;
1125
1126        for (i = 0; i < TWITTER_LOG_LENGTH; i++) {
1127                if (td->log[i].id == txs->id) {
1128                        /* Got a duplicate (RT, probably). Drop it. */
1129                        return TRUE;
1130                }
1131        }
1132
1133        if (!(g_strcasecmp(txs->user->screen_name, td->user) == 0 ||
1134              set_getbool(&ic->acc->set, "fetch_mentions") ||
1135              bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
1136                /* Tweet is from an unknown person and the user does not want
1137                   to see @mentions, so drop it. twitter_stream_handle_event()
1138                   picks up new follows so this simple filter should be safe. */
1139                /* TODO: The streaming API seems to do poor @mention matching.
1140                   I.e. I'm getting mentions for @WilmerSomething, not just for
1141                   @Wilmer. But meh. You want spam, you get spam. */
1142                return TRUE;
1143        }
1144
1145        twitter_status_show(ic, txs);
1146
1147        return TRUE;
1148}
1149
1150static gboolean twitter_stream_handle_event(struct im_connection *ic, JSON_Object *o)
1151{
1152        struct twitter_data *td = ic->proto_data;
1153        JSON_Object *source = json_object_get_object(o, "source");
1154        JSON_Object *target = json_object_get_object(o, "target");
1155        const char *type = json_object_get_string(o, "event");
1156        struct twitter_xml_user *us = NULL;
1157        struct twitter_xml_user *ut = NULL;
1158
1159        if (!type || !source || !target) {
1160                return FALSE;
1161        }
1162
1163        if (strcmp(type, "follow") == 0) {
1164                us = twitter_xt_get_user(source);
1165                ut = twitter_xt_get_user(target);
1166                if (g_strcasecmp(us->screen_name, td->user) == 0) {
1167                        twitter_add_buddy(ic, ut->screen_name, ut->name);
1168                }
1169        } else if (strcmp(type, "mute") == 0) {
1170                GSList *found;
1171                char *uid_str;
1172                ut = twitter_xt_get_user(target);
1173                uid_str = g_strdup_printf("%" G_GUINT64_FORMAT, ut->uid);
1174                if (!(found = g_slist_find_custom(td->mutes_ids, uid_str,
1175                                                  (GCompareFunc)strcmp))) {
1176                        td->mutes_ids = g_slist_prepend(td->mutes_ids, uid_str);
1177                }
1178                twitter_log(ic, "Muted user %s", ut->screen_name);
1179                if (getenv("BITLBEE_DEBUG")) {
1180                        fprintf(stderr, "New mute: %s %"G_GUINT64_FORMAT"\n",
1181                                ut->screen_name, ut->uid);
1182                }
1183        } else if (strcmp(type, "unmute") == 0) {
1184                GSList *found;
1185                char *uid_str;
1186                ut = twitter_xt_get_user(target);
1187                uid_str = g_strdup_printf("%" G_GUINT64_FORMAT, ut->uid);
1188                if ((found = g_slist_find_custom(td->mutes_ids, uid_str,
1189                                                (GCompareFunc)strcmp))) {
1190                        char *found_str = found->data;
1191                        td->mutes_ids = g_slist_delete_link(td->mutes_ids, found);
1192                        g_free(found_str);
1193                }
1194                g_free(uid_str);
1195                twitter_log(ic, "Unmuted user %s", ut->screen_name);
1196                if (getenv("BITLBEE_DEBUG")) {
1197                        fprintf(stderr, "New unmute: %s %"G_GUINT64_FORMAT"\n",
1198                                ut->screen_name, ut->uid);
1199                }
1200        }
1201
1202        txu_free(us);
1203        txu_free(ut);
1204
1205        return TRUE;
1206}
1207
1208gboolean twitter_open_stream(struct im_connection *ic)
1209{
1210        struct twitter_data *td = ic->proto_data;
1211        char *args[2] = { "with", "followings" };
1212
1213        if ((td->stream = twitter_http(ic, TWITTER_USER_STREAM_URL,
1214                                       twitter_http_stream, ic, 0, args, 2))) {
1215                /* This flag must be enabled or we'll get no data until EOF
1216                   (which err, kind of, defeats the purpose of a streaming API). */
1217                td->stream->flags |= HTTPC_STREAMING;
1218                return TRUE;
1219        }
1220
1221        return FALSE;
1222}
1223
1224static gboolean twitter_filter_stream(struct im_connection *ic)
1225{
1226        struct twitter_data *td = ic->proto_data;
1227        char *args[4] = { "follow", NULL, "track", NULL };
1228        GString *followstr = g_string_new("");
1229        GString *trackstr = g_string_new("");
1230        gboolean ret = FALSE;
1231        struct twitter_filter *tf;
1232        GSList *l;
1233
1234        for (l = td->filters; l; l = g_slist_next(l)) {
1235                tf = l->data;
1236
1237                switch (tf->type) {
1238                case TWITTER_FILTER_TYPE_FOLLOW:
1239                        if (followstr->len > 0) {
1240                                g_string_append_c(followstr, ',');
1241                        }
1242
1243                        g_string_append_printf(followstr, "%" G_GUINT64_FORMAT,
1244                                               tf->uid);
1245                        break;
1246
1247                case TWITTER_FILTER_TYPE_TRACK:
1248                        if (trackstr->len > 0) {
1249                                g_string_append_c(trackstr, ',');
1250                        }
1251
1252                        g_string_append(trackstr, tf->text);
1253                        break;
1254
1255                default:
1256                        continue;
1257                }
1258        }
1259
1260        args[1] = followstr->str;
1261        args[3] = trackstr->str;
1262
1263        if (td->filter_stream) {
1264                http_close(td->filter_stream);
1265        }
1266
1267        if ((td->filter_stream = twitter_http(ic, TWITTER_FILTER_STREAM_URL,
1268                                              twitter_http_stream, ic, 0,
1269                                              args, 4))) {
1270                /* This flag must be enabled or we'll get no data until EOF
1271                   (which err, kind of, defeats the purpose of a streaming API). */
1272                td->filter_stream->flags |= HTTPC_STREAMING;
1273                ret = TRUE;
1274        }
1275
1276        g_string_free(followstr, TRUE);
1277        g_string_free(trackstr, TRUE);
1278
1279        return ret;
1280}
1281
1282static void twitter_filter_users_post(struct http_request *req)
1283{
1284        struct im_connection *ic = req->data;
1285        struct twitter_data *td;
1286        struct twitter_filter *tf;
1287        GList *users = NULL;
1288        JSON_Value *parsed;
1289        GString *fstr;
1290        GSList *l;
1291        GList *u;
1292        int i;
1293
1294        // Check if the connection is still active.
1295        if (!g_slist_find(twitter_connections, ic)) {
1296                return;
1297        }
1298
1299        td = ic->proto_data;
1300
1301        if (!(parsed = twitter_parse_response(ic, req))) {
1302                return;
1303        }
1304
1305        for (l = td->filters; l; l = g_slist_next(l)) {
1306                tf = l->data;
1307
1308                if (tf->type == TWITTER_FILTER_TYPE_FOLLOW) {
1309                        users = g_list_prepend(users, tf);
1310                }
1311        }
1312
1313        if (json_type(parsed) != JSONArray) {
1314                goto finish;
1315        }
1316
1317        for (i = 0; i < json_array_get_count(json_array(parsed)); i++) {
1318                JSON_Object *o = json_array_get_object(json_array(parsed), i);
1319                jint id = json_object_get_integer(o, "id");
1320                const char *name = json_object_get_string(o, "screen_name");
1321
1322                if (!name || !id) {
1323                        continue;
1324                }
1325
1326                for (u = users; u; u = g_list_next(u)) {
1327                        tf = u->data;
1328
1329                        if (g_strcasecmp(tf->text, name) == 0) {
1330                                tf->uid = id;
1331                                users = g_list_delete_link(users, u);
1332                                break;
1333                        }
1334                }
1335        }
1336
1337finish:
1338        json_value_free(parsed);
1339        twitter_filter_stream(ic);
1340
1341        if (!users) {
1342                return;
1343        }
1344
1345        fstr = g_string_new("");
1346
1347        for (u = users; u; u = g_list_next(u)) {
1348                if (fstr->len > 0) {
1349                        g_string_append(fstr, ", ");
1350                }
1351
1352                g_string_append(fstr, tf->text);
1353        }
1354
1355        imcb_error(ic, "Failed UID acquisitions: %s", fstr->str);
1356
1357        g_string_free(fstr, TRUE);
1358        g_list_free(users);
1359}
1360
1361gboolean twitter_open_filter_stream(struct im_connection *ic)
1362{
1363        struct twitter_data *td = ic->proto_data;
1364        char *args[2] = { "screen_name", NULL };
1365        GString *ustr = g_string_new("");
1366        struct twitter_filter *tf;
1367        struct http_request *req;
1368        GSList *l;
1369
1370        for (l = td->filters; l; l = g_slist_next(l)) {
1371                tf = l->data;
1372
1373                if (tf->type != TWITTER_FILTER_TYPE_FOLLOW || tf->uid != 0) {
1374                        continue;
1375                }
1376
1377                if (ustr->len > 0) {
1378                        g_string_append_c(ustr, ',');
1379                }
1380
1381                g_string_append(ustr, tf->text);
1382        }
1383
1384        if (ustr->len == 0) {
1385                g_string_free(ustr, TRUE);
1386                return twitter_filter_stream(ic);
1387        }
1388
1389        args[1] = ustr->str;
1390        req = twitter_http(ic, TWITTER_USERS_LOOKUP_URL,
1391                           twitter_filter_users_post,
1392                           ic, 0, args, 2);
1393
1394        g_string_free(ustr, TRUE);
1395        return req != NULL;
1396}
1397
1398static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor);
1399static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor);
1400
1401/**
1402 * Get the timeline with optionally mentions
1403 */
1404gboolean twitter_get_timeline(struct im_connection *ic, gint64 next_cursor)
1405{
1406        struct twitter_data *td = ic->proto_data;
1407        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
1408
1409        if (td->flags & TWITTER_DOING_TIMELINE) {
1410                if (++td->http_fails >= 5) {
1411                        imcb_error(ic, "Fetch timeout (%d)", td->flags);
1412                        imc_logout(ic, TRUE);
1413                        return FALSE;
1414                }
1415        }
1416
1417        td->flags |= TWITTER_DOING_TIMELINE;
1418
1419        twitter_get_home_timeline(ic, next_cursor);
1420
1421        if (include_mentions) {
1422                twitter_get_mentions(ic, next_cursor);
1423        }
1424
1425        return TRUE;
1426}
1427
1428/**
1429 * Call this one after receiving timeline/mentions. Show to user once we have
1430 * both.
1431 */
1432void twitter_flush_timeline(struct im_connection *ic)
1433{
1434        struct twitter_data *td = ic->proto_data;
1435        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
1436        int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions");
1437        struct twitter_xml_list *home_timeline = td->home_timeline_obj;
1438        struct twitter_xml_list *mentions = td->mentions_obj;
1439        guint64 last_id = 0;
1440        GSList *output = NULL;
1441        GSList *l;
1442
1443        imcb_connected(ic);
1444
1445        if (!(td->flags & TWITTER_GOT_TIMELINE)) {
1446                return;
1447        }
1448
1449        if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) {
1450                return;
1451        }
1452
1453        if (home_timeline && home_timeline->list) {
1454                for (l = home_timeline->list; l; l = g_slist_next(l)) {
1455                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
1456                }
1457        }
1458
1459        if (include_mentions && mentions && mentions->list) {
1460                for (l = mentions->list; l; l = g_slist_next(l)) {
1461                        if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) {
1462                                continue;
1463                        }
1464
1465                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
1466                }
1467        }
1468
1469        // See if the user wants to see the messages in a groupchat window or as private messages.
1470        while (output) {
1471                struct twitter_xml_status *txs = output->data;
1472                if (txs->id != last_id) {
1473                        twitter_status_show(ic, txs);
1474                }
1475                last_id = txs->id;
1476                output = g_slist_remove(output, txs);
1477        }
1478
1479        txl_free(home_timeline);
1480        txl_free(mentions);
1481
1482        td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS);
1483        td->home_timeline_obj = td->mentions_obj = NULL;
1484}
1485
1486static void twitter_http_get_home_timeline(struct http_request *req);
1487static void twitter_http_get_mentions(struct http_request *req);
1488
1489/**
1490 * Get the timeline.
1491 */
1492static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor)
1493{
1494        struct twitter_data *td = ic->proto_data;
1495
1496        txl_free(td->home_timeline_obj);
1497        td->home_timeline_obj = NULL;
1498        td->flags &= ~TWITTER_GOT_TIMELINE;
1499
1500        char *args[8];
1501        args[0] = "cursor";
1502        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
1503        args[2] = "include_entities";
1504        args[3] = "true";
1505        args[4] = "tweet_mode";
1506        args[5] = "extended";
1507        if (td->timeline_id) {
1508                args[6] = "since_id";
1509                args[7] = g_strdup_printf("%" G_GUINT64_FORMAT, td->timeline_id);
1510        }
1511
1512        if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args,
1513                         td->timeline_id ? 8 : 6) == NULL) {
1514                if (++td->http_fails >= 5) {
1515                        imcb_error(ic, "Could not retrieve %s: %s",
1516                                   TWITTER_HOME_TIMELINE_URL, "connection failed");
1517                }
1518                td->flags |= TWITTER_GOT_TIMELINE;
1519                twitter_flush_timeline(ic);
1520        }
1521
1522        g_free(args[1]);
1523        if (td->timeline_id) {
1524                g_free(args[7]);
1525        }
1526}
1527
1528/**
1529 * Get mentions.
1530 */
1531static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor)
1532{
1533        struct twitter_data *td = ic->proto_data;
1534
1535        txl_free(td->mentions_obj);
1536        td->mentions_obj = NULL;
1537        td->flags &= ~TWITTER_GOT_MENTIONS;
1538
1539        char *args[8];
1540        args[0] = "cursor";
1541        args[1] = g_strdup_printf("%" G_GINT64_FORMAT, next_cursor);
1542        args[2] = "include_entities";
1543        args[3] = "true";
1544        if (td->timeline_id) {
1545                args[4] = "since_id";
1546                args[5] = g_strdup_printf("%" G_GUINT64_FORMAT, td->timeline_id);
1547        } else {
1548                args[4] = "count";
1549                args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions"));
1550        }
1551        args[6] = "tweet_mode";
1552        args[7] = "extended";
1553
1554        if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions,
1555                         ic, 0, args, 8) == NULL) {
1556                if (++td->http_fails >= 5) {
1557                        imcb_error(ic, "Could not retrieve %s: %s",
1558                                   TWITTER_MENTIONS_URL, "connection failed");
1559                }
1560                td->flags |= TWITTER_GOT_MENTIONS;
1561                twitter_flush_timeline(ic);
1562        }
1563
1564        g_free(args[1]);
1565        g_free(args[5]);
1566}
1567
1568/**
1569 * Callback for getting the home timeline.
1570 */
1571static void twitter_http_get_home_timeline(struct http_request *req)
1572{
1573        struct im_connection *ic = req->data;
1574        struct twitter_data *td;
1575        JSON_Value *parsed;
1576        struct twitter_xml_list *txl;
1577
1578        // Check if the connection is still active.
1579        if (!g_slist_find(twitter_connections, ic)) {
1580                return;
1581        }
1582
1583        td = ic->proto_data;
1584
1585        // The root <statuses> node should hold the list of statuses <status>
1586        if (!(parsed = twitter_parse_response(ic, req))) {
1587                goto end;
1588        }
1589
1590        txl = g_new0(struct twitter_xml_list, 1);
1591        txl->list = NULL;
1592
1593        twitter_xt_get_status_list(ic, parsed, txl);
1594        json_value_free(parsed);
1595
1596        td->home_timeline_obj = txl;
1597
1598end:
1599        if (!g_slist_find(twitter_connections, ic)) {
1600                return;
1601        }
1602
1603        td->flags |= TWITTER_GOT_TIMELINE;
1604
1605        twitter_flush_timeline(ic);
1606}
1607
1608/**
1609 * Callback for getting mentions.
1610 */
1611static void twitter_http_get_mentions(struct http_request *req)
1612{
1613        struct im_connection *ic = req->data;
1614        struct twitter_data *td;
1615        JSON_Value *parsed;
1616        struct twitter_xml_list *txl;
1617
1618        // Check if the connection is still active.
1619        if (!g_slist_find(twitter_connections, ic)) {
1620                return;
1621        }
1622
1623        td = ic->proto_data;
1624
1625        // The root <statuses> node should hold the list of statuses <status>
1626        if (!(parsed = twitter_parse_response(ic, req))) {
1627                goto end;
1628        }
1629
1630        txl = g_new0(struct twitter_xml_list, 1);
1631        txl->list = NULL;
1632
1633        twitter_xt_get_status_list(ic, parsed, txl);
1634        json_value_free(parsed);
1635
1636        td->mentions_obj = txl;
1637
1638end:
1639        if (!g_slist_find(twitter_connections, ic)) {
1640                return;
1641        }
1642
1643        td->flags |= TWITTER_GOT_MENTIONS;
1644
1645        twitter_flush_timeline(ic);
1646}
1647
1648/**
1649 * Callback to use after sending a POST request to twitter.
1650 * (Generic, used for a few kinds of queries.)
1651 */
1652static void twitter_http_post(struct http_request *req)
1653{
1654        struct im_connection *ic = req->data;
1655        struct twitter_data *td;
1656        JSON_Value *parsed;
1657        jint id;
1658
1659        // Check if the connection is still active.
1660        if (!g_slist_find(twitter_connections, ic)) {
1661                return;
1662        }
1663
1664        td = ic->proto_data;
1665        td->last_status_id = 0;
1666
1667        if (!(parsed = twitter_parse_response(ic, req))) {
1668                return;
1669        }
1670
1671        if ((id = json_object_get_integer(json_object(parsed), "id"))) {
1672                td->last_status_id = id;
1673        }
1674
1675        json_value_free(parsed);
1676
1677        if (req->flags & TWITTER_HTTP_USER_ACK) {
1678                twitter_log(ic, "Command processed successfully");
1679        }
1680}
1681
1682/**
1683 * Function to POST a new status to twitter.
1684 */
1685void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to)
1686{
1687        char *args[4] = {
1688                "status", msg,
1689                "in_reply_to_status_id",
1690                g_strdup_printf("%" G_GUINT64_FORMAT, in_reply_to)
1691        };
1692
1693        twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1,
1694                     args, in_reply_to ? 4 : 2);
1695        g_free(args[3]);
1696}
1697
1698
1699/**
1700 * Function to POST a new message to twitter.
1701 */
1702void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg)
1703{
1704        char *args[4];
1705
1706        args[0] = "screen_name";
1707        args[1] = who;
1708        args[2] = "text";
1709        args[3] = msg;
1710        // Use the same callback as for twitter_post_status, since it does basically the same.
1711        twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4);
1712}
1713
1714void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create)
1715{
1716        char *args[2];
1717
1718        args[0] = "screen_name";
1719        args[1] = who;
1720        twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL,
1721                     twitter_http_post, ic, 1, args, 2);
1722}
1723
1724/**
1725 * Mute or unmute a user
1726 */
1727void twitter_mute_create_destroy(struct im_connection *ic, char *who, int create)
1728{
1729        char *args[2];
1730
1731        args[0] = "screen_name";
1732        args[1] = who;
1733        twitter_http(ic, create ? TWITTER_MUTES_CREATE_URL : TWITTER_MUTES_DESTROY_URL,
1734                     twitter_http_post, ic, 1, args, 2);
1735}
1736
1737void twitter_status_destroy(struct im_connection *ic, guint64 id)
1738{
1739        char *url;
1740
1741        url = g_strdup_printf("%s%" G_GUINT64_FORMAT "%s",
1742                              TWITTER_STATUS_DESTROY_URL, id, ".json");
1743        twitter_http_f(ic, url, twitter_http_post, ic, 1, NULL, 0,
1744                       TWITTER_HTTP_USER_ACK);
1745        g_free(url);
1746}
1747
1748void twitter_status_retweet(struct im_connection *ic, guint64 id)
1749{
1750        char *url;
1751
1752        url = g_strdup_printf("%s%" G_GUINT64_FORMAT "%s",
1753                              TWITTER_STATUS_RETWEET_URL, id, ".json");
1754        twitter_http_f(ic, url, twitter_http_post, ic, 1, NULL, 0,
1755                       TWITTER_HTTP_USER_ACK);
1756        g_free(url);
1757}
1758
1759/**
1760 * Report a user for sending spam.
1761 */
1762void twitter_report_spam(struct im_connection *ic, char *screen_name)
1763{
1764        char *args[2] = {
1765                "screen_name",
1766                NULL,
1767        };
1768
1769        args[1] = screen_name;
1770        twitter_http_f(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post,
1771                       ic, 1, args, 2, TWITTER_HTTP_USER_ACK);
1772}
1773
1774/**
1775 * Favourite a tweet.
1776 */
1777void twitter_favourite_tweet(struct im_connection *ic, guint64 id)
1778{
1779        char *args[2] = {
1780                "id",
1781                NULL,
1782        };
1783
1784        args[1] = g_strdup_printf("%" G_GUINT64_FORMAT, id);
1785        twitter_http_f(ic, TWITTER_FAVORITE_CREATE_URL, twitter_http_post,
1786                       ic, 1, args, 2, TWITTER_HTTP_USER_ACK);
1787        g_free(args[1]);
1788}
1789
1790static void twitter_http_status_show_url(struct http_request *req)
1791{
1792        struct im_connection *ic = req->data;
1793        JSON_Value *parsed;
1794        uint64_t id;
1795        const char *name;
1796
1797        // Check if the connection is still active.
1798        if (!g_slist_find(twitter_connections, ic)) {
1799                return;
1800        }
1801
1802        if (!(parsed = twitter_parse_response(ic, req))) {
1803                return;
1804        }
1805
1806        name = json_object_dotget_string(json_object(parsed), "user.screen_name");
1807        id = json_object_get_integer(json_object(parsed), "id");
1808
1809        if (name && id) {
1810                twitter_log(ic, "https://twitter.com/%s/status/%" G_GUINT64_FORMAT, name, id);
1811        } else {
1812                twitter_log(ic, "Error: could not fetch tweet url.");
1813        }
1814
1815        json_value_free(parsed);
1816}
1817
1818void twitter_status_show_url(struct im_connection *ic, guint64 id)
1819{
1820        char *url = g_strdup_printf("%s%" G_GUINT64_FORMAT "%s", TWITTER_STATUS_SHOW_URL, id, ".json");
1821        twitter_http(ic, url, twitter_http_status_show_url, ic, 0, NULL, 0);
1822        g_free(url);
1823}
Note: See TracBrowser for help on using the repository browser.