source: protocols/twitter/twitter.c @ bdf9214

Last change on this file since bdf9214 was 952e264, checked in by dequis <dx@…>, at 2017-04-11T23:44:58Z

twitter: experimental support for place_id

  • Property mode set to 100644
File size: 29.1 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Simple module to facilitate twitter functionality.                       *
5*                                                                           *
6*  Copyright 2009-2010 Geert Mulders <g.c.w.m.mulders@gmail.com>            *
7*  Copyright 2010-2013 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#include "nogaim.h"
26#include "oauth.h"
27#include "twitter.h"
28#include "twitter_http.h"
29#include "twitter_lib.h"
30#include "url.h"
31
32GSList *twitter_connections = NULL;
33
34static int twitter_filter_cmp(struct twitter_filter *tf1,
35                              struct twitter_filter *tf2)
36{
37        int i1 = 0;
38        int i2 = 0;
39        int i;
40
41        static const twitter_filter_type_t types[] = {
42                /* Order of the types */
43                TWITTER_FILTER_TYPE_FOLLOW,
44                TWITTER_FILTER_TYPE_TRACK
45        };
46
47        for (i = 0; i < G_N_ELEMENTS(types); i++) {
48                if (types[i] == tf1->type) {
49                        i1 = i + 1;
50                        break;
51                }
52        }
53
54        for (i = 0; i < G_N_ELEMENTS(types); i++) {
55                if (types[i] == tf2->type) {
56                        i2 = i + 1;
57                        break;
58                }
59        }
60
61        if (i1 != i2) {
62                /* With different types, return their difference */
63                return i1 - i2;
64        }
65
66        /* With the same type, return the text comparison */
67        return g_strcasecmp(tf1->text, tf2->text);
68}
69
70static gboolean twitter_filter_update(gpointer data, gint fd,
71                                      b_input_condition cond)
72{
73        struct im_connection *ic = data;
74        struct twitter_data *td = ic->proto_data;
75
76        if (td->filters) {
77                twitter_open_filter_stream(ic);
78        } else if (td->filter_stream) {
79                http_close(td->filter_stream);
80                td->filter_stream = NULL;
81        }
82
83        td->filter_update_id = 0;
84        return FALSE;
85}
86
87static struct twitter_filter *twitter_filter_get(struct groupchat *c,
88                                                 twitter_filter_type_t type,
89                                                 const char *text)
90{
91        struct twitter_data *td = c->ic->proto_data;
92        struct twitter_filter *tf = NULL;
93        struct twitter_filter tfc = { type, (char *) text };
94        GSList *l;
95
96        for (l = td->filters; l; l = g_slist_next(l)) {
97                tf = l->data;
98
99                if (twitter_filter_cmp(tf, &tfc) == 0) {
100                        break;
101                }
102
103                tf = NULL;
104        }
105
106        if (!tf) {
107                tf = g_new0(struct twitter_filter, 1);
108                tf->type = type;
109                tf->text = g_strdup(text);
110                td->filters = g_slist_prepend(td->filters, tf);
111        }
112
113        if (!g_slist_find(tf->groupchats, c)) {
114                tf->groupchats = g_slist_prepend(tf->groupchats, c);
115        }
116
117        if (td->filter_update_id > 0) {
118                b_event_remove(td->filter_update_id);
119        }
120
121        /* Wait for other possible filter changes to avoid request spam */
122        td->filter_update_id = b_timeout_add(TWITTER_FILTER_UPDATE_WAIT,
123                                             twitter_filter_update, c->ic);
124        return tf;
125}
126
127static void twitter_filter_free(struct twitter_filter *tf)
128{
129        g_slist_free(tf->groupchats);
130        g_free(tf->text);
131        g_free(tf);
132}
133
134static void twitter_filter_remove(struct groupchat *c)
135{
136        struct twitter_data *td = c->ic->proto_data;
137        struct twitter_filter *tf;
138        GSList *l = td->filters;
139        GSList *p;
140
141        while (l != NULL) {
142                tf = l->data;
143                tf->groupchats = g_slist_remove(tf->groupchats, c);
144
145                p = l;
146                l = g_slist_next(l);
147
148                if (!tf->groupchats) {
149                        twitter_filter_free(tf);
150                        td->filters = g_slist_delete_link(td->filters, p);
151                }
152        }
153
154        if (td->filter_update_id > 0) {
155                b_event_remove(td->filter_update_id);
156        }
157
158        /* Wait for other possible filter changes to avoid request spam */
159        td->filter_update_id = b_timeout_add(TWITTER_FILTER_UPDATE_WAIT,
160                                             twitter_filter_update, c->ic);
161}
162
163static void twitter_filter_remove_all(struct im_connection *ic)
164{
165        struct twitter_data *td = ic->proto_data;
166        GSList *chats = NULL;
167        struct twitter_filter *tf;
168        GSList *l = td->filters;
169        GSList *p;
170
171        while (l != NULL) {
172                tf = l->data;
173
174                /* Build up a list of groupchats to be freed */
175                for (p = tf->groupchats; p; p = g_slist_next(p)) {
176                        if (!g_slist_find(chats, p->data)) {
177                                chats = g_slist_prepend(chats, p->data);
178                        }
179                }
180
181                p = l;
182                l = g_slist_next(l);
183                twitter_filter_free(p->data);
184                td->filters = g_slist_delete_link(td->filters, p);
185        }
186
187        l = chats;
188
189        while (l != NULL) {
190                p = l;
191                l = g_slist_next(l);
192
193                /* Freed each remaining groupchat */
194                imcb_chat_free(p->data);
195                chats = g_slist_delete_link(chats, p);
196        }
197
198        if (td->filter_stream) {
199                http_close(td->filter_stream);
200                td->filter_stream = NULL;
201        }
202}
203
204static GSList *twitter_filter_parse(struct groupchat *c, const char *text)
205{
206        char **fs = g_strsplit(text, ";", 0);
207        GSList *ret = NULL;
208        struct twitter_filter *tf;
209        char **f;
210        char *v;
211        int i;
212        int t;
213
214        static const twitter_filter_type_t types[] = {
215                TWITTER_FILTER_TYPE_FOLLOW,
216                TWITTER_FILTER_TYPE_TRACK
217        };
218
219        static const char *typestrs[] = {
220                "follow",
221                "track"
222        };
223
224        for (f = fs; *f; f++) {
225                if ((v = strchr(*f, ':')) == NULL) {
226                        continue;
227                }
228
229                *(v++) = 0;
230
231                for (t = -1, i = 0; i < G_N_ELEMENTS(types); i++) {
232                        if (g_strcasecmp(typestrs[i], *f) == 0) {
233                                t = i;
234                                break;
235                        }
236                }
237
238                if (t < 0 || strlen(v) == 0) {
239                        continue;
240                }
241
242                tf = twitter_filter_get(c, types[t], v);
243                ret = g_slist_prepend(ret, tf);
244        }
245
246        g_strfreev(fs);
247        return ret;
248}
249
250/**
251 * Main loop function
252 */
253gboolean twitter_main_loop(gpointer data, gint fd, b_input_condition cond)
254{
255        struct im_connection *ic = data;
256
257        // Check if we are still logged in...
258        if (!g_slist_find(twitter_connections, ic)) {
259                return FALSE;
260        }
261
262        // Do stuff..
263        return twitter_get_timeline(ic, -1) &&
264               ((ic->flags & OPT_LOGGED_IN) == OPT_LOGGED_IN);
265}
266
267static void twitter_main_loop_start(struct im_connection *ic)
268{
269        struct twitter_data *td = ic->proto_data;
270
271        char *last_tweet = set_getstr(&ic->acc->set, "_last_tweet");
272
273        if (last_tweet) {
274                td->timeline_id = g_ascii_strtoull(last_tweet, NULL, 0);
275        }
276
277        /* Create the room now that we "logged in". */
278        if (td->flags & TWITTER_MODE_CHAT) {
279                twitter_groupchat_init(ic);
280        }
281
282        imcb_log(ic, "Getting initial statuses");
283
284        // Run this once. After this queue the main loop function (or open the
285        // stream if available).
286        twitter_main_loop(ic, -1, 0);
287
288        if (set_getbool(&ic->acc->set, "stream")) {
289                /* That fetch was just to get backlog, the stream will give
290                   us the rest. \o/ */
291                twitter_open_stream(ic);
292
293                /* Stream sends keepalives (empty lines) or actual data at
294                   least twice a minute. Disconnect if this stops. */
295                ic->flags |= OPT_PONGS;
296        } else {
297                /* Not using the streaming API, so keep polling the old-
298                   fashioned way. :-( */
299                td->main_loop_id =
300                        b_timeout_add(set_getint(&ic->acc->set, "fetch_interval") * 1000,
301                                      twitter_main_loop, ic);
302        }
303}
304
305struct groupchat *twitter_groupchat_init(struct im_connection *ic)
306{
307        char *name_hint;
308        struct groupchat *gc;
309        struct twitter_data *td = ic->proto_data;
310        GSList *l;
311
312        if (td->timeline_gc) {
313                return td->timeline_gc;
314        }
315
316        td->timeline_gc = gc = imcb_chat_new(ic, "twitter/timeline");
317
318        name_hint = g_strdup_printf("%s_%s", td->prefix, ic->acc->user);
319        imcb_chat_name_hint(gc, name_hint);
320        g_free(name_hint);
321
322        for (l = ic->bee->users; l; l = l->next) {
323                bee_user_t *bu = l->data;
324                if (bu->ic == ic) {
325                        imcb_chat_add_buddy(gc, bu->handle);
326                }
327        }
328        imcb_chat_add_buddy(gc, ic->acc->user);
329
330        return gc;
331}
332
333static void twitter_oauth_start(struct im_connection *ic);
334
335void twitter_login_finish(struct im_connection *ic)
336{
337        struct twitter_data *td = ic->proto_data;
338
339        td->flags &= ~TWITTER_DOING_TIMELINE;
340
341        if (set_getbool(&ic->acc->set, "oauth") && !td->oauth_info) {
342                twitter_oauth_start(ic);
343        } else if (!(td->flags & TWITTER_MODE_ONE) &&
344                   !(td->flags & TWITTER_HAVE_FRIENDS)) {
345                imcb_log(ic, "Getting contact list");
346                twitter_get_friends_ids(ic, -1);
347                twitter_get_mutes_ids(ic, -1);
348                twitter_get_noretweets_ids(ic, -1);
349        } else {
350                twitter_main_loop_start(ic);
351        }
352}
353
354static const struct oauth_service twitter_oauth = {
355        "https://api.twitter.com/oauth/request_token",
356        "https://api.twitter.com/oauth/access_token",
357        "https://api.twitter.com/oauth/authorize",
358        .consumer_key = "xsDNKJuNZYkZyMcu914uEA",
359        .consumer_secret = "FCxqcr0pXKzsF9ajmP57S3VQ8V6Drk4o2QYtqMcOszo",
360};
361
362static const struct oauth_service identica_oauth = {
363        "https://identi.ca/api/oauth/request_token",
364        "https://identi.ca/api/oauth/access_token",
365        "https://identi.ca/api/oauth/authorize",
366        .consumer_key = "e147ff789fcbd8a5a07963afbb43f9da",
367        .consumer_secret = "c596267f277457ec0ce1ab7bb788d828",
368};
369
370static gboolean twitter_oauth_callback(struct oauth_info *info);
371
372static const struct oauth_service *get_oauth_service(struct im_connection *ic)
373{
374        struct twitter_data *td = ic->proto_data;
375
376        if (strstr(td->url_host, "identi.ca")) {
377                return &identica_oauth;
378        } else {
379                return &twitter_oauth;
380        }
381
382        /* Could add more services, or allow configuring your own base URL +
383           API keys. */
384}
385
386static void twitter_oauth_start(struct im_connection *ic)
387{
388        struct twitter_data *td = ic->proto_data;
389        const char *url = set_getstr(&ic->acc->set, "base_url");
390
391        imcb_log(ic, "Requesting OAuth request token");
392
393        if (!strstr(url, "twitter.com") && !strstr(url, "identi.ca")) {
394                imcb_log(ic, "Warning: OAuth only works with identi.ca and "
395                         "Twitter.");
396        }
397
398        td->oauth_info = oauth_request_token(get_oauth_service(ic), twitter_oauth_callback, ic);
399
400        /* We need help from the user to complete OAuth login, so don't time
401           out on this login. */
402        ic->flags |= OPT_SLOW_LOGIN;
403}
404
405static gboolean twitter_oauth_callback(struct oauth_info *info)
406{
407        struct im_connection *ic = info->data;
408        struct twitter_data *td;
409
410        if (!g_slist_find(twitter_connections, ic)) {
411                return FALSE;
412        }
413
414        td = ic->proto_data;
415        if (info->stage == OAUTH_REQUEST_TOKEN) {
416                char *name, *msg;
417
418                if (info->request_token == NULL) {
419                        imcb_error(ic, "OAuth error: %s", twitter_parse_error(info->http));
420                        imc_logout(ic, TRUE);
421                        return FALSE;
422                }
423
424                name = g_strdup_printf("%s_%s", td->prefix, ic->acc->user);
425                msg = g_strdup_printf("To finish OAuth authentication, please visit "
426                                      "%s and respond with the resulting PIN code.",
427                                      info->auth_url);
428                imcb_buddy_msg(ic, name, msg, 0, 0);
429                g_free(name);
430                g_free(msg);
431        } else if (info->stage == OAUTH_ACCESS_TOKEN) {
432                const char *sn;
433
434                if (info->token == NULL || info->token_secret == NULL) {
435                        imcb_error(ic, "OAuth error: %s", twitter_parse_error(info->http));
436                        imc_logout(ic, TRUE);
437                        return FALSE;
438                }
439
440                if ((sn = oauth_params_get(&info->params, "screen_name"))) {
441                        if (ic->acc->prpl->handle_cmp(sn, ic->acc->user) != 0) {
442                                imcb_log(ic, "Warning: You logged in via OAuth as %s "
443                                         "instead of %s.", sn, ic->acc->user);
444                        }
445                        g_free(td->user);
446                        td->user = g_strdup(sn);
447                }
448
449                /* IM mods didn't do this so far and it's ugly but I should
450                   be able to get away with it... */
451                g_free(ic->acc->pass);
452                ic->acc->pass = oauth_to_string(info);
453
454                twitter_login_finish(ic);
455        }
456
457        return TRUE;
458}
459
460int twitter_url_len_diff(gchar *msg, unsigned int target_len)
461{
462        int url_len_diff = 0;
463
464        static GRegex *regex = NULL;
465        GMatchInfo *match_info;
466
467        if (regex == NULL) {
468                regex = g_regex_new("(^|\\s)(http(s)?://[^\\s$]+)", 0, 0, NULL);
469        }
470
471        g_regex_match(regex, msg, 0, &match_info);
472        while (g_match_info_matches(match_info)) {
473                gchar *url;
474
475                url = g_match_info_fetch(match_info, 2);
476                url_len_diff += target_len - g_utf8_strlen(url, -1);
477
478                g_free(url);
479                g_match_info_next(match_info, NULL);
480        }
481        g_match_info_free(match_info);
482
483        return url_len_diff;
484}
485
486int twitter_message_len(gchar *msg, int target_len)
487{
488        int url_len_diff = 0;
489
490        if (target_len > 0) {
491                url_len_diff = twitter_url_len_diff(msg, target_len);
492        }
493
494        return g_utf8_strlen(msg, -1) + url_len_diff;
495}
496
497static gboolean twitter_length_check(struct im_connection *ic, gchar * msg)
498{
499        int max = set_getint(&ic->acc->set, "message_length");
500        int target_len = set_getint(&ic->acc->set, "target_url_length");
501        int len = twitter_message_len(msg, target_len);
502
503        if (max == 0 || len <= max) {
504                return TRUE;
505        }
506
507        twitter_log(ic, "Maximum message length exceeded: %d > %d", len, max);
508
509        return FALSE;
510}
511
512static char *set_eval_commands(set_t * set, char *value)
513{
514        if (g_strcasecmp(value, "strict") == 0) {
515                return value;
516        } else {
517                return set_eval_bool(set, value);
518        }
519}
520
521static char *set_eval_mode(set_t * set, char *value)
522{
523        if (g_strcasecmp(value, "one") == 0 ||
524            g_strcasecmp(value, "many") == 0 || g_strcasecmp(value, "chat") == 0) {
525                return value;
526        } else {
527                return NULL;
528        }
529}
530
531static void twitter_init(account_t * acc)
532{
533        set_t *s;
534        char *def_url;
535        char *def_tul;
536        char *def_mentions;
537
538        if (strcmp(acc->prpl->name, "twitter") == 0) {
539                def_url = TWITTER_API_URL;
540                def_tul = "23";
541                def_mentions = "true";
542        } else {                /* if( strcmp( acc->prpl->name, "identica" ) == 0 ) */
543                def_url = IDENTICA_API_URL;
544                def_tul = "0";
545                def_mentions = "false";
546        }
547
548        s = set_add(&acc->set, "auto_reply_timeout", "10800", set_eval_int, acc);
549
550        s = set_add(&acc->set, "base_url", def_url, NULL, acc);
551        s->flags |= ACC_SET_OFFLINE_ONLY;
552
553        s = set_add(&acc->set, "commands", "true", set_eval_commands, acc);
554
555        s = set_add(&acc->set, "fetch_interval", "60", set_eval_int, acc);
556        s->flags |= ACC_SET_OFFLINE_ONLY;
557
558        s = set_add(&acc->set, "fetch_mentions", def_mentions, set_eval_bool, acc);
559
560        s = set_add(&acc->set, "message_length", "140", set_eval_int, acc);
561
562        s = set_add(&acc->set, "target_url_length", def_tul, set_eval_int, acc);
563
564        s = set_add(&acc->set, "mode", "chat", set_eval_mode, acc);
565        s->flags |= ACC_SET_OFFLINE_ONLY;
566
567        s = set_add(&acc->set, "oauth", "true", set_eval_oauth, acc);
568
569        s = set_add(&acc->set, "show_ids", "true", set_eval_bool, acc);
570
571        s = set_add(&acc->set, "show_old_mentions", "0", set_eval_int, acc);
572
573        s = set_add(&acc->set, "strip_newlines", "false", set_eval_bool, acc);
574
575        s = set_add(&acc->set, "_last_tweet", "0", NULL, acc);
576        s->flags |= SET_HIDDEN | SET_NOSAVE;
577
578        s = set_add(&acc->set, "in_korea", "false", set_eval_bool, acc);
579        s->flags |= SET_HIDDEN;
580
581        if (strcmp(acc->prpl->name, "twitter") == 0) {
582                s = set_add(&acc->set, "stream", "true", set_eval_bool, acc);
583                s->flags |= ACC_SET_OFFLINE_ONLY;
584        }
585}
586
587/**
588 * Login method. Since the twitter API works with separate HTTP request we
589 * only save the user and pass to the twitter_data object.
590 */
591static void twitter_login(account_t * acc)
592{
593        struct im_connection *ic = imcb_new(acc);
594        struct twitter_data *td;
595        char name[strlen(acc->user) + 9];
596        url_t url;
597        char *s;
598
599        if (!url_set(&url, set_getstr(&ic->acc->set, "base_url")) ||
600            (url.proto != PROTO_HTTP && url.proto != PROTO_HTTPS)) {
601                imcb_error(ic, "Incorrect API base URL: %s", set_getstr(&ic->acc->set, "base_url"));
602                imc_logout(ic, FALSE);
603                return;
604        }
605
606        if (!strstr(url.host, "twitter.com") &&
607            set_getbool(&ic->acc->set, "stream")) {
608                imcb_error(ic, "Warning: The streaming API is only supported by Twitter, "
609                           "and you seem to be connecting to a different service.");
610        }
611
612        imcb_log(ic, "Connecting");
613
614        twitter_connections = g_slist_append(twitter_connections, ic);
615        td = g_new0(struct twitter_data, 1);
616        ic->proto_data = td;
617        td->user = g_strdup(acc->user);
618
619        td->url_ssl = url.proto == PROTO_HTTPS;
620        td->url_port = url.port;
621        td->url_host = g_strdup(url.host);
622        if (strcmp(url.file, "/") != 0) {
623                td->url_path = g_strdup(url.file);
624        } else {
625                td->url_path = g_strdup("");
626                if (g_str_has_suffix(url.host, "twitter.com")) {
627                        /* May fire for people who turned on HTTPS. */
628                        imcb_error(ic, "Warning: Twitter requires a version number in API calls "
629                                   "now. Try resetting the base_url account setting.");
630                }
631        }
632
633        /* Hacky string mangling: Turn identi.ca into identi.ca and api.twitter.com
634           into twitter, and try to be sensible if we get anything else. */
635        td->prefix = g_strdup(url.host);
636        if (g_str_has_suffix(td->prefix, ".com")) {
637                td->prefix[strlen(url.host) - 4] = '\0';
638        }
639        if ((s = strrchr(td->prefix, '.')) && strlen(s) > 4) {
640                /* If we have at least 3 chars after the last dot, cut off the rest.
641                   (mostly a www/api prefix or sth) */
642                s = g_strdup(s + 1);
643                g_free(td->prefix);
644                td->prefix = s;
645        }
646
647        if (strstr(acc->pass, "oauth_token=")) {
648                td->oauth_info = oauth_from_string(acc->pass, get_oauth_service(ic));
649        }
650
651        sprintf(name, "%s_%s", td->prefix, acc->user);
652        imcb_add_buddy(ic, name, NULL);
653        imcb_buddy_status(ic, name, OPT_LOGGED_IN, NULL, NULL);
654
655        td->log = g_new0(struct twitter_log_data, TWITTER_LOG_LENGTH);
656        td->log_id = -1;
657
658        s = set_getstr(&ic->acc->set, "mode");
659        if (g_strcasecmp(s, "one") == 0) {
660                td->flags |= TWITTER_MODE_ONE;
661        } else if (g_strcasecmp(s, "many") == 0) {
662                td->flags |= TWITTER_MODE_MANY;
663        } else {
664                td->flags |= TWITTER_MODE_CHAT;
665        }
666
667        twitter_login_finish(ic);
668}
669
670/**
671 * Logout method. Just free the twitter_data.
672 */
673static void twitter_logout(struct im_connection *ic)
674{
675        struct twitter_data *td = ic->proto_data;
676
677        // Set the status to logged out.
678        ic->flags &= ~OPT_LOGGED_IN;
679
680        if (td) {
681                // Remove the main_loop function from the function queue.
682                b_event_remove(td->main_loop_id);
683
684                if (td->timeline_gc) {
685                        imcb_chat_free(td->timeline_gc);
686                }
687
688                if (td->filter_update_id > 0) {
689                        b_event_remove(td->filter_update_id);
690                }
691
692                g_slist_foreach(td->mutes_ids, (GFunc) g_free, NULL);
693                g_slist_free(td->mutes_ids);
694
695                g_slist_foreach(td->noretweets_ids, (GFunc) g_free, NULL);
696                g_slist_free(td->noretweets_ids);
697
698                http_close(td->stream);
699                twitter_filter_remove_all(ic);
700                oauth_info_free(td->oauth_info);
701                g_free(td->user);
702                g_free(td->prefix);
703                g_free(td->url_host);
704                g_free(td->url_path);
705                g_free(td->log);
706                g_free(td);
707        }
708
709        twitter_connections = g_slist_remove(twitter_connections, ic);
710}
711
712static void twitter_handle_command(struct im_connection *ic, char *message);
713
714/**
715 *
716 */
717static int twitter_buddy_msg(struct im_connection *ic, char *who, char *message, int away)
718{
719        struct twitter_data *td = ic->proto_data;
720        int plen = strlen(td->prefix);
721
722        if (g_strncasecmp(who, td->prefix, plen) == 0 && who[plen] == '_' &&
723            g_strcasecmp(who + plen + 1, ic->acc->user) == 0) {
724                if (set_getbool(&ic->acc->set, "oauth") &&
725                    td->oauth_info && td->oauth_info->token == NULL) {
726                        char pin[strlen(message) + 1], *s;
727
728                        strcpy(pin, message);
729                        for (s = pin + sizeof(pin) - 2; s > pin && g_ascii_isspace(*s); s--) {
730                                *s = '\0';
731                        }
732                        for (s = pin; *s && g_ascii_isspace(*s); s++) {
733                        }
734
735                        if (!oauth_access_token(s, td->oauth_info)) {
736                                imcb_error(ic, "OAuth error: %s",
737                                           "Failed to send access token request");
738                                imc_logout(ic, TRUE);
739                                return FALSE;
740                        }
741                } else {
742                        twitter_handle_command(ic, message);
743                }
744        } else {
745                twitter_direct_messages_new(ic, who, message);
746        }
747        return (0);
748}
749
750static void twitter_get_info(struct im_connection *ic, char *who)
751{
752}
753
754static void twitter_add_buddy(struct im_connection *ic, char *who, char *group)
755{
756        twitter_friendships_create_destroy(ic, who, 1);
757}
758
759static void twitter_remove_buddy(struct im_connection *ic, char *who, char *group)
760{
761        twitter_friendships_create_destroy(ic, who, 0);
762}
763
764static void twitter_chat_msg(struct groupchat *c, char *message, int flags)
765{
766        if (c && message) {
767                twitter_handle_command(c->ic, message);
768        }
769}
770
771static void twitter_chat_invite(struct groupchat *c, char *who, char *message)
772{
773}
774
775static struct groupchat *twitter_chat_join(struct im_connection *ic,
776                                           const char *room, const char *nick,
777                                           const char *password, set_t **sets)
778{
779        struct groupchat *c = imcb_chat_new(ic, room);
780        GSList *fs = twitter_filter_parse(c, room);
781        GString *topic = g_string_new("");
782        struct twitter_filter *tf;
783        GSList *l;
784
785        fs = g_slist_sort(fs, (GCompareFunc) twitter_filter_cmp);
786
787        for (l = fs; l; l = g_slist_next(l)) {
788                tf = l->data;
789
790                if (topic->len > 0) {
791                        g_string_append(topic, ", ");
792                }
793
794                if (tf->type == TWITTER_FILTER_TYPE_FOLLOW) {
795                        g_string_append_c(topic, '@');
796                }
797
798                g_string_append(topic, tf->text);
799        }
800
801        if (topic->len > 0) {
802                g_string_prepend(topic, "Twitter Filter: ");
803        }
804
805        imcb_chat_topic(c, NULL, topic->str, 0);
806        imcb_chat_add_buddy(c, ic->acc->user);
807
808        if (topic->len == 0) {
809                imcb_error(ic, "Failed to handle any filters");
810                imcb_chat_free(c);
811                c = NULL;
812        }
813
814        g_string_free(topic, TRUE);
815        g_slist_free(fs);
816
817        return c;
818}
819
820static void twitter_chat_leave(struct groupchat *c)
821{
822        struct twitter_data *td = c->ic->proto_data;
823
824        if (c != td->timeline_gc) {
825                twitter_filter_remove(c);
826                imcb_chat_free(c);
827                return;
828        }
829
830        /* If the user leaves the channel: Fine. Rejoin him/her once new
831           tweets come in. */
832        imcb_chat_free(td->timeline_gc);
833        td->timeline_gc = NULL;
834}
835
836static void twitter_keepalive(struct im_connection *ic)
837{
838}
839
840static void twitter_add_permit(struct im_connection *ic, char *who)
841{
842}
843
844static void twitter_rem_permit(struct im_connection *ic, char *who)
845{
846}
847
848static void twitter_add_deny(struct im_connection *ic, char *who)
849{
850}
851
852static void twitter_rem_deny(struct im_connection *ic, char *who)
853{
854}
855
856//static char *twitter_set_display_name( set_t *set, char *value )
857//{
858//      return value;
859//}
860
861static void twitter_buddy_data_add(struct bee_user *bu)
862{
863        bu->data = g_new0(struct twitter_user_data, 1);
864}
865
866static void twitter_buddy_data_free(struct bee_user *bu)
867{
868        g_free(bu->data);
869}
870
871bee_user_t twitter_log_local_user;
872
873/** Convert the given bitlbee tweet ID, bitlbee username, or twitter tweet ID
874 *  into a twitter tweet ID.
875 *
876 *  Returns 0 if the user provides garbage.
877 */
878static guint64 twitter_message_id_from_command_arg(struct im_connection *ic, char *arg, bee_user_t **bu_)
879{
880        struct twitter_data *td = ic->proto_data;
881        struct twitter_user_data *tud;
882        bee_user_t *bu = NULL;
883        guint64 id = 0;
884
885        if (bu_) {
886                *bu_ = NULL;
887        }
888        if (!arg || !arg[0]) {
889                return 0;
890        }
891
892        if (arg[0] != '#' && (bu = bee_user_by_handle(ic->bee, ic, arg))) {
893                if ((tud = bu->data)) {
894                        id = tud->last_id;
895                }
896        } else {
897                if (arg[0] == '#') {
898                        arg++;
899                }
900                if (parse_int64(arg, 16, &id) && id < TWITTER_LOG_LENGTH) {
901                        bu = td->log[id].bu;
902                        id = td->log[id].id;
903                } else if (parse_int64(arg, 10, &id)) {
904                        /* Allow normal tweet IDs as well; not a very useful
905                           feature but it's always been there. Just ignore
906                           very low IDs to avoid accidents. */
907                        if (id < 1000000) {
908                                id = 0;
909                        }
910                }
911        }
912        if (bu_) {
913                if (bu == &twitter_log_local_user) {
914                        /* HACK alert. There's no bee_user object for the local
915                         * user so just fake one for the few cmds that need it. */
916                        twitter_log_local_user.handle = td->user;
917                } else {
918                        /* Beware of dangling pointers! */
919                        if (!g_slist_find(ic->bee->users, bu)) {
920                                bu = NULL;
921                        }
922                }
923                *bu_ = bu;
924        }
925        return id;
926}
927
928static void twitter_handle_command(struct im_connection *ic, char *message)
929{
930        struct twitter_data *td = ic->proto_data;
931        char *cmds, **cmd, *new = NULL;
932        guint64 in_reply_to = 0, id;
933        gboolean allow_post =
934                g_strcasecmp(set_getstr(&ic->acc->set, "commands"), "strict") != 0;
935        bee_user_t *bu = NULL;
936
937        cmds = g_strdup(message);
938        cmd = split_command_parts(cmds, 2);
939
940        if (cmd[0] == NULL) {
941                goto eof;
942        } else if (!set_getbool(&ic->acc->set, "commands") && allow_post) {
943                /* Not supporting commands if "commands" is set to true/strict. */
944        } else if (g_strcasecmp(cmd[0], "undo") == 0) {
945                if (cmd[1] == NULL) {
946                        twitter_status_destroy(ic, td->last_status_id);
947                } else if ((id = twitter_message_id_from_command_arg(ic, cmd[1], NULL))) {
948                        twitter_status_destroy(ic, id);
949                } else {
950                        twitter_log(ic, "Could not undo last action");
951                }
952
953                goto eof;
954        } else if ((g_strcasecmp(cmd[0], "favourite") == 0 ||
955                    g_strcasecmp(cmd[0], "favorite") == 0 ||
956                    g_strcasecmp(cmd[0], "fav") == 0 ||
957                    g_strcasecmp(cmd[0], "like") == 0) && cmd[1]) {
958                if ((id = twitter_message_id_from_command_arg(ic, cmd[1], NULL))) {
959                        twitter_favourite_tweet(ic, id);
960                } else {
961                        twitter_log(ic, "Please provide a message ID or username.");
962                }
963                goto eof;
964        } else if (g_strcasecmp(cmd[0], "follow") == 0 && cmd[1]) {
965                twitter_add_buddy(ic, cmd[1], NULL);
966                goto eof;
967        } else if (g_strcasecmp(cmd[0], "unfollow") == 0 && cmd[1]) {
968                twitter_remove_buddy(ic, cmd[1], NULL);
969                goto eof;
970        } else if (g_strcasecmp(cmd[0], "mute") == 0 && cmd[1]) {
971                twitter_mute_create_destroy(ic, cmd[1], 1);
972                goto eof;
973        } else if (g_strcasecmp(cmd[0], "unmute") == 0 && cmd[1]) {
974                twitter_mute_create_destroy(ic, cmd[1], 0);
975                goto eof;
976        } else if ((g_strcasecmp(cmd[0], "report") == 0 ||
977                    g_strcasecmp(cmd[0], "spam") == 0) && cmd[1]) {
978                char *screen_name;
979
980                /* Report nominally works on users but look up the user who
981                   posted the given ID if the user wants to do it that way */
982                twitter_message_id_from_command_arg(ic, cmd[1], &bu);
983                if (bu) {
984                        screen_name = bu->handle;
985                } else {
986                        screen_name = cmd[1];
987                }
988
989                twitter_report_spam(ic, screen_name);
990                goto eof;
991        } else if (g_strcasecmp(cmd[0], "rt") == 0 && cmd[1]) {
992                id = twitter_message_id_from_command_arg(ic, cmd[1], NULL);
993
994                td->last_status_id = 0;
995                if (id) {
996                        twitter_status_retweet(ic, id);
997                } else {
998                        twitter_log(ic, "User `%s' does not exist or didn't "
999                                    "post any statuses recently", cmd[1]);
1000                }
1001
1002                goto eof;
1003        } else if (g_strcasecmp(cmd[0], "reply") == 0 && cmd[1] && cmd[2]) {
1004                id = twitter_message_id_from_command_arg(ic, cmd[1], &bu);
1005                if (!id || !bu) {
1006                        twitter_log(ic, "User `%s' does not exist or didn't "
1007                                    "post any statuses recently", cmd[1]);
1008                        goto eof;
1009                }
1010                message = new = g_strdup_printf("@%s %s", bu->handle, cmd[2]);
1011                in_reply_to = id;
1012                allow_post = TRUE;
1013        } else if (g_strcasecmp(cmd[0], "rawreply") == 0 && cmd[1] && cmd[2]) {
1014                id = twitter_message_id_from_command_arg(ic, cmd[1], NULL);
1015                if (!id) {
1016                        twitter_log(ic, "Tweet `%s' does not exist", cmd[1]);
1017                        goto eof;
1018                }
1019                message = cmd[2];
1020                in_reply_to = id;
1021                allow_post = TRUE;
1022        } else if (g_strcasecmp(cmd[0], "url") == 0) {
1023                id = twitter_message_id_from_command_arg(ic, cmd[1], &bu);
1024                if (!id) {
1025                        twitter_log(ic, "Tweet `%s' does not exist", cmd[1]);
1026                } else {
1027                        twitter_status_show_url(ic, id);
1028                }
1029                goto eof;
1030
1031        } else if (g_strcasecmp(cmd[0], "post") == 0) {
1032                message += 5;
1033                allow_post = TRUE;
1034        }
1035
1036        if (allow_post) {
1037                char *s;
1038
1039                if (!twitter_length_check(ic, message)) {
1040                        goto eof;
1041                }
1042
1043                s = cmd[0] + strlen(cmd[0]) - 1;
1044                if (!new && s > cmd[0] && (*s == ':' || *s == ',')) {
1045                        *s = '\0';
1046
1047                        if ((bu = bee_user_by_handle(ic->bee, ic, cmd[0]))) {
1048                                struct twitter_user_data *tud = bu->data;
1049
1050                                new = g_strdup_printf("@%s %s", bu->handle,
1051                                                      message + (s - cmd[0]) + 2);
1052                                message = new;
1053
1054                                if (time(NULL) < tud->last_time +
1055                                    set_getint(&ic->acc->set, "auto_reply_timeout")) {
1056                                        in_reply_to = tud->last_id;
1057                                }
1058                        }
1059                }
1060
1061                /* If the user runs undo between this request and its response
1062                   this would delete the second-last Tweet. Prevent that. */
1063                td->last_status_id = 0;
1064                twitter_post_status(ic, message, in_reply_to);
1065        } else {
1066                twitter_log(ic, "Unknown command: %s", cmd[0]);
1067        }
1068eof:
1069        g_free(new);
1070        g_free(cmds);
1071}
1072
1073void twitter_log(struct im_connection *ic, char *format, ...)
1074{
1075        struct twitter_data *td = ic->proto_data;
1076        va_list params;
1077        char *text;
1078
1079        va_start(params, format);
1080        text = g_strdup_vprintf(format, params);
1081        va_end(params);
1082
1083        if (td->timeline_gc) {
1084                imcb_chat_log(td->timeline_gc, "%s", text);
1085        } else {
1086                imcb_log(ic, "%s", text);
1087        }
1088
1089        g_free(text);
1090}
1091
1092
1093void twitter_initmodule()
1094{
1095        struct prpl *ret = g_new0(struct prpl, 1);
1096
1097        ret->options = PRPL_OPT_NOOTR | PRPL_OPT_NO_PASSWORD;
1098        ret->name = "twitter";
1099        ret->login = twitter_login;
1100        ret->init = twitter_init;
1101        ret->logout = twitter_logout;
1102        ret->buddy_msg = twitter_buddy_msg;
1103        ret->get_info = twitter_get_info;
1104        ret->add_buddy = twitter_add_buddy;
1105        ret->remove_buddy = twitter_remove_buddy;
1106        ret->chat_msg = twitter_chat_msg;
1107        ret->chat_invite = twitter_chat_invite;
1108        ret->chat_join = twitter_chat_join;
1109        ret->chat_leave = twitter_chat_leave;
1110        ret->keepalive = twitter_keepalive;
1111        ret->add_permit = twitter_add_permit;
1112        ret->rem_permit = twitter_rem_permit;
1113        ret->add_deny = twitter_add_deny;
1114        ret->rem_deny = twitter_rem_deny;
1115        ret->buddy_data_add = twitter_buddy_data_add;
1116        ret->buddy_data_free = twitter_buddy_data_free;
1117        ret->handle_cmp = g_strcasecmp;
1118
1119        register_protocol(ret);
1120
1121        /* And an identi.ca variant: */
1122        ret = g_memdup(ret, sizeof(struct prpl));
1123        ret->name = "identica";
1124        ret->options =  PRPL_OPT_NOOTR;
1125        register_protocol(ret);
1126}
Note: See TracBrowser for help on using the repository browser.