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

Last change on this file since 3ca001b was b235228, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-25T22:28:38Z

Have root confirm some commands that so far gave no feedback at all, since
"no news is good news" can be a little confusing.

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