source: protocols/twitter/twitter_lib.c @ 7f557d5

Last change on this file since 7f557d5 was 7f557d5, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-25T14:58:29Z

Fixing two oopses from my last commit.

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