source: protocols/twitter/twitter_lib.c @ c9b5817

Last change on this file since c9b5817 was c9b5817, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-25T00:55:47Z

Minor rework: Always fill td->log now and use it not just for show_ids, but
also for stream deduplication. Also, drop tweets from unknown people unless
fetch_mentions is set. The stream will feed us that spam either way but not
everyone wants to see it.

Last, fixing a bug where in streaming mode, per-user last tweet times were
no longer getting tracked.

  • Property mode set to 100644
File size: 34.6 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-2012 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 "json_util.h"
39#include <ctype.h>
40#include <errno.h>
41
42/* GLib < 2.12.0 doesn't have g_ascii_strtoll(), work around using system strtoll(). */
43/* GLib < 2.12.4 can be buggy: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=488013 */
44#if !GLIB_CHECK_VERSION(2,12,5)
45#include <stdlib.h>
46#include <limits.h>
47#define g_ascii_strtoll strtoll
48#endif
49
50#define TXL_STATUS 1
51#define TXL_USER 2
52#define TXL_ID 3
53
54struct twitter_xml_list {
55        int type;
56        gint64 next_cursor;
57        GSList *list;
58};
59
60struct twitter_xml_user {
61        char *name;
62        char *screen_name;
63};
64
65struct twitter_xml_status {
66        time_t created_at;
67        char *text;
68        struct twitter_xml_user *user;
69        guint64 id, reply_to;
70};
71
72static void twitter_groupchat_init(struct im_connection *ic);
73
74/**
75 * Frees a twitter_xml_user struct.
76 */
77static void txu_free(struct twitter_xml_user *txu)
78{
79        if (txu == NULL)
80                return;
81
82        g_free(txu->name);
83        g_free(txu->screen_name);
84        g_free(txu);
85}
86
87/**
88 * Frees a twitter_xml_status struct.
89 */
90static void txs_free(struct twitter_xml_status *txs)
91{
92        if (txs == NULL)
93                return;
94
95        g_free(txs->text);
96        txu_free(txs->user);
97        g_free(txs);
98}
99
100/**
101 * Free a twitter_xml_list struct.
102 * type is the type of list the struct holds.
103 */
104static void txl_free(struct twitter_xml_list *txl)
105{
106        GSList *l;
107        if (txl == NULL)
108                return;
109
110        for (l = txl->list; l; l = g_slist_next(l)) {
111                if (txl->type == TXL_STATUS) {
112                        txs_free((struct twitter_xml_status *) l->data);
113                } else if (txl->type == TXL_ID) {
114                        g_free(l->data);
115                } else if (txl->type == TXL_USER) {
116                        txu_free(l->data);
117                }
118        }
119
120        g_slist_free(txl->list);
121        g_free(txl);
122}
123
124/**
125 * Compare status elements
126 */
127static gint twitter_compare_elements(gconstpointer a, gconstpointer b)
128{
129        struct twitter_xml_status *a_status = (struct twitter_xml_status *) a;
130        struct twitter_xml_status *b_status = (struct twitter_xml_status *) b;
131
132        if (a_status->created_at < b_status->created_at) {
133                return -1;
134        } else if (a_status->created_at > b_status->created_at) {
135                return 1;
136        } else {
137                return 0;
138        }
139}
140
141/**
142 * Add a buddy if it is not already added, set the status to logged in.
143 */
144static void twitter_add_buddy(struct im_connection *ic, char *name, const char *fullname)
145{
146        struct twitter_data *td = ic->proto_data;
147
148        // Check if the buddy is already in the buddy list.
149        if (!bee_user_by_handle(ic->bee, ic, name)) {
150                char *mode = set_getstr(&ic->acc->set, "mode");
151
152                // The buddy is not in the list, add the buddy and set the status to logged in.
153                imcb_add_buddy(ic, name, NULL);
154                imcb_rename_buddy(ic, name, fullname);
155                if (g_strcasecmp(mode, "chat") == 0) {
156                        /* Necessary so that nicks always get translated to the
157                           exact Twitter username. */
158                        imcb_buddy_nick_hint(ic, name, name);
159                        imcb_chat_add_buddy(td->timeline_gc, name);
160                } else if (g_strcasecmp(mode, "many") == 0)
161                        imcb_buddy_status(ic, name, OPT_LOGGED_IN, NULL, NULL);
162        }
163}
164
165/* Warning: May return a malloc()ed value, which will be free()d on the next
166   call. Only for short-term use. NOT THREADSAFE!  */
167char *twitter_parse_error(struct http_request *req)
168{
169        static char *ret = NULL;
170        json_value *root, *err;
171
172        g_free(ret);
173        ret = NULL;
174
175        if (req->body_size > 0) {
176                root = json_parse(req->reply_body);
177                err = json_o_get(root, "errors");
178                if (err && err->type == json_array && (err = err->u.array.values[0]) &&
179                    err->type == json_object) {
180                        const char *msg = json_o_str(err, "message");
181                        if (msg)
182                                ret = g_strdup_printf("%s (%s)", req->status_string, msg);
183                }
184                json_value_free(root);
185        }
186
187        return ret ? ret : req->status_string;
188}
189
190/* WATCH OUT: This function might or might not destroy your connection.
191   Sub-optimal indeed, but just be careful when this returns NULL! */
192static json_value *twitter_parse_response(struct im_connection *ic, struct http_request *req)
193{
194        gboolean logging_in = !(ic->flags & OPT_LOGGED_IN);
195        gboolean periodic;
196        struct twitter_data *td = ic->proto_data;
197        json_value *ret;
198        char path[64] = "", *s;
199       
200        if ((s = strchr(req->request, ' '))) {
201                path[sizeof(path)-1] = '\0';
202                strncpy(path, s + 1, sizeof(path) - 1);
203                if ((s = strchr(path, '?')) || (s = strchr(path, ' ')))
204                        *s = '\0';
205        }
206       
207        /* Kinda nasty. :-( Trying to suppress error messages, but only
208           for periodic (i.e. mentions/timeline) queries. */
209        periodic = strstr(path, "timeline") || strstr(path, "mentions");
210       
211        if (req->status_code == 401 && logging_in) {
212                /* IIRC Twitter once had an outage where they were randomly
213                   throwing 401s so I'll keep treating this one as fatal
214                   only during login. */
215                imcb_error(ic, "Authentication failure (%s)",
216                               twitter_parse_error(req));
217                imc_logout(ic, FALSE);
218                return NULL;
219        } else if (req->status_code != 200) {
220                // It didn't go well, output the error and return.
221                if (!periodic || logging_in || ++td->http_fails >= 5)
222                        imcb_error(ic, "Could not retrieve %s: %s",
223                                   path, twitter_parse_error(req));
224               
225                if (logging_in)
226                        imc_logout(ic, TRUE);
227                return NULL;
228        } else {
229                td->http_fails = 0;
230        }
231
232        if ((ret = json_parse(req->reply_body)) == NULL) {
233                imcb_error(ic, "Could not retrieve %s: %s",
234                           path, "XML parse error");
235        }
236        return ret;
237}
238
239static void twitter_http_get_friends_ids(struct http_request *req);
240
241/**
242 * Get the friends ids.
243 */
244void twitter_get_friends_ids(struct im_connection *ic, gint64 next_cursor)
245{
246        // Primitive, but hey! It works...     
247        char *args[2];
248        args[0] = "cursor";
249        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
250        twitter_http(ic, TWITTER_FRIENDS_IDS_URL, twitter_http_get_friends_ids, ic, 0, args, 2);
251
252        g_free(args[1]);
253}
254
255/**
256 * Fill a list of ids.
257 */
258static gboolean twitter_xt_get_friends_id_list(json_value *node, struct twitter_xml_list *txl)
259{
260        json_value *c;
261        int i;
262
263        // Set the list type.
264        txl->type = TXL_ID;
265
266        c = json_o_get(node, "ids");
267        if (!c || c->type != json_array)
268                return FALSE;
269
270        for (i = 0; i < c->u.array.length; i ++) {
271                if (c->u.array.values[i]->type != json_integer)
272                        continue;
273               
274                txl->list = g_slist_prepend(txl->list,
275                        g_strdup_printf("%lld", c->u.array.values[i]->u.integer));
276               
277        }
278       
279        c = json_o_get(node, "next_cursor");
280        if (c && c->type == json_integer)
281                txl->next_cursor = c->u.integer;
282        else
283                txl->next_cursor = -1;
284       
285        return TRUE;
286}
287
288static void twitter_get_users_lookup(struct im_connection *ic);
289
290/**
291 * Callback for getting the friends ids.
292 */
293static void twitter_http_get_friends_ids(struct http_request *req)
294{
295        struct im_connection *ic;
296        json_value *parsed;
297        struct twitter_xml_list *txl;
298        struct twitter_data *td;
299
300        ic = req->data;
301
302        // Check if the connection is still active.
303        if (!g_slist_find(twitter_connections, ic))
304                return;
305
306        td = ic->proto_data;
307
308        /* Create the room now that we "logged in". */
309        if (!td->timeline_gc && g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "chat") == 0)
310                twitter_groupchat_init(ic);
311
312        txl = g_new0(struct twitter_xml_list, 1);
313        txl->list = td->follow_ids;
314
315        // Parse the data.
316        if (!(parsed = twitter_parse_response(ic, req)))
317                return;
318       
319        twitter_xt_get_friends_id_list(parsed, txl);
320        json_value_free(parsed);
321
322        td->follow_ids = txl->list;
323        if (txl->next_cursor)
324                /* These were just numbers. Up to 4000 in a response AFAIK so if we get here
325                   we may be using a spammer account. \o/ */
326                twitter_get_friends_ids(ic, txl->next_cursor);
327        else
328                /* Now to convert all those numbers into names.. */
329                twitter_get_users_lookup(ic);
330
331        txl->list = NULL;
332        txl_free(txl);
333}
334
335static gboolean twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl);
336static void twitter_http_get_users_lookup(struct http_request *req);
337
338static void twitter_get_users_lookup(struct im_connection *ic)
339{
340        struct twitter_data *td = ic->proto_data;
341        char *args[2] = {
342                "user_id",
343                NULL,
344        };
345        GString *ids = g_string_new("");
346        int i;
347       
348        /* We can request up to 100 users at a time. */
349        for (i = 0; i < 100 && td->follow_ids; i ++) {
350                g_string_append_printf(ids, ",%s", (char*) td->follow_ids->data);
351                g_free(td->follow_ids->data);
352                td->follow_ids = g_slist_remove(td->follow_ids, td->follow_ids->data);
353        }
354        if (ids->len > 0) {
355                args[1] = ids->str + 1;
356                /* POST, because I think ids can be up to 1KB long. */
357                twitter_http(ic, TWITTER_USERS_LOOKUP_URL, twitter_http_get_users_lookup, ic, 1, args, 2);
358        } else {
359                /* We have all users. Continue with login. (Get statuses.) */
360                td->flags |= TWITTER_HAVE_FRIENDS;
361                twitter_login_finish(ic);
362        }
363        g_string_free(ids, TRUE);
364}
365
366/**
367 * Callback for getting (twitter)friends...
368 *
369 * Be afraid, be very afraid! This function will potentially add hundreds of "friends". "Who has
370 * hundreds of friends?" you wonder? You probably not, since you are reading the source of
371 * BitlBee... Get a life and meet new people!
372 */
373static void twitter_http_get_users_lookup(struct http_request *req)
374{
375        struct im_connection *ic = req->data;
376        json_value *parsed;
377        struct twitter_xml_list *txl;
378        GSList *l = NULL;
379        struct twitter_xml_user *user;
380
381        // Check if the connection is still active.
382        if (!g_slist_find(twitter_connections, ic))
383                return;
384
385        txl = g_new0(struct twitter_xml_list, 1);
386        txl->list = NULL;
387
388        // Get the user list from the parsed xml feed.
389        if (!(parsed = twitter_parse_response(ic, req)))
390                return;
391        twitter_xt_get_users(parsed, txl);
392        json_value_free(parsed);
393
394        // Add the users as buddies.
395        for (l = txl->list; l; l = g_slist_next(l)) {
396                user = l->data;
397                twitter_add_buddy(ic, user->screen_name, user->name);
398        }
399
400        // Free the structure.
401        txl_free(txl);
402
403        twitter_get_users_lookup(ic);
404}
405
406struct twitter_xml_user *twitter_xt_get_user(const json_value *node)
407{
408        struct twitter_xml_user *txu;
409       
410        txu = g_new0(struct twitter_xml_user, 1);
411        txu->name = g_strdup(json_o_str(node, "name"));
412        txu->screen_name = g_strdup(json_o_str(node, "screen_name"));
413       
414        return txu;
415}
416
417/**
418 * Function to fill a twitter_xml_list struct.
419 * It sets:
420 *  - all <user>s from the <users> element.
421 */
422static gboolean twitter_xt_get_users(json_value *node, struct twitter_xml_list *txl)
423{
424        struct twitter_xml_user *txu;
425        int i;
426
427        // Set the type of the list.
428        txl->type = TXL_USER;
429
430        if (!node || node->type != json_array)
431                return FALSE;
432
433        // The root <users> node should hold the list of users <user>
434        // Walk over the nodes children.
435        for (i = 0; i < node->u.array.length; i ++) {
436                txu = twitter_xt_get_user(node->u.array.values[i]);
437                if (txu)
438                        txl->list = g_slist_prepend(txl->list, txu);
439        }
440
441        return TRUE;
442}
443
444#ifdef __GLIBC__
445#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S %z %Y"
446#else
447#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S +0000 %Y"
448#endif
449
450static char* expand_entities(char* text, const json_value *entities);
451
452/**
453 * Function to fill a twitter_xml_status struct.
454 * It sets:
455 *  - the status text and
456 *  - the created_at timestamp and
457 *  - the status id and
458 *  - the user in a twitter_xml_user struct.
459 */
460static struct twitter_xml_status *twitter_xt_get_status(const json_value *node)
461{
462        struct twitter_xml_status *txs;
463        const json_value *rt = NULL, *entities = NULL;
464       
465        if (node->type != json_object)
466                return FALSE;
467        txs = g_new0(struct twitter_xml_status, 1);
468
469        JSON_O_FOREACH (node, k, v) {
470                if (strcmp("text", k) == 0 && v->type == json_string) {
471                        txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1);
472                } else if (strcmp("retweeted_status", k) == 0 && v->type == json_object) {
473                        rt = v;
474                } else if (strcmp("created_at", k) == 0 && v->type == json_string) {
475                        struct tm parsed;
476
477                        /* Very sensitive to changes to the formatting of
478                           this field. :-( Also assumes the timezone used
479                           is UTC since C time handling functions suck. */
480                        if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL)
481                                txs->created_at = mktime_utc(&parsed);
482                } else if (strcmp("user", k) == 0 && v->type == json_object) {
483                        txs->user = twitter_xt_get_user(v);
484                } else if (strcmp("id", k) == 0 && v->type == json_integer) {
485                        txs->id = v->u.integer;
486                } else if (strcmp("in_reply_to_status_id", k) == 0 && v->type == json_integer) {
487                        txs->reply_to = v->u.integer;
488                } else if (strcmp("entities", k) == 0 && v->type == json_object) {
489                        entities = v;
490                }
491        }
492
493        /* If it's a (truncated) retweet, get the original. Even if the API claims it
494           wasn't truncated because it may be lying. */
495        if (rt) {
496                struct twitter_xml_status *rtxs = twitter_xt_get_status(rt);
497                if (rtxs) {
498                        g_free(txs->text);
499                        txs->text = g_strdup_printf("RT @%s: %s", rtxs->user->screen_name, rtxs->text);
500                        txs->id = rtxs->id;
501                        txs_free(rtxs);
502                }
503        } else if (entities) {
504                txs->text = expand_entities(txs->text, entities);
505        }
506
507        if (txs->text && txs->user && txs->id)
508                return txs;
509       
510        txs_free(txs);
511        return NULL;
512}
513
514/**
515 * Function to fill a twitter_xml_status struct (DM variant).
516 */
517static gboolean twitter_xt_get_dm(const json_value *node, struct twitter_xml_status *txs)
518{
519        const json_value *entities = NULL;
520       
521        if (node->type != json_object)
522                return FALSE;
523
524        JSON_O_FOREACH (node, k, v) {
525                if (strcmp("text", k) == 0 && v->type == json_string) {
526                        txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1);
527                } else if (strcmp("created_at", k) == 0 && v->type == json_string) {
528                        struct tm parsed;
529
530                        /* Very sensitive to changes to the formatting of
531                           this field. :-( Also assumes the timezone used
532                           is UTC since C time handling functions suck. */
533                        if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL)
534                                txs->created_at = mktime_utc(&parsed);
535                } else if (strcmp("sender", k) == 0 && v->type == json_object) {
536                        txs->user = twitter_xt_get_user(v);
537                } else if (strcmp("id", k) == 0 && v->type == json_integer) {
538                        txs->id = v->u.integer;
539                }
540        }
541
542        if (entities) {
543                txs->text = expand_entities(txs->text, entities);
544        }
545
546        return txs->text && txs->user && txs->id;
547}
548
549static char* expand_entities(char* text, const json_value *entities) {
550        JSON_O_FOREACH (entities, k, v) {
551                int i;
552               
553                if (v->type != json_array)
554                        continue;
555                if (strcmp(k, "urls") != 0 && strcmp(k, "media") != 0)
556                        continue;
557               
558                for (i = 0; i < v->u.array.length; i ++) {
559                        if (v->u.array.values[i]->type != json_object)
560                                continue;
561                       
562                        const char *kort = json_o_str(v->u.array.values[i], "url");
563                        const char *disp = json_o_str(v->u.array.values[i], "display_url");
564                        char *pos, *new;
565                       
566                        if (!kort || !disp || !(pos = strstr(text, kort)))
567                                continue;
568                       
569                        *pos = '\0';
570                        new = g_strdup_printf("%s%s &lt;%s&gt;%s", text, kort,
571                                              disp, pos + strlen(kort));
572                       
573                        g_free(text);
574                        text = new;
575                }
576        }
577       
578        return text;
579}
580
581/**
582 * Function to fill a twitter_xml_list struct.
583 * It sets:
584 *  - all <status>es within the <status> element and
585 *  - the next_cursor.
586 */
587static gboolean twitter_xt_get_status_list(struct im_connection *ic, const json_value *node,
588                                           struct twitter_xml_list *txl)
589{
590        struct twitter_xml_status *txs;
591        int i;
592
593        // Set the type of the list.
594        txl->type = TXL_STATUS;
595       
596        if (node->type != json_array)
597                return FALSE;
598
599        // The root <statuses> node should hold the list of statuses <status>
600        // Walk over the nodes children.
601        for (i = 0; i < node->u.array.length; i ++) {
602                txs = twitter_xt_get_status(node->u.array.values[i]);
603                if (!txs)
604                        continue;
605               
606                txl->list = g_slist_prepend(txl->list, txs);
607        }
608
609        return TRUE;
610}
611
612/* Will log messages either way. Need to keep track of IDs for stream deduping.
613   Plus, show_ids is on by default and I don't see why anyone would disable it. */
614static char *twitter_msg_add_id(struct im_connection *ic,
615                                struct twitter_xml_status *txs, const char *prefix)
616{
617        struct twitter_data *td = ic->proto_data;
618        int reply_to = -1;
619        bee_user_t *bu;
620
621        if (txs->reply_to) {
622                int i;
623                for (i = 0; i < TWITTER_LOG_LENGTH; i++)
624                        if (td->log[i].id == txs->reply_to) {
625                                reply_to = i;
626                                break;
627                        }
628        }
629
630        if (txs->user && txs->user->screen_name &&
631            (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
632                struct twitter_user_data *tud = bu->data;
633
634                if (txs->id > tud->last_id) {
635                        tud->last_id = txs->id;
636                        tud->last_time = txs->created_at;
637                }
638        }
639       
640        td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH;
641        td->log[td->log_id].id = txs->id;
642        td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name);
643       
644        if (set_getbool(&ic->acc->set, "show_ids")) {
645                if (reply_to != -1)
646                        return g_strdup_printf("\002[\002%02d->%02d\002]\002 %s%s",
647                                               td->log_id, reply_to, prefix, txs->text);
648                else
649                        return g_strdup_printf("\002[\002%02d\002]\002 %s%s",
650                                               td->log_id, prefix, txs->text);
651        } else {
652                if (*prefix)
653                        return g_strconcat(prefix, txs->text, NULL);
654                else
655                        return NULL;
656        }
657}
658
659static void twitter_groupchat_init(struct im_connection *ic)
660{
661        char *name_hint;
662        struct groupchat *gc;
663        struct twitter_data *td = ic->proto_data;
664        GSList *l;
665
666        td->timeline_gc = gc = imcb_chat_new(ic, "twitter/timeline");
667
668        name_hint = g_strdup_printf("%s_%s", td->prefix, ic->acc->user);
669        imcb_chat_name_hint(gc, name_hint);
670        g_free(name_hint);
671
672        for (l = ic->bee->users; l; l = l->next) {
673                bee_user_t *bu = l->data;
674                if (bu->ic == ic)
675                        imcb_chat_add_buddy(td->timeline_gc, bu->handle);
676        }
677}
678
679/**
680 * Function that is called to see the statuses in a groupchat window.
681 */
682static void twitter_groupchat(struct im_connection *ic, GSList * list)
683{
684        struct twitter_data *td = ic->proto_data;
685        GSList *l = NULL;
686        struct twitter_xml_status *status;
687        struct groupchat *gc;
688        guint64 last_id = 0;
689
690        // Create a new groupchat if it does not exsist.
691        if (!td->timeline_gc)
692                twitter_groupchat_init(ic);
693
694        gc = td->timeline_gc;
695        if (!gc->joined)
696                imcb_chat_add_buddy(gc, ic->acc->user);
697
698        for (l = list; l; l = g_slist_next(l)) {
699                char *msg;
700
701                status = l->data;
702                if (status->user == NULL || status->text == NULL || last_id == status->id)
703                        continue;
704
705                last_id = status->id;
706
707                strip_html(status->text);
708
709                if (set_getbool(&ic->acc->set, "strip_newlines"))
710                        strip_newlines(status->text);
711
712                msg = twitter_msg_add_id(ic, status, "");
713
714                // Say it!
715                if (g_strcasecmp(td->user, status->user->screen_name) == 0) {
716                        imcb_chat_log(gc, "You: %s", msg ? msg : status->text);
717                } else {
718                        twitter_add_buddy(ic, status->user->screen_name, status->user->name);
719
720                        imcb_chat_msg(gc, status->user->screen_name,
721                                      msg ? msg : status->text, 0, status->created_at);
722                }
723
724                g_free(msg);
725
726                // Update the timeline_id to hold the highest id, so that by the next request
727                // we won't pick up the updates already in the list.
728                td->timeline_id = MAX(td->timeline_id, status->id);
729        }
730}
731
732/**
733 * Function that is called to see statuses as private messages.
734 */
735static void twitter_private_message_chat(struct im_connection *ic, GSList * list)
736{
737        struct twitter_data *td = ic->proto_data;
738        GSList *l = NULL;
739        struct twitter_xml_status *status;
740        char from[MAX_STRING];
741        gboolean mode_one;
742        guint64 last_id = 0;
743
744        mode_one = g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "one") == 0;
745
746        if (mode_one) {
747                g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user);
748                from[MAX_STRING - 1] = '\0';
749        }
750
751        for (l = list; l; l = g_slist_next(l)) {
752                char *prefix = NULL, *text = NULL;
753
754                status = l->data;
755                if (status->user == NULL || status->text == NULL || last_id == status->id)
756                        continue;
757
758                last_id = status->id;
759
760                strip_html(status->text);
761                if (mode_one)
762                        prefix = g_strdup_printf("\002<\002%s\002>\002 ",
763                                                 status->user->screen_name);
764                else
765                        twitter_add_buddy(ic, status->user->screen_name, status->user->name);
766
767                text = twitter_msg_add_id(ic, status, prefix ? prefix : "");
768
769                imcb_buddy_msg(ic,
770                               mode_one ? from : status->user->screen_name,
771                               text ? text : status->text, 0, status->created_at);
772
773                // Update the timeline_id to hold the highest id, so that by the next request
774                // we won't pick up the updates already in the list.
775                td->timeline_id = MAX(td->timeline_id, status->id);
776
777                g_free(text);
778                g_free(prefix);
779        }
780}
781
782static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o);
783
784static void twitter_http_stream(struct http_request *req)
785{
786        struct im_connection *ic = req->data;
787        struct twitter_data *td;
788        json_value *parsed;
789        int len = 0;
790        char c, *nl;
791       
792        if (!g_slist_find(twitter_connections, ic))
793                return;
794       
795        ic->flags |= OPT_PONGED;
796        td = ic->proto_data;
797       
798        if ((req->flags & HTTPC_EOF) || !req->reply_body) {
799                td->stream = NULL;
800                imcb_error(ic, "Stream closed (%s)", req->status_string);
801                imc_logout(ic, TRUE);
802                return;
803        }
804       
805        printf( "%d bytes in stream\n", req->body_size );
806       
807        /* MUST search for CRLF, not just LF:
808           https://dev.twitter.com/docs/streaming-apis/processing#Parsing_responses */
809        nl = strstr(req->reply_body, "\r\n");
810       
811        if (!nl) {
812                printf("Incomplete data\n");
813                return;
814        }
815       
816        len = nl - req->reply_body;
817        if (len > 0) {
818                c = req->reply_body[len];
819                req->reply_body[len] = '\0';
820               
821                printf("JSON: %s\n", req->reply_body);
822                printf("parsed: %p\n", (parsed = json_parse(req->reply_body)));
823                if (parsed) {
824                        twitter_stream_handle_object(ic, parsed);
825                }
826                json_value_free(parsed);
827                req->reply_body[len] = c;
828        }
829       
830        http_flush_bytes(req, len + 2);
831       
832        /* One notification might bring multiple events! */
833        if (req->body_size > 0)
834                twitter_http_stream(req);
835}
836
837static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o);
838static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs);
839
840static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o)
841{
842        struct twitter_data *td = ic->proto_data;
843        struct twitter_xml_status *txs;
844        json_value *c;
845       
846        if ((txs = twitter_xt_get_status(o))) {
847                return twitter_stream_handle_status(ic, txs);
848        } else if ((c = json_o_get(o, "direct_message")) &&
849                   twitter_xt_get_dm(c, txs)) {
850                GSList *output = g_slist_append(NULL, txs);
851                twitter_private_message_chat(ic, output);
852                txs_free(txs);
853                g_slist_free(output);
854                return TRUE;
855        } else if ((c = json_o_get(o, "event")) && c->type == json_string) {
856                twitter_stream_handle_event(ic, o);
857                return TRUE;
858        } else if ((c = json_o_get(o, "disconnect")) && c->type == json_object) {
859                /* HACK: Because we're inside an event handler, we can't just
860                   disconnect here. Instead, just change the HTTP status string
861                   into a Twitter status string. */
862                char *reason = json_o_strdup(c, "reason");
863                if (reason) {
864                        g_free(td->stream->status_string);
865                        td->stream->status_string = reason;
866                }
867                return TRUE;
868        }
869        return FALSE;
870}
871
872static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs)
873{
874        struct twitter_data *td = ic->proto_data;
875        int i;
876       
877        for (i = 0; i < TWITTER_LOG_LENGTH; i++) {
878                if (td->log[i].id == txs->id) {
879                        /* Got a duplicate (RT, surely). Drop it. */
880                        txs_free(txs);
881                        return TRUE;
882                }
883        }
884       
885        if (!(set_getbool(&ic->acc->set, "fetch_mentions") ||
886              bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
887                /* Tweet is from an unknown person and the user does not want
888                   to see @mentions, so drop it. twitter_stream_handle_event()
889                   picks up new follows so this simple filter should be safe. */
890                /* TODO: The streaming API seems to do poor @mention matching.
891                   I.e. I'm getting mentions for @WilmerSomething, not just for
892                   @Wilmer. But meh. You want spam, you get spam. */
893                return TRUE;
894        }
895       
896        GSList *output = g_slist_append(NULL, txs);
897        twitter_groupchat(ic, output);
898        txs_free(txs);
899        g_slist_free(output);
900        return TRUE;
901}
902
903static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o)
904{
905        struct twitter_data *td = ic->proto_data;
906        json_value *source = json_o_get(o, "source");
907        json_value *target = json_o_get(o, "target");
908        const char *type = json_o_str(o, "event");
909       
910        if (!type || !source || source->type != json_object
911                  || !target || target->type != json_object) {
912                return FALSE;
913        }
914       
915        if (strcmp(type, "follow") == 0) {
916                struct twitter_xml_user *us = twitter_xt_get_user(source);
917                struct twitter_xml_user *ut = twitter_xt_get_user(target);
918                if (strcmp(us->screen_name, td->user) == 0) {
919                        twitter_add_buddy(ic, ut->screen_name, ut->name);
920                }
921                txu_free(us);
922                txu_free(ut);
923        }
924       
925        return TRUE;
926}
927
928gboolean twitter_open_stream(struct im_connection *ic)
929{
930        struct twitter_data *td = ic->proto_data;
931        char *args[2] = {"with", "followings"};
932       
933        if ((td->stream = twitter_http(ic, TWITTER_USER_STREAM_URL,
934                                       twitter_http_stream, ic, 0, args, 2))) {
935                /* This flag must be enabled or we'll get no data until EOF
936                   (which err, kind of, defeats the purpose of a streaming API). */
937                td->stream->flags |= HTTPC_STREAMING;
938                return TRUE;
939        }
940       
941        return FALSE;
942}
943
944static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor);
945static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor);
946
947/**
948 * Get the timeline with optionally mentions
949 */
950void twitter_get_timeline(struct im_connection *ic, gint64 next_cursor)
951{
952        struct twitter_data *td = ic->proto_data;
953        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
954
955        if (td->flags & TWITTER_DOING_TIMELINE) {
956                if (++td->http_fails >= 5) {
957                        imcb_error(ic, "Fetch timeout (%d)", td->flags);
958                        imc_logout(ic, TRUE);
959                }
960        }
961
962        td->flags |= TWITTER_DOING_TIMELINE;
963
964        twitter_get_home_timeline(ic, next_cursor);
965
966        if (include_mentions) {
967                twitter_get_mentions(ic, next_cursor);
968        }
969}
970
971/**
972 * Call this one after receiving timeline/mentions. Show to user once we have
973 * both.
974 */
975void twitter_flush_timeline(struct im_connection *ic)
976{
977        struct twitter_data *td = ic->proto_data;
978        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
979        int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions");
980        struct twitter_xml_list *home_timeline = td->home_timeline_obj;
981        struct twitter_xml_list *mentions = td->mentions_obj;
982        GSList *output = NULL;
983        GSList *l;
984
985        if (!(td->flags & TWITTER_GOT_TIMELINE)) {
986                return;
987        }
988
989        if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) {
990                return;
991        }
992
993        if (home_timeline && home_timeline->list) {
994                for (l = home_timeline->list; l; l = g_slist_next(l)) {
995                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
996                }
997        }
998
999        if (include_mentions && mentions && mentions->list) {
1000                for (l = mentions->list; l; l = g_slist_next(l)) {
1001                        if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) {
1002                                continue;
1003                        }
1004
1005                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
1006                }
1007        }
1008       
1009        if (!(ic->flags & OPT_LOGGED_IN))
1010                imcb_connected(ic);
1011
1012        // See if the user wants to see the messages in a groupchat window or as private messages.
1013        if (g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "chat") == 0)
1014                twitter_groupchat(ic, output);
1015        else
1016                twitter_private_message_chat(ic, output);
1017
1018        g_slist_free(output);
1019
1020        txl_free(home_timeline);
1021        txl_free(mentions);
1022
1023        td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS);
1024        td->home_timeline_obj = td->mentions_obj = NULL;
1025}
1026
1027static void twitter_http_get_home_timeline(struct http_request *req);
1028static void twitter_http_get_mentions(struct http_request *req);
1029
1030/**
1031 * Get the timeline.
1032 */
1033static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor)
1034{
1035        struct twitter_data *td = ic->proto_data;
1036
1037        txl_free(td->home_timeline_obj);
1038        td->home_timeline_obj = NULL;
1039        td->flags &= ~TWITTER_GOT_TIMELINE;
1040
1041        char *args[6];
1042        args[0] = "cursor";
1043        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
1044        args[2] = "include_entities";
1045        args[3] = "true";
1046        if (td->timeline_id) {
1047                args[4] = "since_id";
1048                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
1049        }
1050
1051        if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args,
1052                     td->timeline_id ? 6 : 4) == NULL) {
1053                if (++td->http_fails >= 5)
1054                        imcb_error(ic, "Could not retrieve %s: %s",
1055                                   TWITTER_HOME_TIMELINE_URL, "connection failed");
1056                td->flags |= TWITTER_GOT_TIMELINE;
1057                twitter_flush_timeline(ic);
1058        }
1059
1060        g_free(args[1]);
1061        if (td->timeline_id) {
1062                g_free(args[5]);
1063        }
1064}
1065
1066/**
1067 * Get mentions.
1068 */
1069static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor)
1070{
1071        struct twitter_data *td = ic->proto_data;
1072
1073        txl_free(td->mentions_obj);
1074        td->mentions_obj = NULL;
1075        td->flags &= ~TWITTER_GOT_MENTIONS;
1076
1077        char *args[6];
1078        args[0] = "cursor";
1079        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
1080        args[2] = "include_entities";
1081        args[3] = "true";
1082        if (td->timeline_id) {
1083                args[4] = "since_id";
1084                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
1085        } else {
1086                args[4] = "count";
1087                args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions"));
1088        }
1089
1090        if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions,
1091                         ic, 0, args, 6) == NULL) {
1092                if (++td->http_fails >= 5)
1093                        imcb_error(ic, "Could not retrieve %s: %s",
1094                                   TWITTER_MENTIONS_URL, "connection failed");
1095                td->flags |= TWITTER_GOT_MENTIONS;
1096                twitter_flush_timeline(ic);
1097        }
1098
1099        g_free(args[1]);
1100        g_free(args[5]);
1101}
1102
1103/**
1104 * Callback for getting the home timeline.
1105 */
1106static void twitter_http_get_home_timeline(struct http_request *req)
1107{
1108        struct im_connection *ic = req->data;
1109        struct twitter_data *td;
1110        json_value *parsed;
1111        struct twitter_xml_list *txl;
1112
1113        // Check if the connection is still active.
1114        if (!g_slist_find(twitter_connections, ic))
1115                return;
1116
1117        td = ic->proto_data;
1118
1119        txl = g_new0(struct twitter_xml_list, 1);
1120        txl->list = NULL;
1121
1122        // The root <statuses> node should hold the list of statuses <status>
1123        if (!(parsed = twitter_parse_response(ic, req)))
1124                goto end;
1125        twitter_xt_get_status_list(ic, parsed, txl);
1126        json_value_free(parsed);
1127
1128        td->home_timeline_obj = txl;
1129
1130      end:
1131        if (!g_slist_find(twitter_connections, ic))
1132                return;
1133
1134        td->flags |= TWITTER_GOT_TIMELINE;
1135
1136        twitter_flush_timeline(ic);
1137}
1138
1139/**
1140 * Callback for getting mentions.
1141 */
1142static void twitter_http_get_mentions(struct http_request *req)
1143{
1144        struct im_connection *ic = req->data;
1145        struct twitter_data *td;
1146        json_value *parsed;
1147        struct twitter_xml_list *txl;
1148
1149        // Check if the connection is still active.
1150        if (!g_slist_find(twitter_connections, ic))
1151                return;
1152
1153        td = ic->proto_data;
1154
1155        txl = g_new0(struct twitter_xml_list, 1);
1156        txl->list = NULL;
1157
1158        // The root <statuses> node should hold the list of statuses <status>
1159        if (!(parsed = twitter_parse_response(ic, req)))
1160                goto end;
1161        twitter_xt_get_status_list(ic, parsed, txl);
1162        json_value_free(parsed);
1163
1164        td->mentions_obj = txl;
1165
1166      end:
1167        if (!g_slist_find(twitter_connections, ic))
1168                return;
1169
1170        td->flags |= TWITTER_GOT_MENTIONS;
1171
1172        twitter_flush_timeline(ic);
1173}
1174
1175/**
1176 * Callback to use after sending a POST request to twitter.
1177 * (Generic, used for a few kinds of queries.)
1178 */
1179static void twitter_http_post(struct http_request *req)
1180{
1181        struct im_connection *ic = req->data;
1182        struct twitter_data *td;
1183        json_value *parsed, *id;
1184
1185        // Check if the connection is still active.
1186        if (!g_slist_find(twitter_connections, ic))
1187                return;
1188
1189        td = ic->proto_data;
1190        td->last_status_id = 0;
1191
1192        if (!(parsed = twitter_parse_response(ic, req)))
1193                return;
1194       
1195        if ((id = json_o_get(parsed, "id")) && id->type == json_integer)
1196                td->last_status_id = id->u.integer;
1197       
1198        json_value_free(parsed);
1199}
1200
1201/**
1202 * Function to POST a new status to twitter.
1203 */
1204void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to)
1205{
1206        char *args[4] = {
1207                "status", msg,
1208                "in_reply_to_status_id",
1209                g_strdup_printf("%llu", (unsigned long long) in_reply_to)
1210        };
1211        twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1,
1212                     args, in_reply_to ? 4 : 2);
1213        g_free(args[3]);
1214}
1215
1216
1217/**
1218 * Function to POST a new message to twitter.
1219 */
1220void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg)
1221{
1222        char *args[4];
1223        args[0] = "screen_name";
1224        args[1] = who;
1225        args[2] = "text";
1226        args[3] = msg;
1227        // Use the same callback as for twitter_post_status, since it does basically the same.
1228        twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4);
1229}
1230
1231void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create)
1232{
1233        char *args[2];
1234        args[0] = "screen_name";
1235        args[1] = who;
1236        twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL,
1237                     twitter_http_post, ic, 1, args, 2);
1238}
1239
1240void twitter_status_destroy(struct im_connection *ic, guint64 id)
1241{
1242        char *url;
1243        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_DESTROY_URL,
1244                              (unsigned long long) id, ".json");
1245        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1246        g_free(url);
1247}
1248
1249void twitter_status_retweet(struct im_connection *ic, guint64 id)
1250{
1251        char *url;
1252        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_RETWEET_URL,
1253                              (unsigned long long) id, ".json");
1254        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1255        g_free(url);
1256}
1257
1258/**
1259 * Report a user for sending spam.
1260 */
1261void twitter_report_spam(struct im_connection *ic, char *screen_name)
1262{
1263        char *args[2] = {
1264                "screen_name",
1265                NULL,
1266        };
1267        args[1] = screen_name;
1268        twitter_http(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post,
1269                     ic, 1, args, 2);
1270}
1271
1272/**
1273 * Favourite a tweet.
1274 */
1275void twitter_favourite_tweet(struct im_connection *ic, guint64 id)
1276{
1277        char *url;
1278        url = g_strdup_printf("%s%llu%s", TWITTER_FAVORITE_CREATE_URL,
1279                              (unsigned long long) id, ".json");
1280        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1281        g_free(url);
1282}
Note: See TracBrowser for help on using the repository browser.