source: protocols/twitter/twitter_lib.c @ e08ae0c

Last change on this file since e08ae0c was e08ae0c, checked in by Wilmer van der Gaast <wilmer@…>, at 2012-11-04T23:39:48Z

Can log in now. Fails to fetch timelines though, which is going to be the
more annoying part anyway. Plus, I want streaming API stuff instead.

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