source: protocols/twitter/twitter_lib.c @ 6f55bec

Last change on this file since 6f55bec was 11ec078, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-09-22T12:44:47Z

Since I can't figure out where the stalls are coming from at this point, at
least have a work-around for it.

After hitting the Twitter timer a few times while a previous fetch still
seems to be running, close the connection. Auto-reconnect will do the rest.

  • Property mode set to 100644
File size: 29.5 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-2011 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 "xmltree.h"
38#include "twitter_lib.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
72static void twitter_groupchat_init(struct im_connection *ic);
73
74/**
75 * Frees a twitter_xml_user struct.
76 */
77static void txu_free(struct twitter_xml_user *txu)
78{
79        if (txu == NULL)
80                return;
81
82        g_free(txu->name);
83        g_free(txu->screen_name);
84        g_free(txu);
85}
86
87/**
88 * Frees a twitter_xml_status struct.
89 */
90static void txs_free(struct twitter_xml_status *txs)
91{
92        if (txs == NULL)
93                return;
94
95        g_free(txs->text);
96        txu_free(txs->user);
97        g_free(txs);
98}
99
100/**
101 * Free a twitter_xml_list struct.
102 * type is the type of list the struct holds.
103 */
104static void txl_free(struct twitter_xml_list *txl)
105{
106        GSList *l;
107        if (txl == NULL)
108                return;
109
110        for (l = txl->list; l; l = g_slist_next(l)) {
111                if (txl->type == TXL_STATUS) {
112                        txs_free((struct twitter_xml_status *) l->data);
113                } else if (txl->type == TXL_ID) {
114                        g_free(l->data);
115                } else if (txl->type == TXL_USER) {
116                        txu_free(l->data);
117                }
118        }
119
120        g_slist_free(txl->list);
121        g_free(txl);
122}
123
124/**
125 * Compare status elements
126 */
127static gint twitter_compare_elements(gconstpointer a, gconstpointer b)
128{
129        struct twitter_xml_status *a_status = (struct twitter_xml_status *) a;
130        struct twitter_xml_status *b_status = (struct twitter_xml_status *) b;
131
132        if (a_status->created_at < b_status->created_at) {
133                return -1;
134        } else if (a_status->created_at > b_status->created_at) {
135                return 1;
136        } else {
137                return 0;
138        }
139}
140
141/**
142 * Add a buddy if it is not already added, set the status to logged in.
143 */
144static void twitter_add_buddy(struct im_connection *ic, char *name, const char *fullname)
145{
146        struct twitter_data *td = ic->proto_data;
147
148        // Check if the buddy is already in the buddy list.
149        if (!bee_user_by_handle(ic->bee, ic, name)) {
150                char *mode = set_getstr(&ic->acc->set, "mode");
151
152                // The buddy is not in the list, add the buddy and set the status to logged in.
153                imcb_add_buddy(ic, name, NULL);
154                imcb_rename_buddy(ic, name, fullname);
155                if (g_strcasecmp(mode, "chat") == 0) {
156                        /* Necessary so that nicks always get translated to the
157                           exact Twitter username. */
158                        imcb_buddy_nick_hint(ic, name, name);
159                        imcb_chat_add_buddy(td->timeline_gc, name);
160                } else if (g_strcasecmp(mode, "many") == 0)
161                        imcb_buddy_status(ic, name, OPT_LOGGED_IN, NULL, NULL);
162        }
163}
164
165/* Warning: May return a malloc()ed value, which will be free()d on the next
166   call. Only for short-term use. NOT THREADSAFE!  */
167char *twitter_parse_error(struct http_request *req)
168{
169        static char *ret = NULL;
170        struct xt_node *root, *node, *err;
171
172        g_free(ret);
173        ret = NULL;
174
175        if (req->body_size > 0) {
176                root = xt_from_string(req->reply_body, req->body_size);
177               
178                for (node = root; node; node = node->next)
179                        if ((err = xt_find_node(node->children, "error")) && err->text_len > 0) {
180                                ret = g_strdup_printf("%s (%s)", req->status_string, err->text);
181                                break;
182                        }
183
184                xt_free_node(root);
185        }
186
187        return ret ? ret : req->status_string;
188}
189
190static void twitter_http_get_friends_ids(struct http_request *req);
191
192/**
193 * Get the friends ids.
194 */
195void twitter_get_friends_ids(struct im_connection *ic, gint64 next_cursor)
196{
197        // Primitive, but hey! It works...     
198        char *args[2];
199        args[0] = "cursor";
200        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
201        twitter_http(ic, TWITTER_FRIENDS_IDS_URL, twitter_http_get_friends_ids, ic, 0, args, 2);
202
203        g_free(args[1]);
204}
205
206/**
207 * Function to help fill a list.
208 */
209static xt_status twitter_xt_next_cursor(struct xt_node *node, struct twitter_xml_list *txl)
210{
211        char *end = NULL;
212
213        if (node->text)
214                txl->next_cursor = g_ascii_strtoll(node->text, &end, 10);
215        if (end == NULL)
216                txl->next_cursor = -1;
217
218        return XT_HANDLED;
219}
220
221/**
222 * Fill a list of ids.
223 */
224static xt_status twitter_xt_get_friends_id_list(struct xt_node *node, struct twitter_xml_list *txl)
225{
226        struct xt_node *child;
227
228        // Set the list type.
229        txl->type = TXL_ID;
230
231        // The root <statuses> node should hold the list of statuses <status>
232        // Walk over the nodes children.
233        for (child = node->children; child; child = child->next) {
234                if (g_strcasecmp("ids", child->name) == 0) {
235                        struct xt_node *idc;
236                        for (idc = child->children; idc; idc = idc->next)
237                                if (g_strcasecmp(idc->name, "id") == 0)
238                                        txl->list = g_slist_prepend(txl->list,
239                                                g_memdup(idc->text, idc->text_len + 1));
240                } else if (g_strcasecmp("next_cursor", child->name) == 0) {
241                        twitter_xt_next_cursor(child, txl);
242                }
243        }
244
245        return XT_HANDLED;
246}
247
248static void twitter_get_users_lookup(struct im_connection *ic);
249
250/**
251 * Callback for getting the friends ids.
252 */
253static void twitter_http_get_friends_ids(struct http_request *req)
254{
255        struct im_connection *ic;
256        struct xt_node *parsed;
257        struct twitter_xml_list *txl;
258        struct twitter_data *td;
259
260        ic = req->data;
261
262        // Check if the connection is still active.
263        if (!g_slist_find(twitter_connections, ic))
264                return;
265
266        td = ic->proto_data;
267
268        // Check if the HTTP request went well. More strict checks as this is
269        // the first request we do in a session.
270        if (req->status_code == 401) {
271                imcb_error(ic, "Authentication failure");
272                imc_logout(ic, FALSE);
273                return;
274        } else if (req->status_code != 200) {
275                // It didn't go well, output the error and return.
276                imcb_error(ic, "Could not retrieve %s: %s",
277                           TWITTER_FRIENDS_IDS_URL, twitter_parse_error(req));
278                imc_logout(ic, TRUE);
279                return;
280        } else {
281                td->http_fails = 0;
282        }
283
284        /* Create the room now that we "logged in". */
285        if (!td->timeline_gc && g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "chat") == 0)
286                twitter_groupchat_init(ic);
287
288        txl = g_new0(struct twitter_xml_list, 1);
289        txl->list = td->follow_ids;
290
291        // Parse the data.
292        parsed = xt_from_string(req->reply_body, req->body_size);
293        twitter_xt_get_friends_id_list(parsed, txl);
294        xt_free_node(parsed);
295
296        td->follow_ids = txl->list;
297        if (txl->next_cursor)
298                /* These were just numbers. Up to 4000 in a response AFAIK so if we get here
299                   we may be using a spammer account. \o/ */
300                twitter_get_friends_ids(ic, txl->next_cursor);
301        else
302                /* Now to convert all those numbers into names.. */
303                twitter_get_users_lookup(ic);
304
305        txl->list = NULL;
306        txl_free(txl);
307}
308
309static xt_status twitter_xt_get_users(struct xt_node *node, struct twitter_xml_list *txl);
310static void twitter_http_get_users_lookup(struct http_request *req);
311
312static void twitter_get_users_lookup(struct im_connection *ic)
313{
314        struct twitter_data *td = ic->proto_data;
315        char *args[2] = {
316                "user_id",
317                NULL,
318        };
319        GString *ids = g_string_new("");
320        int i;
321       
322        /* We can request up to 100 users at a time. */
323        for (i = 0; i < 100 && td->follow_ids; i ++) {
324                g_string_append_printf(ids, ",%s", (char*) td->follow_ids->data);
325                g_free(td->follow_ids->data);
326                td->follow_ids = g_slist_remove(td->follow_ids, td->follow_ids->data);
327        }
328        if (ids->len > 0) {
329                args[1] = ids->str + 1;
330                /* POST, because I think ids can be up to 1KB long. */
331                twitter_http(ic, TWITTER_USERS_LOOKUP_URL, twitter_http_get_users_lookup, ic, 1, args, 2);
332        } else {
333                /* We have all users. Continue with login. (Get statuses.) */
334                td->flags |= TWITTER_HAVE_FRIENDS;
335                twitter_login_finish(ic);
336        }
337        g_string_free(ids, TRUE);
338}
339
340/**
341 * Callback for getting (twitter)friends...
342 *
343 * Be afraid, be very afraid! This function will potentially add hundreds of "friends". "Who has
344 * hundreds of friends?" you wonder? You probably not, since you are reading the source of
345 * BitlBee... Get a life and meet new people!
346 */
347static void twitter_http_get_users_lookup(struct http_request *req)
348{
349        struct im_connection *ic = req->data;
350        struct twitter_data *td;
351        struct xt_node *parsed;
352        struct twitter_xml_list *txl;
353        GSList *l = NULL;
354        struct twitter_xml_user *user;
355
356        // Check if the connection is still active.
357        if (!g_slist_find(twitter_connections, ic))
358                return;
359
360        td = ic->proto_data;
361
362        if (req->status_code != 200) {
363                // It didn't go well, output the error and return.
364                imcb_error(ic, "Could not retrieve %s: %s",
365                           TWITTER_USERS_LOOKUP_URL, twitter_parse_error(req));
366                imc_logout(ic, TRUE);
367                return;
368        } else {
369                td->http_fails = 0;
370        }
371
372        txl = g_new0(struct twitter_xml_list, 1);
373        txl->list = NULL;
374
375        // Parse the data.
376        parsed = xt_from_string(req->reply_body, req->body_size);
377
378        // Get the user list from the parsed xml feed.
379        twitter_xt_get_users(parsed, txl);
380        xt_free_node(parsed);
381
382        // Add the users as buddies.
383        for (l = txl->list; l; l = g_slist_next(l)) {
384                user = l->data;
385                twitter_add_buddy(ic, user->screen_name, user->name);
386        }
387
388        // Free the structure.
389        txl_free(txl);
390
391        twitter_get_users_lookup(ic);
392}
393
394/**
395 * Function to fill a twitter_xml_user struct.
396 * It sets:
397 *  - the name and
398 *  - the screen_name.
399 */
400static xt_status twitter_xt_get_user(struct xt_node *node, struct twitter_xml_user *txu)
401{
402        struct xt_node *child;
403
404        // Walk over the nodes children.
405        for (child = node->children; child; child = child->next) {
406                if (g_strcasecmp("name", child->name) == 0) {
407                        txu->name = g_memdup(child->text, child->text_len + 1);
408                } else if (g_strcasecmp("screen_name", child->name) == 0) {
409                        txu->screen_name = g_memdup(child->text, child->text_len + 1);
410                }
411        }
412        return XT_HANDLED;
413}
414
415/**
416 * Function to fill a twitter_xml_list struct.
417 * It sets:
418 *  - all <user>s from the <users> element.
419 */
420static xt_status twitter_xt_get_users(struct xt_node *node, struct twitter_xml_list *txl)
421{
422        struct twitter_xml_user *txu;
423        struct xt_node *child;
424
425        // Set the type of the list.
426        txl->type = TXL_USER;
427
428        // The root <users> node should hold the list of users <user>
429        // Walk over the nodes children.
430        for (child = node->children; child; child = child->next) {
431                if (g_strcasecmp("user", child->name) == 0) {
432                        txu = g_new0(struct twitter_xml_user, 1);
433                        twitter_xt_get_user(child, txu);
434                        // Put the item in the front of the list.
435                        txl->list = g_slist_prepend(txl->list, txu);
436                }
437        }
438
439        return XT_HANDLED;
440}
441
442#ifdef __GLIBC__
443#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S %z %Y"
444#else
445#define TWITTER_TIME_FORMAT "%a %b %d %H:%M:%S +0000 %Y"
446#endif
447
448/**
449 * Function to fill a twitter_xml_status struct.
450 * It sets:
451 *  - the status text and
452 *  - the created_at timestamp and
453 *  - the status id and
454 *  - the user in a twitter_xml_user struct.
455 */
456static xt_status twitter_xt_get_status(struct xt_node *node, struct twitter_xml_status *txs)
457{
458        struct xt_node *child, *rt = NULL;
459
460        // Walk over the nodes children.
461        for (child = node->children; child; child = child->next) {
462                if (g_strcasecmp("text", child->name) == 0) {
463                        txs->text = g_memdup(child->text, child->text_len + 1);
464                } else if (g_strcasecmp("retweeted_status", child->name) == 0) {
465                        rt = child;
466                } else if (g_strcasecmp("created_at", child->name) == 0) {
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(child->text, TWITTER_TIME_FORMAT, &parsed) != NULL)
473                                txs->created_at = mktime_utc(&parsed);
474                } else if (g_strcasecmp("user", child->name) == 0) {
475                        txs->user = g_new0(struct twitter_xml_user, 1);
476                        twitter_xt_get_user(child, txs->user);
477                } else if (g_strcasecmp("id", child->name) == 0) {
478                        txs->id = g_ascii_strtoull(child->text, NULL, 10);
479                } else if (g_strcasecmp("in_reply_to_status_id", child->name) == 0) {
480                        txs->reply_to = g_ascii_strtoull(child->text, NULL, 10);
481                }
482        }
483
484        /* If it's a (truncated) retweet, get the original. Even if the API claims it
485           wasn't truncated because it may be lying. */
486        if (rt) {
487                struct twitter_xml_status *rtxs = g_new0(struct twitter_xml_status, 1);
488                if (twitter_xt_get_status(rt, rtxs) != XT_HANDLED) {
489                        txs_free(rtxs);
490                        return XT_HANDLED;
491                }
492
493                g_free(txs->text);
494                txs->text = g_strdup_printf("RT @%s: %s", rtxs->user->screen_name, rtxs->text);
495                txs_free(rtxs);
496        } else {
497                struct xt_node *urls, *url;
498               
499                urls = xt_find_path(node, "entities");
500                if (urls != NULL)
501                        urls = urls->children;
502                for (; urls; urls = urls->next) {
503                        if (strcmp(urls->name, "urls") != 0 && strcmp(urls->name, "media") != 0)
504                                continue;
505                       
506                        for (url = urls ? urls->children : NULL; url; url = url->next) {
507                                /* "short" is a reserved word. :-P */
508                                struct xt_node *kort = xt_find_node(url->children, "url");
509                                struct xt_node *disp = xt_find_node(url->children, "display_url");
510                                char *pos, *new;
511                               
512                                if (!kort || !kort->text || !disp || !disp->text ||
513                                    !(pos = strstr(txs->text, kort->text)))
514                                        continue;
515                               
516                                *pos = '\0';
517                                new = g_strdup_printf("%s%s &lt;%s&gt;%s", txs->text, kort->text,
518                                                      disp->text, pos + strlen(kort->text));
519                               
520                                g_free(txs->text);
521                                txs->text = new;
522                        }
523                }
524        }
525
526        return XT_HANDLED;
527}
528
529/**
530 * Function to fill a twitter_xml_list struct.
531 * It sets:
532 *  - all <status>es within the <status> element and
533 *  - the next_cursor.
534 */
535static xt_status twitter_xt_get_status_list(struct im_connection *ic, struct xt_node *node,
536                                            struct twitter_xml_list *txl)
537{
538        struct twitter_xml_status *txs;
539        struct xt_node *child;
540        bee_user_t *bu;
541
542        // Set the type of the list.
543        txl->type = TXL_STATUS;
544
545        // The root <statuses> node should hold the list of statuses <status>
546        // Walk over the nodes children.
547        for (child = node->children; child; child = child->next) {
548                if (g_strcasecmp("status", child->name) == 0) {
549                        txs = g_new0(struct twitter_xml_status, 1);
550                        twitter_xt_get_status(child, txs);
551                        // Put the item in the front of the list.
552                        txl->list = g_slist_prepend(txl->list, txs);
553
554                        if (txs->user && txs->user->screen_name &&
555                            (bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name))) {
556                                struct twitter_user_data *tud = bu->data;
557
558                                if (txs->id > tud->last_id) {
559                                        tud->last_id = txs->id;
560                                        tud->last_time = txs->created_at;
561                                }
562                        }
563                } else if (g_strcasecmp("next_cursor", child->name) == 0) {
564                        twitter_xt_next_cursor(child, txl);
565                }
566        }
567
568        return XT_HANDLED;
569}
570
571static char *twitter_msg_add_id(struct im_connection *ic,
572                                struct twitter_xml_status *txs, const char *prefix)
573{
574        struct twitter_data *td = ic->proto_data;
575        char *ret = NULL;
576
577        if (!set_getbool(&ic->acc->set, "show_ids")) {
578                if (*prefix)
579                        return g_strconcat(prefix, txs->text, NULL);
580                else
581                        return NULL;
582        }
583
584        td->log[td->log_id].id = txs->id;
585        td->log[td->log_id].bu = bee_user_by_handle(ic->bee, ic, txs->user->screen_name);
586        if (txs->reply_to) {
587                int i;
588                for (i = 0; i < TWITTER_LOG_LENGTH; i++)
589                        if (td->log[i].id == txs->reply_to) {
590                                ret = g_strdup_printf("\002[\002%02d->%02d\002]\002 %s%s",
591                                                      td->log_id, i, prefix, txs->text);
592                                break;
593                        }
594        }
595        if (ret == NULL)
596                ret = g_strdup_printf("\002[\002%02d\002]\002 %s%s", td->log_id, prefix, txs->text);
597        td->log_id = (td->log_id + 1) % TWITTER_LOG_LENGTH;
598
599        return ret;
600}
601
602static void twitter_groupchat_init(struct im_connection *ic)
603{
604        char *name_hint;
605        struct groupchat *gc;
606        struct twitter_data *td = ic->proto_data;
607        GSList *l;
608
609        td->timeline_gc = gc = imcb_chat_new(ic, "twitter/timeline");
610
611        name_hint = g_strdup_printf("%s_%s", td->prefix, ic->acc->user);
612        imcb_chat_name_hint(gc, name_hint);
613        g_free(name_hint);
614
615        for (l = ic->bee->users; l; l = l->next) {
616                bee_user_t *bu = l->data;
617                if (bu->ic == ic)
618                        imcb_chat_add_buddy(td->timeline_gc, bu->handle);
619        }
620}
621
622/**
623 * Function that is called to see the statuses in a groupchat window.
624 */
625static void twitter_groupchat(struct im_connection *ic, GSList * list)
626{
627        struct twitter_data *td = ic->proto_data;
628        GSList *l = NULL;
629        struct twitter_xml_status *status;
630        struct groupchat *gc;
631        guint64 last_id = 0;
632
633        // Create a new groupchat if it does not exsist.
634        if (!td->timeline_gc)
635                twitter_groupchat_init(ic);
636
637        gc = td->timeline_gc;
638        if (!gc->joined)
639                imcb_chat_add_buddy(gc, ic->acc->user);
640
641        for (l = list; l; l = g_slist_next(l)) {
642                char *msg;
643
644                status = l->data;
645                if (status->user == NULL || status->text == NULL || last_id == status->id)
646                        continue;
647
648                last_id = status->id;
649
650                strip_html(status->text);
651
652                if (set_getbool(&ic->acc->set, "strip_newlines"))
653                        strip_newlines(status->text);
654
655                msg = twitter_msg_add_id(ic, status, "");
656
657                // Say it!
658                if (g_strcasecmp(td->user, status->user->screen_name) == 0) {
659                        imcb_chat_log(gc, "You: %s", msg ? msg : status->text);
660                } else {
661                        twitter_add_buddy(ic, status->user->screen_name, status->user->name);
662
663                        imcb_chat_msg(gc, status->user->screen_name,
664                                      msg ? msg : status->text, 0, status->created_at);
665                }
666
667                g_free(msg);
668
669                // Update the timeline_id to hold the highest id, so that by the next request
670                // we won't pick up the updates already in the list.
671                td->timeline_id = MAX(td->timeline_id, status->id);
672        }
673}
674
675/**
676 * Function that is called to see statuses as private messages.
677 */
678static void twitter_private_message_chat(struct im_connection *ic, GSList * list)
679{
680        struct twitter_data *td = ic->proto_data;
681        GSList *l = NULL;
682        struct twitter_xml_status *status;
683        char from[MAX_STRING];
684        gboolean mode_one;
685        guint64 last_id = 0;
686
687        mode_one = g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "one") == 0;
688
689        if (mode_one) {
690                g_snprintf(from, sizeof(from) - 1, "%s_%s", td->prefix, ic->acc->user);
691                from[MAX_STRING - 1] = '\0';
692        }
693
694        for (l = list; l; l = g_slist_next(l)) {
695                char *prefix = NULL, *text = NULL;
696
697                status = l->data;
698                if (status->user == NULL || status->text == NULL || last_id == status->id)
699                        continue;
700
701                last_id = status->id;
702
703                strip_html(status->text);
704                if (mode_one)
705                        prefix = g_strdup_printf("\002<\002%s\002>\002 ",
706                                                 status->user->screen_name);
707                else
708                        twitter_add_buddy(ic, status->user->screen_name, status->user->name);
709
710                text = twitter_msg_add_id(ic, status, prefix ? prefix : "");
711
712                imcb_buddy_msg(ic,
713                               mode_one ? from : status->user->screen_name,
714                               text ? text : status->text, 0, status->created_at);
715
716                // Update the timeline_id to hold the highest id, so that by the next request
717                // we won't pick up the updates already in the list.
718                td->timeline_id = MAX(td->timeline_id, status->id);
719
720                g_free(text);
721                g_free(prefix);
722        }
723}
724
725static void twitter_http_get_home_timeline(struct http_request *req);
726static void twitter_http_get_mentions(struct http_request *req);
727
728/**
729 * Get the timeline with optionally mentions
730 */
731void twitter_get_timeline(struct im_connection *ic, gint64 next_cursor)
732{
733        struct twitter_data *td = ic->proto_data;
734        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
735
736        if (td->flags & TWITTER_DOING_TIMELINE) {
737                if (++td->http_fails >= 5) {
738                        imcb_error(ic, "Fetch timeout (%d)", td->flags);
739                        imc_logout(ic, TRUE);
740                }
741        }
742
743        td->flags |= TWITTER_DOING_TIMELINE;
744
745        twitter_get_home_timeline(ic, next_cursor);
746
747        if (include_mentions) {
748                twitter_get_mentions(ic, next_cursor);
749        }
750}
751
752/**
753 * Call this one after receiving timeline/mentions. Show to user once we have
754 * both.
755 */
756void twitter_flush_timeline(struct im_connection *ic)
757{
758        struct twitter_data *td = ic->proto_data;
759        gboolean include_mentions = set_getbool(&ic->acc->set, "fetch_mentions");
760        int show_old_mentions = set_getint(&ic->acc->set, "show_old_mentions");
761        struct twitter_xml_list *home_timeline = td->home_timeline_obj;
762        struct twitter_xml_list *mentions = td->mentions_obj;
763        GSList *output = NULL;
764        GSList *l;
765
766        if (!(td->flags & TWITTER_GOT_TIMELINE)) {
767                return;
768        }
769
770        if (include_mentions && !(td->flags & TWITTER_GOT_MENTIONS)) {
771                return;
772        }
773
774        if (home_timeline && home_timeline->list) {
775                for (l = home_timeline->list; l; l = g_slist_next(l)) {
776                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
777                }
778        }
779
780        if (include_mentions && mentions && mentions->list) {
781                for (l = mentions->list; l; l = g_slist_next(l)) {
782                        if (show_old_mentions < 1 && output && twitter_compare_elements(l->data, output->data) < 0) {
783                                continue;
784                        }
785
786                        output = g_slist_insert_sorted(output, l->data, twitter_compare_elements);
787                }
788        }
789
790        // See if the user wants to see the messages in a groupchat window or as private messages.
791        if (g_strcasecmp(set_getstr(&ic->acc->set, "mode"), "chat") == 0)
792                twitter_groupchat(ic, output);
793        else
794                twitter_private_message_chat(ic, output);
795
796        g_slist_free(output);
797
798        txl_free(home_timeline);
799        txl_free(mentions);
800
801        td->flags &= ~(TWITTER_DOING_TIMELINE | TWITTER_GOT_TIMELINE | TWITTER_GOT_MENTIONS);
802        td->home_timeline_obj = td->mentions_obj = NULL;
803}
804
805/**
806 * Get the timeline.
807 */
808void twitter_get_home_timeline(struct im_connection *ic, gint64 next_cursor)
809{
810        struct twitter_data *td = ic->proto_data;
811
812        txl_free(td->home_timeline_obj);
813        td->home_timeline_obj = NULL;
814        td->flags &= ~TWITTER_GOT_TIMELINE;
815
816        char *args[6];
817        args[0] = "cursor";
818        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
819        args[2] = "include_entities";
820        args[3] = "true";
821        if (td->timeline_id) {
822                args[4] = "since_id";
823                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
824        }
825
826        if (twitter_http(ic, TWITTER_HOME_TIMELINE_URL, twitter_http_get_home_timeline, ic, 0, args,
827                     td->timeline_id ? 6 : 4) == NULL) {
828                if (++td->http_fails >= 5)
829                        imcb_error(ic, "Could not retrieve %s: %s",
830                                   TWITTER_HOME_TIMELINE_URL, "connection failed");
831                td->flags |= TWITTER_GOT_TIMELINE;
832                twitter_flush_timeline(ic);
833        }
834
835        g_free(args[1]);
836        if (td->timeline_id) {
837                g_free(args[5]);
838        }
839}
840
841/**
842 * Get mentions.
843 */
844void twitter_get_mentions(struct im_connection *ic, gint64 next_cursor)
845{
846        struct twitter_data *td = ic->proto_data;
847
848        txl_free(td->mentions_obj);
849        td->mentions_obj = NULL;
850        td->flags &= ~TWITTER_GOT_MENTIONS;
851
852        char *args[6];
853        args[0] = "cursor";
854        args[1] = g_strdup_printf("%lld", (long long) next_cursor);
855        args[2] = "include_entities";
856        args[3] = "true";
857        if (td->timeline_id) {
858                args[4] = "since_id";
859                args[5] = g_strdup_printf("%llu", (long long unsigned int) td->timeline_id);
860        } else {
861                args[4] = "count";
862                args[5] = g_strdup_printf("%d", set_getint(&ic->acc->set, "show_old_mentions"));
863        }
864
865        if (twitter_http(ic, TWITTER_MENTIONS_URL, twitter_http_get_mentions,
866                         ic, 0, args, 6) == NULL) {
867                if (++td->http_fails >= 5)
868                        imcb_error(ic, "Could not retrieve %s: %s",
869                                   TWITTER_MENTIONS_URL, "connection failed");
870                td->flags |= TWITTER_GOT_MENTIONS;
871                twitter_flush_timeline(ic);
872        }
873
874        g_free(args[1]);
875        if (td->timeline_id) {
876                g_free(args[5]);
877        }
878}
879
880/**
881 * Callback for getting the home timeline.
882 */
883static void twitter_http_get_home_timeline(struct http_request *req)
884{
885        struct im_connection *ic = req->data;
886        struct twitter_data *td;
887        struct xt_node *parsed;
888        struct twitter_xml_list *txl;
889
890        // Check if the connection is still active.
891        if (!g_slist_find(twitter_connections, ic))
892                return;
893
894        td = ic->proto_data;
895
896        // Check if the HTTP request went well.
897        if (req->status_code == 200) {
898                td->http_fails = 0;
899                if (!(ic->flags & OPT_LOGGED_IN))
900                        imcb_connected(ic);
901        } else {
902                // It didn't go well, output the error and return.
903                if (++td->http_fails >= 5)
904                        imcb_error(ic, "Could not retrieve %s: %s",
905                                   TWITTER_HOME_TIMELINE_URL, twitter_parse_error(req));
906
907                goto end;
908        }
909
910        txl = g_new0(struct twitter_xml_list, 1);
911        txl->list = NULL;
912
913        // Parse the data.
914        parsed = xt_from_string(req->reply_body, req->body_size);
915        // The root <statuses> node should hold the list of statuses <status>
916        twitter_xt_get_status_list(ic, parsed, txl);
917        xt_free_node(parsed);
918
919        td->home_timeline_obj = txl;
920
921      end:
922        td->flags |= TWITTER_GOT_TIMELINE;
923
924        twitter_flush_timeline(ic);
925}
926
927/**
928 * Callback for getting mentions.
929 */
930static void twitter_http_get_mentions(struct http_request *req)
931{
932        struct im_connection *ic = req->data;
933        struct twitter_data *td;
934        struct xt_node *parsed;
935        struct twitter_xml_list *txl;
936
937        // Check if the connection is still active.
938        if (!g_slist_find(twitter_connections, ic))
939                return;
940
941        td = ic->proto_data;
942
943        // Check if the HTTP request went well.
944        if (req->status_code == 200) {
945                td->http_fails = 0;
946                if (!(ic->flags & OPT_LOGGED_IN))
947                        imcb_connected(ic);
948        } else {
949                // It didn't go well, output the error and return.
950                if (++td->http_fails >= 5)
951                        imcb_error(ic, "Could not retrieve %s: %s",
952                                   TWITTER_MENTIONS_URL, twitter_parse_error(req));
953
954                goto end;
955        }
956
957        txl = g_new0(struct twitter_xml_list, 1);
958        txl->list = NULL;
959
960        // Parse the data.
961        parsed = xt_from_string(req->reply_body, req->body_size);
962        // The root <statuses> node should hold the list of statuses <status>
963        twitter_xt_get_status_list(ic, parsed, txl);
964        xt_free_node(parsed);
965
966        td->mentions_obj = txl;
967
968      end:
969        td->flags |= TWITTER_GOT_MENTIONS;
970
971        twitter_flush_timeline(ic);
972}
973
974/**
975 * Callback to use after sending a POST request to twitter.
976 * (Generic, used for a few kinds of queries.)
977 */
978static void twitter_http_post(struct http_request *req)
979{
980        struct im_connection *ic = req->data;
981        struct twitter_data *td;
982
983        // Check if the connection is still active.
984        if (!g_slist_find(twitter_connections, ic))
985                return;
986
987        td = ic->proto_data;
988        td->last_status_id = 0;
989
990        // Check if the HTTP request went well.
991        if (req->status_code != 200) {
992                // It didn't go well, output the error and return.
993                imcb_error(ic, "HTTP error: %s", twitter_parse_error(req));
994                return;
995        }
996
997        if (req->body_size > 0) {
998                struct xt_node *parsed, *node;
999
1000                parsed = xt_from_string(req->reply_body, req->body_size);
1001
1002                if ((node = xt_find_node(parsed, "status")) &&
1003                    (node = xt_find_node(node->children, "id")) && node->text)
1004                        td->last_status_id = g_ascii_strtoull(node->text, NULL, 10);
1005
1006                xt_free_node(parsed);
1007        }
1008}
1009
1010/**
1011 * Function to POST a new status to twitter.
1012 */
1013void twitter_post_status(struct im_connection *ic, char *msg, guint64 in_reply_to)
1014{
1015        char *args[4] = {
1016                "status", msg,
1017                "in_reply_to_status_id",
1018                g_strdup_printf("%llu", (unsigned long long) in_reply_to)
1019        };
1020        twitter_http(ic, TWITTER_STATUS_UPDATE_URL, twitter_http_post, ic, 1,
1021                     args, in_reply_to ? 4 : 2);
1022        g_free(args[3]);
1023}
1024
1025
1026/**
1027 * Function to POST a new message to twitter.
1028 */
1029void twitter_direct_messages_new(struct im_connection *ic, char *who, char *msg)
1030{
1031        char *args[4];
1032        args[0] = "screen_name";
1033        args[1] = who;
1034        args[2] = "text";
1035        args[3] = msg;
1036        // Use the same callback as for twitter_post_status, since it does basically the same.
1037        twitter_http(ic, TWITTER_DIRECT_MESSAGES_NEW_URL, twitter_http_post, ic, 1, args, 4);
1038}
1039
1040void twitter_friendships_create_destroy(struct im_connection *ic, char *who, int create)
1041{
1042        char *args[2];
1043        args[0] = "screen_name";
1044        args[1] = who;
1045        twitter_http(ic, create ? TWITTER_FRIENDSHIPS_CREATE_URL : TWITTER_FRIENDSHIPS_DESTROY_URL,
1046                     twitter_http_post, ic, 1, args, 2);
1047}
1048
1049void twitter_status_destroy(struct im_connection *ic, guint64 id)
1050{
1051        char *url;
1052        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_DESTROY_URL,
1053                              (unsigned long long) id, ".xml");
1054        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1055        g_free(url);
1056}
1057
1058void twitter_status_retweet(struct im_connection *ic, guint64 id)
1059{
1060        char *url;
1061        url = g_strdup_printf("%s%llu%s", TWITTER_STATUS_RETWEET_URL,
1062                              (unsigned long long) id, ".xml");
1063        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1064        g_free(url);
1065}
1066
1067/**
1068 * Report a user for sending spam.
1069 */
1070void twitter_report_spam(struct im_connection *ic, char *screen_name)
1071{
1072        char *args[2] = {
1073                "screen_name",
1074                NULL,
1075        };
1076        args[1] = screen_name;
1077        twitter_http(ic, TWITTER_REPORT_SPAM_URL, twitter_http_post,
1078                     ic, 1, args, 2);
1079}
1080
1081/**
1082 * Favourite a tweet.
1083 */
1084void twitter_favourite_tweet(struct im_connection *ic, guint64 id)
1085{
1086        char *url;
1087        url = g_strdup_printf("%s%llu%s", TWITTER_FAVORITE_CREATE_URL,
1088                              (unsigned long long) id, ".xml");
1089        twitter_http(ic, url, twitter_http_post, ic, 1, NULL, 0);
1090        g_free(url);
1091}
Note: See TracBrowser for help on using the repository browser.