source: protocols/twitter/twitter_lib.c @ 8e3b7ac

Last change on this file since 8e3b7ac was 8e3b7ac, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-08T22:38:20Z

It logs in and fetches statuses! \o/ But, some corruption..

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