source: protocols/twitter/twitter_lib.c @ fb351ce

Last change on this file since fb351ce was fb351ce, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-09T00:07:23Z

Getting better. Corruption fixed, fetching of mentions fixed, error handling
"fixed".

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