source: protocols/twitter/twitter_lib.c @ 9ed0081

Last change on this file since 9ed0081 was 9ed0081, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-25T18:39:11Z

Fixed one potential memory leak, and re-remembered that for GLib + valgrind
you REALLY need to set G_SLICE=always-malloc. Argh!

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