source: protocols/twitter/twitter_lib.c @ 29f72b7

Last change on this file since 29f72b7 was 29f72b7, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-25T17:43:13Z

Finally cleaned up the show-tweet functions.

  • Property mode set to 100644
File size: 33.8 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                        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->id = rtxs->id;
495                        txs_free(rtxs);
496                }
497        } else if (entities) {
498                txs->text = expand_entities(txs->text, entities);
499        }
500
501        if (txs->text && txs->user && txs->id)
502                return txs;
503       
504        txs_free(txs);
505        return NULL;
506}
507
508/**
509 * Function to fill a twitter_xml_status struct (DM variant).
510 */
511static struct twitter_xml_status *twitter_xt_get_dm(const json_value *node)
512{
513        struct twitter_xml_status *txs;
514        const json_value *entities = NULL;
515       
516        if (node->type != json_object)
517                return FALSE;
518        txs = g_new0(struct twitter_xml_status, 1);
519
520        JSON_O_FOREACH (node, k, v) {
521                if (strcmp("text", k) == 0 && v->type == json_string) {
522                        txs->text = g_memdup(v->u.string.ptr, v->u.string.length + 1);
523                        strip_html(txs->text);
524                } else if (strcmp("created_at", k) == 0 && v->type == json_string) {
525                        struct tm parsed;
526
527                        /* Very sensitive to changes to the formatting of
528                           this field. :-( Also assumes the timezone used
529                           is UTC since C time handling functions suck. */
530                        if (strptime(v->u.string.ptr, TWITTER_TIME_FORMAT, &parsed) != NULL)
531                                txs->created_at = mktime_utc(&parsed);
532                } else if (strcmp("sender", k) == 0 && v->type == json_object) {
533                        txs->user = twitter_xt_get_user(v);
534                } else if (strcmp("id", k) == 0 && v->type == json_integer) {
535                        txs->id = v->u.integer;
536                }
537        }
538
539        if (entities) {
540                txs->text = expand_entities(txs->text, entities);
541        }
542
543        if (txs->text && txs->user && txs->id)
544                return txs;
545       
546        txs_free(txs);
547        return NULL;
548}
549
550static char* expand_entities(char* text, const json_value *entities) {
551        JSON_O_FOREACH (entities, k, v) {
552                int i;
553               
554                if (v->type != json_array)
555                        continue;
556                if (strcmp(k, "urls") != 0 && strcmp(k, "media") != 0)
557                        continue;
558               
559                for (i = 0; i < v->u.array.length; i ++) {
560                        if (v->u.array.values[i]->type != json_object)
561                                continue;
562                       
563                        const char *kort = json_o_str(v->u.array.values[i], "url");
564                        const char *disp = json_o_str(v->u.array.values[i], "display_url");
565                        char *pos, *new;
566                       
567                        if (!kort || !disp || !(pos = strstr(text, kort)))
568                                continue;
569                       
570                        *pos = '\0';
571                        new = g_strdup_printf("%s%s <%s>%s", text, kort,
572                                              disp, pos + strlen(kort));
573                       
574                        g_free(text);
575                        text = new;
576                }
577        }
578       
579        return text;
580}
581
582/**
583 * Function to fill a twitter_xml_list struct.
584 * It sets:
585 *  - all <status>es within the <status> element and
586 *  - the next_cursor.
587 */
588static gboolean twitter_xt_get_status_list(struct im_connection *ic, const json_value *node,
589                                           struct twitter_xml_list *txl)
590{
591        struct twitter_xml_status *txs;
592        int i;
593
594        // Set the type of the list.
595        txl->type = TXL_STATUS;
596       
597        if (node->type != json_array)
598                return FALSE;
599
600        // The root <statuses> node should hold the list of statuses <status>
601        // Walk over the nodes children.
602        for (i = 0; i < node->u.array.length; i ++) {
603                txs = twitter_xt_get_status(node->u.array.values[i]);
604                if (!txs)
605                        continue;
606               
607                txl->list = g_slist_prepend(txl->list, txs);
608        }
609
610        return TRUE;
611}
612
613/* Will log messages either way. Need to keep track of IDs for stream deduping.
614   Plus, show_ids is on by default and I don't see why anyone would disable it. */
615static char *twitter_msg_add_id(struct im_connection *ic,
616                                struct twitter_xml_status *txs, const char *prefix)
617{
618        struct twitter_data *td = ic->proto_data;
619        int reply_to = -1;
620        bee_user_t *bu;
621
622        if (txs->reply_to) {
623                int i;
624                for (i = 0; i < TWITTER_LOG_LENGTH; i++)
625                        if (td->log[i].id == txs->reply_to) {
626                                reply_to = i;
627                                break;
628                        }
629        }
630
631        if (txs->user && txs->user->screen_name &&
632            (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
633                struct twitter_user_data *tud = bu->data;
634
635                if (txs->id > tud->last_id) {
636                        tud->last_id = txs->id;
637                        tud->last_time = txs->created_at;
638                }
639        }
640       
641        td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH;
642        td->log[td->log_id].id = txs->id;
643        td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name);
644       
645        if (set_getbool(&ic->acc->set, "show_ids")) {
646                if (reply_to != -1)
647                        return g_strdup_printf("\002[\002%02d->%02d\002]\002 %s%s",
648                                               td->log_id, reply_to, prefix, txs->text);
649                else
650                        return g_strdup_printf("\002[\002%02d\002]\002 %s%s",
651                                               td->log_id, prefix, txs->text);
652        } else {
653                if (*prefix)
654                        return g_strconcat(prefix, txs->text, NULL);
655                else
656                        return NULL;
657        }
658}
659
660/**
661 * Function that is called to see the statuses in a groupchat window.
662 */
663static void twitter_status_show_chat(struct im_connection *ic, struct twitter_xml_status *status)
664{
665        struct twitter_data *td = ic->proto_data;
666        struct groupchat *gc;
667        gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0;
668        char *msg;
669
670        // Create a new groupchat if it does not exsist.
671        gc = twitter_groupchat_init(ic);
672
673        if (!me)
674                /* MUST be done before twitter_msg_add_id() to avoid #872. */
675                twitter_add_buddy(ic, status->user->screen_name, status->user->name);
676        msg = twitter_msg_add_id(ic, status, "");
677       
678        // Say it!
679        if (me) {
680                imcb_chat_log(gc, "You: %s", msg ? msg : status->text);
681        } else {
682                imcb_chat_msg(gc, status->user->screen_name,
683                              msg ? msg : status->text, 0, status->created_at);
684        }
685
686        g_free(msg);
687}
688
689/**
690 * Function that is called to see statuses as private messages.
691 */
692static void twitter_status_show_msg(struct im_connection *ic, struct twitter_xml_status *status)
693{
694        struct twitter_data *td = ic->proto_data;
695        char from[MAX_STRING] = "";
696        char *prefix = NULL, *text = NULL;
697        gboolean me = g_strcasecmp(td->user, status->user->screen_name) == 0;
698
699        if (td->flags & TWITTER_MODE_ONE) {
700                g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user);
701                from[MAX_STRING - 1] = '\0';
702        }
703
704        if (td->flags & TWITTER_MODE_ONE)
705                prefix = g_strdup_printf("\002<\002%s\002>\002 ",
706                                         status->user->screen_name);
707        else if (!me)
708                twitter_add_buddy(ic, status->user->screen_name, status->user->name);
709        else
710                prefix = g_strdup("You: ");
711
712        text = twitter_msg_add_id(ic, status, prefix ? prefix : "");
713
714        imcb_buddy_msg(ic,
715                       *from ? from : status->user->screen_name,
716                       text ? text : status->text, 0, status->created_at);
717
718        g_free(text);
719        g_free(prefix);
720}
721
722static void twitter_status_show(struct im_connection *ic, struct twitter_xml_status *status)
723{
724        struct twitter_data *td = ic->proto_data;
725       
726        if (status->user == NULL || status->text == NULL)
727                return;
728       
729        /* Grrrr. Would like to do this during parsing, but can't access
730           settings from there. */
731        if (set_getbool(&ic->acc->set, "strip_newlines"))
732                strip_newlines(status->text);
733       
734        if (td->flags & TWITTER_MODE_CHAT)
735                twitter_status_show_chat(ic, status);
736        else
737                twitter_status_show_msg(ic, status);
738
739        // Update the timeline_id to hold the highest id, so that by the next request
740        // we won't pick up the updates already in the list.
741        td->timeline_id = MAX(td->timeline_id, status->id);
742}
743
744static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o);
745
746static void twitter_http_stream(struct http_request *req)
747{
748        struct im_connection *ic = req->data;
749        struct twitter_data *td;
750        json_value *parsed;
751        int len = 0;
752        char c, *nl;
753       
754        if (!g_slist_find(twitter_connections, ic))
755                return;
756       
757        ic->flags |= OPT_PONGED;
758        td = ic->proto_data;
759       
760        if ((req->flags & HTTPC_EOF) || !req->reply_body) {
761                td->stream = NULL;
762                imcb_error(ic, "Stream closed (%s)", req->status_string);
763                imc_logout(ic, TRUE);
764                return;
765        }
766       
767        printf( "%d bytes in stream\n", req->body_size );
768       
769        /* MUST search for CRLF, not just LF:
770           https://dev.twitter.com/docs/streaming-apis/processing#Parsing_responses */
771        nl = strstr(req->reply_body, "\r\n");
772       
773        if (!nl) {
774                printf("Incomplete data\n");
775                return;
776        }
777       
778        len = nl - req->reply_body;
779        if (len > 0) {
780                c = req->reply_body[len];
781                req->reply_body[len] = '\0';
782               
783                printf("JSON: %s\n", req->reply_body);
784                printf("parsed: %p\n", (parsed = json_parse(req->reply_body)));
785                if (parsed) {
786                        twitter_stream_handle_object(ic, parsed);
787                }
788                json_value_free(parsed);
789                req->reply_body[len] = c;
790        }
791       
792        http_flush_bytes(req, len + 2);
793       
794        /* One notification might bring multiple events! */
795        if (req->body_size > 0)
796                twitter_http_stream(req);
797}
798
799static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o);
800static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs);
801
802static gboolean twitter_stream_handle_object(struct im_connection *ic, json_value *o)
803{
804        struct twitter_data *td = ic->proto_data;
805        struct twitter_xml_status *txs;
806        json_value *c;
807       
808        if ((txs = twitter_xt_get_status(o))) {
809                return twitter_stream_handle_status(ic, txs);
810        } else if ((c = json_o_get(o, "direct_message")) &&
811                   (txs = twitter_xt_get_dm(c))) {
812                if (strcmp(txs->user->screen_name, td->user) != 0)
813                        imcb_buddy_msg(ic, txs->user->screen_name,
814                                       txs->text, 0, txs->created_at);
815                txs_free(txs);
816                return TRUE;
817        } else if ((c = json_o_get(o, "event")) && c->type == json_string) {
818                twitter_stream_handle_event(ic, o);
819                return TRUE;
820        } else if ((c = json_o_get(o, "disconnect")) && c->type == json_object) {
821                /* HACK: Because we're inside an event handler, we can't just
822                   disconnect here. Instead, just change the HTTP status string
823                   into a Twitter status string. */
824                char *reason = json_o_strdup(c, "reason");
825                if (reason) {
826                        g_free(td->stream->status_string);
827                        td->stream->status_string = reason;
828                }
829                return TRUE;
830        }
831        return FALSE;
832}
833
834static gboolean twitter_stream_handle_status(struct im_connection *ic, struct twitter_xml_status *txs)
835{
836        struct twitter_data *td = ic->proto_data;
837        int i;
838       
839        for (i = 0; i < TWITTER_LOG_LENGTH; i++) {
840                if (td->log[i].id == txs->id) {
841                        /* Got a duplicate (RT, probably). Drop it. */
842                        txs_free(txs);
843                        return TRUE;
844                }
845        }
846       
847        if (!(set_getbool(&ic->acc->set, "fetch_mentions") ||
848              bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
849                /* Tweet is from an unknown person and the user does not want
850                   to see @mentions, so drop it. twitter_stream_handle_event()
851                   picks up new follows so this simple filter should be safe. */
852                /* TODO: The streaming API seems to do poor @mention matching.
853                   I.e. I'm getting mentions for @WilmerSomething, not just for
854                   @Wilmer. But meh. You want spam, you get spam. */
855                return TRUE;
856        }
857       
858        twitter_status_show(ic, txs);
859        txs_free(txs);
860       
861        return TRUE;
862}
863
864static gboolean twitter_stream_handle_event(struct im_connection *ic, json_value *o)
865{
866        struct twitter_data *td = ic->proto_data;
867        json_value *source = json_o_get(o, "source");
868        json_value *target = json_o_get(o, "target");
869        const char *type = json_o_str(o, "event");
870       
871        if (!type || !source || source->type != json_object
872                  || !target || target->type != json_object) {
873                return FALSE;
874        }
875       
876        if (strcmp(type, "follow") == 0) {
877                struct twitter_xml_user *us = twitter_xt_get_user(source);
878                struct twitter_xml_user *ut = twitter_xt_get_user(target);
879                if (strcmp(us->screen_name, td->user) == 0) {
880                        twitter_add_buddy(ic, ut->screen_name, ut->name);
881                }
882                txu_free(us);
883                txu_free(ut);
884        }
885       
886        return TRUE;
887}
888
889gboolean twitter_open_stream(struct im_connection *ic)
890{
891        struct twitter_data *td = ic->proto_data;
892        char *args[2] = {"with", "followings"};
893       
894        if ((td->stream = twitter_http(ic, TWITTER_USER_STREAM_URL,
895                                       twitter_http_stream, ic, 0, args, 2))) {
896                /* This flag must be enabled or we'll get no data until EOF
897                   (which err, kind of, defeats the purpose of a streaming API). */
898                td->stream->flags |= HTTPC_STREAMING;
899                return TRUE;
900        }
901       
902        return FALSE;
903}
904
905static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor);
906static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor);
907
908/**
909 * Get the timeline with optionally mentions
910 */
911void twitter_get_timeline(struct im_connection *ic, gint64 next_cursor)
912{
913        struct twitter_data *td = ic->proto_data;
914        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
915
916        if (td->flags & TWITTER_DOING_TIMELINE) {
917                if (++td->http_fails >= 5) {
918                        imcb_error(ic, "Fetch timeout (%d)", td->flags);
919                        imc_logout(ic, TRUE);
920                }
921        }
922
923        td->flags |= TWITTER_DOING_TIMELINE;
924
925        twitter_get_home_timeline(ic, next_cursor);
926
927        if (include_mentions) {
928                twitter_get_mentions(ic, next_cursor);
929        }
930}
931
932/**
933 * Call this one after receiving timeline/mentions. Show to user once we have
934 * both.
935 */
936void twitter_flush_timeline(struct im_connection *ic)
937{
938        struct twitter_data *td = ic->proto_data;
939        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
940        int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions");
941        struct twitter_xml_list *home_timeline = td->home_timeline_obj;
942        struct twitter_xml_list *mentions = td->mentions_obj;
943        guint64 last_id = 0;
944        GSList *output = NULL;
945        GSList *l;
946
947        imcb_connected(ic);
948       
949        if (!(td->flags & TWITTER_GOT_TIMELINE)) {
950                return;
951        }
952
953        if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) {
954                return;
955        }
956
957        if (home_timeline && home_timeline->list) {
958                for (l = home_timeline->list; l; l = g_slist_next(l)) {
959                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
960                }
961        }
962
963        if (include_mentions && mentions && mentions->list) {
964                for (l = mentions->list; l; l = g_slist_next(l)) {
965                        if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) {
966                                continue;
967                        }
968
969                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
970                }
971        }
972
973        // See if the user wants to see the messages in a groupchat window or as private messages.
974        while (output) {
975                struct twitter_xml_status *txs = output->data;
976                if (txs->id != last_id)
977                        twitter_status_show(ic, txs);
978                last_id = txs->id;
979                output = g_slist_remove(output, txs);
980        }
981
982        txl_free(home_timeline);
983        txl_free(mentions);
984
985        td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS);
986        td->home_timeline_obj = td->mentions_obj = NULL;
987}
988
989static void twitter_http_get_home_timeline(struct http_request *req);
990static void twitter_http_get_mentions(struct http_request *req);
991
992/**
993 * Get the timeline.
994 */
995static void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor)
996{
997        struct twitter_data *td = ic->proto_data;
998
999        txl_free(td->home_timeline_obj);
1000        td->home_timeline_obj = NULL;
1001        td->flags &= ~TWITTER_GOT_TIMELINE;
1002
1003        char *args[6];
1004        args[0] = "cursor";
1005        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
1006        args[2] = "include_entities";
1007        args[3] = "true";
1008        if (td->timeline_id) {
1009                args[4] = "since_id";
1010                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
1011        }
1012
1013        if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args,
1014                     td->timeline_id ? 6 : 4) == NULL) {
1015                if (++td->http_fails >= 5)
1016                        imcb_error(ic, "Could not retrieve %s: %s",
1017                                   TWITTER_HOME_TIMELINE_URL, "connection failed");
1018                td->flags |= TWITTER_GOT_TIMELINE;
1019                twitter_flush_timeline(ic);
1020        }
1021
1022        g_free(args[1]);
1023        if (td->timeline_id) {
1024                g_free(args[5]);
1025        }
1026}
1027
1028/**
1029 * Get mentions.
1030 */
1031static void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor)
1032{
1033        struct twitter_data *td = ic->proto_data;
1034
1035        txl_free(td->mentions_obj);
1036        td->mentions_obj = NULL;
1037        td->flags &= ~TWITTER_GOT_MENTIONS;
1038
1039        char *args[6];
1040        args[0] = "cursor";
1041        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
1042        args[2] = "include_entities";
1043        args[3] = "true";
1044        if (td->timeline_id) {
1045                args[4] = "since_id";
1046                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
1047        } else {
1048                args[4] = "count";
1049                args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions"));
1050        }
1051
1052        if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions,
1053                         ic, 0, args, 6) == NULL) {
1054                if (++td->http_fails >= 5)
1055                        imcb_error(ic, "Could not retrieve %s: %s",
1056                                   TWITTER_MENTIONS_URL, "connection failed");
1057                td->flags |= TWITTER_GOT_MENTIONS;
1058                twitter_flush_timeline(ic);
1059        }
1060
1061        g_free(args[1]);
1062        g_free(args[5]);
1063}
1064
1065/**
1066 * Callback for getting the home timeline.
1067 */
1068static void twitter_http_get_home_timeline(struct http_request *req)
1069{
1070        struct im_connection *ic = req->data;
1071        struct twitter_data *td;
1072        json_value *parsed;
1073        struct twitter_xml_list *txl;
1074
1075        // Check if the connection is still active.
1076        if (!g_slist_find(twitter_connections, ic))
1077                return;
1078
1079        td = ic->proto_data;
1080
1081        txl = g_new0(struct twitter_xml_list, 1);
1082        txl->list = NULL;
1083
1084        // The root <statuses> node should hold the list of statuses <status>
1085        if (!(parsed = twitter_parse_response(ic, req)))
1086                goto end;
1087        twitter_xt_get_status_list(ic, parsed, txl);
1088        json_value_free(parsed);
1089
1090        td->home_timeline_obj = txl;
1091
1092      end:
1093        if (!g_slist_find(twitter_connections, ic))
1094                return;
1095
1096        td->flags |= TWITTER_GOT_TIMELINE;
1097
1098        twitter_flush_timeline(ic);
1099}
1100
1101/**
1102 * Callback for getting mentions.
1103 */
1104static void twitter_http_get_mentions(struct http_request *req)
1105{
1106        struct im_connection *ic = req->data;
1107        struct twitter_data *td;
1108        json_value *parsed;
1109        struct twitter_xml_list *txl;
1110
1111        // Check if the connection is still active.
1112        if (!g_slist_find(twitter_connections, ic))
1113                return;
1114
1115        td = ic->proto_data;
1116
1117        txl = g_new0(struct twitter_xml_list, 1);
1118        txl->list = NULL;
1119
1120        // The root <statuses> node should hold the list of statuses <status>
1121        if (!(parsed = twitter_parse_response(ic, req)))
1122                goto end;
1123        twitter_xt_get_status_list(ic, parsed, txl);
1124        json_value_free(parsed);
1125
1126        td->mentions_obj = txl;
1127
1128      end:
1129        if (!g_slist_find(twitter_connections, ic))
1130                return;
1131
1132        td->flags |= TWITTER_GOT_MENTIONS;
1133
1134        twitter_flush_timeline(ic);
1135}
1136
1137/**
1138 * Callback to use after sending a POST request to twitter.
1139 * (Generic, used for a few kinds of queries.)
1140 */
1141static void twitter_http_post(struct http_request *req)
1142{
1143        struct im_connection *ic = req->data;
1144        struct twitter_data *td;
1145        json_value *parsed, *id;
1146
1147        // Check if the connection is still active.
1148        if (!g_slist_find(twitter_connections, ic))
1149                return;
1150
1151        td = ic->proto_data;
1152        td->last_status_id = 0;
1153
1154        if (!(parsed = twitter_parse_response(ic, req)))
1155                return;
1156       
1157        if ((id = json_o_get(parsed, "id")) && id->type == json_integer)
1158                td->last_status_id = id->u.integer;
1159       
1160        json_value_free(parsed);
1161}
1162
1163/**
1164 * Function to POST a new status to twitter.
1165 */
1166void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to)
1167{
1168        char *args[4] = {
1169                "status", msg,
1170                "in_reply_to_status_id",
1171                g_strdup_printf("%llu", (unsigned long long) in_reply_to)
1172        };
1173        twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1,
1174                     args, in_reply_to ? 4 : 2);
1175        g_free(args[3]);
1176}
1177
1178
1179/**
1180 * Function to POST a new message to twitter.
1181 */
1182void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg)
1183{
1184        char *args[4];
1185        args[0] = "screen_name";
1186        args[1] = who;
1187        args[2] = "text";
1188        args[3] = msg;
1189        // Use the same callback as for twitter_post_status, since it does basically the same.
1190        twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4);
1191}
1192
1193void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create)
1194{
1195        char *args[2];
1196        args[0] = "screen_name";
1197        args[1] = who;
1198        twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL,
1199                     twitter_http_post, ic, 1, args, 2);
1200}
1201
1202void twitter_status_destroy(struct im_connection *ic, guint64 id)
1203{
1204        char *url;
1205        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_DESTROY_URL,
1206                              (unsigned long long) id, ".json");
1207        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1208        g_free(url);
1209}
1210
1211void twitter_status_retweet(struct im_connection *ic, guint64 id)
1212{
1213        char *url;
1214        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_RETWEET_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
1220/**
1221 * Report a user for sending spam.
1222 */
1223void twitter_report_spam(struct im_connection *ic, char *screen_name)
1224{
1225        char *args[2] = {
1226                "screen_name",
1227                NULL,
1228        };
1229        args[1] = screen_name;
1230        twitter_http(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post,
1231                     ic, 1, args, 2);
1232}
1233
1234/**
1235 * Favourite a tweet.
1236 */
1237void twitter_favourite_tweet(struct im_connection *ic, guint64 id)
1238{
1239        char *url;
1240        url = g_strdup_printf("%s%llu%s", TWITTER_FAVORITE_CREATE_URL,
1241                              (unsigned long long) id, ".json");
1242        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1243        g_free(url);
1244}
Note: See TracBrowser for help on using the repository browser.