source: protocols/twitter/twitter_lib.c @ 631ec80

Last change on this file since 631ec80 was 631ec80, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-25T14:26:23Z

Changed mode/room management a little bit.

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