source: protocols/twitter/twitter_lib.c @ 2a6da96

Last change on this file since 2a6da96 was 2a6da96, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-09-25T00:08:54Z

Move Twitter XML parsing/error checking into a separate function and use it
everywhere. This should be a more thorough fix for #953.

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