source: protocols/twitter/twitter_lib.c @ 24132ec

Last change on this file since 24132ec was 24132ec, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-09T23:53:45Z

Fixed the last parser (generic handler which just remembers status IDs).
xmltree.h include can almost be removed, it's just used for return values
now.

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