source: protocols/twitter/twitter.c @ ce617f0

Last change on this file since ce617f0 was ce617f0, checked in by Wilmer van der Gaast <wilmer@…>, at 2011-03-27T14:09:55Z

Tweaks to allow authenticating to identi.ca with OAuth. Doesn't seem to work
completely for whatever the reason may be (invalid signature). I give up for
now. Stuff does actually work if you generate access tokens using different
software so BitlBee's definitely able to generate good signatures.

  • Property mode set to 100644
File size: 15.7 KB
Line 
1/***************************************************************************\
2*                                                                           *
3*  BitlBee - An IRC to IM gateway                                           *
4*  Simple module to facilitate twitter functionality.                       *
5*                                                                           *
6*  Copyright 2009 Geert Mulders <g.c.w.m.mulders@gmail.com>                 *
7*                                                                           *
8*  This library is free software; you can redistribute it and/or            *
9*  modify it under the terms of the GNU Lesser General Public               *
10*  License as published by the Free Software Foundation, version            *
11*  2.1.                                                                     *
12*                                                                           *
13*  This library is distributed in the hope that it will be useful,          *
14*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
15*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
16*  Lesser General Public License for more details.                          *
17*                                                                           *
18*  You should have received a copy of the GNU Lesser General Public License *
19*  along with this library; if not, write to the Free Software Foundation,  *
20*  Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA           *
21*                                                                           *
22****************************************************************************/
23
24#include "nogaim.h"
25#include "oauth.h"
26#include "twitter.h"
27#include "twitter_http.h"
28#include "twitter_lib.h"
29#include "url.h"
30
31#define twitter_msg( ic, fmt... ) \
32        do {                                                        \
33                struct twitter_data *td = ic->proto_data;           \
34                if( td->home_timeline_gc )                          \
35                        imcb_chat_log( td->home_timeline_gc, fmt ); \
36                else                                                \
37                        imcb_log( ic, fmt );                        \
38        } while( 0 );
39               
40GSList *twitter_connections = NULL;
41
42/**
43 * Main loop function
44 */
45gboolean twitter_main_loop(gpointer data, gint fd, b_input_condition cond)
46{
47        struct im_connection *ic = data;
48       
49        // Check if we are still logged in...
50        if (!g_slist_find( twitter_connections, ic ))
51                return 0;
52
53        // Do stuff..
54        twitter_get_home_timeline(ic, -1);
55
56        // If we are still logged in run this function again after timeout.
57        return (ic->flags & OPT_LOGGED_IN) == OPT_LOGGED_IN;
58}
59
60static void twitter_main_loop_start( struct im_connection *ic )
61{
62        struct twitter_data *td = ic->proto_data;
63       
64        imcb_log( ic, "Getting initial statuses" );
65
66        // Run this once. After this queue the main loop function.
67        twitter_main_loop(ic, -1, 0);
68
69        // Queue the main_loop
70        // Save the return value, so we can remove the timeout on logout.
71        td->main_loop_id = b_timeout_add(60000, twitter_main_loop, ic);
72}
73
74static void twitter_oauth_start( struct im_connection *ic );
75
76void twitter_login_finish( struct im_connection *ic )
77{
78        struct twitter_data *td = ic->proto_data;
79       
80        if( set_getbool( &ic->acc->set, "oauth" ) && !td->oauth_info )
81                twitter_oauth_start( ic );
82        else if( g_strcasecmp( set_getstr( &ic->acc->set, "mode" ), "one" ) != 0 &&
83                 !( td->flags & TWITTER_HAVE_FRIENDS ) )
84        {
85                imcb_log( ic, "Getting contact list" );
86                twitter_get_statuses_friends( ic, -1 );
87        }
88        else
89                twitter_main_loop_start( ic );
90}
91
92static const struct oauth_service twitter_oauth =
93{
94        "http://api.twitter.com/oauth/request_token",
95        "http://api.twitter.com/oauth/access_token",
96        "https://api.twitter.com/oauth/authorize",
97        .consumer_key = "xsDNKJuNZYkZyMcu914uEA",
98        .consumer_secret = "FCxqcr0pXKzsF9ajmP57S3VQ8V6Drk4o2QYtqMcOszo",
99};
100
101static const struct oauth_service identica_oauth =
102{
103        "http://identi.ca/api/oauth/request_token",
104        "http://identi.ca/api/oauth/access_token",
105        "https://identi.ca/api/oauth/authorize",
106        .consumer_key = "e147ff789fcbd8a5a07963afbb43f9da",
107        .consumer_secret = "c596267f277457ec0ce1ab7bb788d828",
108};
109
110static gboolean twitter_oauth_callback( struct oauth_info *info );
111
112static const struct oauth_service *get_oauth_service( struct im_connection *ic )
113{
114        struct twitter_data *td = ic->proto_data;
115       
116        if( strstr( td->url_host, "identi.ca" ) )
117                return &identica_oauth;
118        else
119                return &twitter_oauth;
120       
121        /* Could add more services, or allow configuring your own base URL +
122           API keys. */
123}
124
125static void twitter_oauth_start( struct im_connection *ic )
126{
127        struct twitter_data *td = ic->proto_data;
128       
129        imcb_log( ic, "Requesting OAuth request token" );
130
131        td->oauth_info = oauth_request_token( get_oauth_service( ic ), twitter_oauth_callback, ic );
132       
133        /* We need help from the user to complete OAuth login, so don't time
134           out on this login. */
135        ic->flags |= OPT_SLOW_LOGIN;
136}
137
138static gboolean twitter_oauth_callback( struct oauth_info *info )
139{
140        struct im_connection *ic = info->data;
141        struct twitter_data *td;
142       
143        if( !g_slist_find( twitter_connections, ic ) )
144                return FALSE;
145       
146        td = ic->proto_data;
147        if( info->stage == OAUTH_REQUEST_TOKEN )
148        {
149                char name[strlen(ic->acc->user)+9], *msg;
150               
151                if( info->request_token == NULL )
152                {
153                        imcb_error( ic, "OAuth error: %s", info->http->status_string );
154                        imc_logout( ic, TRUE );
155                        return FALSE;
156                }
157               
158                sprintf( name, "%s_%s", td->prefix, ic->acc->user );
159                msg = g_strdup_printf( "To finish OAuth authentication, please visit "
160                                       "%s and respond with the resulting PIN code.",
161                                       info->auth_url );
162                imcb_buddy_msg( ic, name, msg, 0, 0 );
163                g_free( msg );
164        }
165        else if( info->stage == OAUTH_ACCESS_TOKEN )
166        {
167                if( info->token == NULL || info->token_secret == NULL )
168                {
169                        imcb_error( ic, "OAuth error: %s", info->http->status_string );
170                        imc_logout( ic, TRUE );
171                        return FALSE;
172                }
173                else
174                {
175                        const char *sn = oauth_params_get( &info->params, "screen_name" );
176                       
177                        if( sn != NULL && ic->acc->prpl->handle_cmp( sn, ic->acc->user ) != 0 )
178                        {
179                                imcb_log( ic, "Warning: You logged in via OAuth as %s "
180                                          "instead of %s.", sn, ic->acc->user );
181                        }
182                }
183               
184                /* IM mods didn't do this so far and it's ugly but I should
185                   be able to get away with it... */
186                g_free( ic->acc->pass );
187                ic->acc->pass = oauth_to_string( info );
188               
189                twitter_login_finish( ic );
190        }
191       
192        return TRUE;
193}
194
195
196static char *set_eval_mode( set_t *set, char *value )
197{
198        if( g_strcasecmp( value, "one" ) == 0 ||
199            g_strcasecmp( value, "many" ) == 0 ||
200            g_strcasecmp( value, "chat" ) == 0 )
201                return value;
202        else
203                return NULL;
204}
205
206static gboolean twitter_length_check( struct im_connection *ic, gchar *msg )
207{
208        int max = set_getint( &ic->acc->set, "message_length" ), len;
209       
210        if( max == 0 || ( len = g_utf8_strlen( msg, -1 ) ) <= max )
211                return TRUE;
212       
213        imcb_error( ic, "Maximum message length exceeded: %d > %d", len, max );
214       
215        return FALSE;
216}
217
218static void twitter_init( account_t *acc )
219{
220        set_t *s;
221        char *def_url;
222        char *def_oauth;
223       
224        if( strcmp( acc->prpl->name, "twitter" ) == 0 )
225        {
226                def_url = TWITTER_API_URL;
227                def_oauth = "true";
228        }
229        else /* if( strcmp( acc->prpl->name, "identica" ) == 0 ) */
230        {
231                def_url = IDENTICA_API_URL;
232                def_oauth = "false";
233        }
234       
235        s = set_add( &acc->set, "auto_reply_timeout", "10800", set_eval_int, acc );
236       
237        s = set_add( &acc->set, "base_url", def_url, NULL, acc );
238        s->flags |= ACC_SET_OFFLINE_ONLY;
239       
240        s = set_add( &acc->set, "commands", "true", set_eval_bool, acc );
241       
242        s = set_add( &acc->set, "message_length", "140", set_eval_int, acc );
243       
244        s = set_add( &acc->set, "mode", "chat", set_eval_mode, acc );
245        s->flags |= ACC_SET_OFFLINE_ONLY;
246       
247        s = set_add( &acc->set, "oauth", def_oauth, set_eval_bool, acc );
248}
249
250/**
251 * Login method. Since the twitter API works with seperate HTTP request we
252 * only save the user and pass to the twitter_data object.
253 */
254static void twitter_login( account_t *acc )
255{
256        struct im_connection *ic = imcb_new( acc );
257        struct twitter_data *td;
258        char name[strlen(acc->user)+9];
259        url_t url;
260
261        if( !url_set( &url, set_getstr( &ic->acc->set, "base_url" ) ) ||
262            ( url.proto != PROTO_HTTP && url.proto != PROTO_HTTPS ) )
263        {
264                imcb_error( ic, "Incorrect API base URL: %s", set_getstr( &ic->acc->set, "base_url" ) );
265                imc_logout( ic, FALSE );
266                return;
267        }
268       
269        twitter_connections = g_slist_append( twitter_connections, ic );
270        td = g_new0( struct twitter_data, 1 );
271        ic->proto_data = td;
272       
273        td->url_ssl = url.proto == PROTO_HTTPS;
274        td->url_port = url.port;
275        td->url_host = g_strdup( url.host );
276        if( strcmp( url.file, "/" ) != 0 )
277                td->url_path = g_strdup( url.file );
278        else
279                td->url_path = g_strdup( "" );
280        if( g_str_has_suffix( url.host, ".com" ) )
281                td->prefix = g_strndup( url.host, strlen( url.host ) - 4 );
282        else
283                td->prefix = g_strdup( url.host );
284       
285        td->user = acc->user;
286        if( strstr( acc->pass, "oauth_token=" ) )
287                td->oauth_info = oauth_from_string( acc->pass, get_oauth_service( ic ) );
288       
289        sprintf( name, "%s_%s", td->prefix, acc->user );
290        imcb_add_buddy( ic, name, NULL );
291        imcb_buddy_status( ic, name, OPT_LOGGED_IN, NULL, NULL );
292       
293        imcb_log( ic, "Connecting" );
294       
295        twitter_login_finish( ic );
296}
297
298/**
299 * Logout method. Just free the twitter_data.
300 */
301static void twitter_logout( struct im_connection *ic )
302{
303        struct twitter_data *td = ic->proto_data;
304       
305        // Set the status to logged out.
306        ic->flags &= ~ OPT_LOGGED_IN;
307
308        // Remove the main_loop function from the function queue.
309        b_event_remove(td->main_loop_id);
310
311        if(td->home_timeline_gc)
312                imcb_chat_free(td->home_timeline_gc);
313
314        if( td )
315        {
316                oauth_info_free( td->oauth_info );
317                g_free( td->prefix );
318                g_free( td->url_host );
319                g_free( td->url_path );
320                g_free( td->pass );
321                g_free( td );
322        }
323
324        twitter_connections = g_slist_remove( twitter_connections, ic );
325}
326
327static void twitter_handle_command( struct im_connection *ic, char *message );
328
329/**
330 *
331 */
332static int twitter_buddy_msg( struct im_connection *ic, char *who, char *message, int away )
333{
334        struct twitter_data *td = ic->proto_data;
335        int plen = strlen( td->prefix );
336       
337        if (g_strncasecmp(who, td->prefix, plen) == 0 && who[plen] == '_' &&
338            g_strcasecmp(who + plen + 1, ic->acc->user) == 0)
339        {
340                if( set_getbool( &ic->acc->set, "oauth" ) &&
341                    td->oauth_info && td->oauth_info->token == NULL )
342                {
343                        char pin[strlen(message)+1], *s;
344                       
345                        strcpy( pin, message );
346                        for( s = pin + sizeof( pin ) - 2; s > pin && isspace( *s ); s -- )
347                                *s = '\0';
348                        for( s = pin; *s && isspace( *s ); s ++ ) {}
349                       
350                        if( !oauth_access_token( s, td->oauth_info ) )
351                        {
352                                imcb_error( ic, "OAuth error: %s", "Failed to send access token request" );
353                                imc_logout( ic, TRUE );
354                                return FALSE;
355                        }
356                }
357                else
358                        twitter_handle_command(ic, message);
359        }
360        else
361        {
362                twitter_direct_messages_new(ic, who, message);
363        }
364        return( 0 );
365}
366
367/**
368 *
369 */
370static void twitter_set_my_name( struct im_connection *ic, char *info )
371{
372}
373
374static void twitter_get_info(struct im_connection *ic, char *who) 
375{
376}
377
378static void twitter_add_buddy( struct im_connection *ic, char *who, char *group )
379{
380        twitter_friendships_create_destroy(ic, who, 1);
381}
382
383static void twitter_remove_buddy( struct im_connection *ic, char *who, char *group )
384{
385        twitter_friendships_create_destroy(ic, who, 0);
386}
387
388static void twitter_chat_msg( struct groupchat *c, char *message, int flags )
389{
390        if( c && message )
391                twitter_handle_command( c->ic, message );
392}
393
394static void twitter_chat_invite( struct groupchat *c, char *who, char *message )
395{
396}
397
398static void twitter_chat_leave( struct groupchat *c )
399{
400        struct twitter_data *td = c->ic->proto_data;
401       
402        if( c != td->home_timeline_gc )
403                return; /* WTF? */
404       
405        /* If the user leaves the channel: Fine. Rejoin him/her once new
406           tweets come in. */
407        imcb_chat_free(td->home_timeline_gc);
408        td->home_timeline_gc = NULL;
409}
410
411static void twitter_keepalive( struct im_connection *ic )
412{
413}
414
415static void twitter_add_permit( struct im_connection *ic, char *who )
416{
417}
418
419static void twitter_rem_permit( struct im_connection *ic, char *who )
420{
421}
422
423static void twitter_add_deny( struct im_connection *ic, char *who )
424{
425}
426
427static void twitter_rem_deny( struct im_connection *ic, char *who )
428{
429}
430
431//static char *twitter_set_display_name( set_t *set, char *value )
432//{
433//      return value;
434//}
435
436static void twitter_buddy_data_add( struct bee_user *bu )
437{
438        bu->data = g_new0( struct twitter_user_data, 1 );
439}
440
441static void twitter_buddy_data_free( struct bee_user *bu )
442{
443        g_free( bu->data );
444}
445
446static void twitter_handle_command( struct im_connection *ic, char *message )
447{
448        struct twitter_data *td = ic->proto_data;
449        char *cmds, **cmd;
450       
451        cmds = g_strdup( message );
452        cmd = split_command_parts( cmds );
453       
454        if( cmd[0] == NULL )
455        {
456                g_free( cmds );
457                return;
458        }
459        else if( !set_getbool( &ic->acc->set, "commands" ) )
460        {
461                /* Not supporting commands. */
462        }
463        else if( g_strcasecmp( cmd[0], "undo" ) == 0 )
464        {
465                guint64 id;
466               
467                if( cmd[1] )
468                        id = g_ascii_strtoull( cmd[1], NULL, 10 );
469                else
470                        id = td->last_status_id;
471               
472                /* TODO: User feedback. */
473                if( id )
474                        twitter_status_destroy( ic, id );
475                else
476                        twitter_msg( ic, "Could not undo last action" );
477               
478                g_free( cmds );
479                return;
480        }
481        else if( g_strcasecmp( cmd[0], "follow" ) == 0 && cmd[1] )
482        {
483                twitter_add_buddy( ic, cmd[1], NULL );
484                g_free( cmds );
485                return;
486        }
487        else if( g_strcasecmp( cmd[0], "unfollow" ) == 0 && cmd[1] )
488        {
489                twitter_remove_buddy( ic, cmd[1], NULL );
490                g_free( cmds );
491                return;
492        }
493        else if( g_strcasecmp( cmd[0], "rt" ) == 0 && cmd[1] )
494        {
495                struct twitter_user_data *tud;
496                bee_user_t *bu;
497                guint64 id;
498               
499                if( ( bu = bee_user_by_handle( ic->bee, ic, cmd[1] ) ) &&
500                    ( tud = bu->data ) && tud->last_id )
501                        id = tud->last_id;
502                else
503                        id = g_ascii_strtoull( cmd[1], NULL, 10 );
504               
505                td->last_status_id = 0;
506                if( id )
507                        twitter_status_retweet( ic, id );
508                else
509                        twitter_msg( ic, "User `%s' does not exist or didn't "
510                                         "post any statuses recently", cmd[1] );
511               
512                g_free( cmds );
513                return;
514        }
515        else if( g_strcasecmp( cmd[0], "post" ) == 0 )
516        {
517                message += 5;
518        }
519       
520        {
521                guint64 in_reply_to = 0;
522                char *s, *new = NULL;
523                bee_user_t *bu;
524               
525                if( !twitter_length_check( ic, message ) )
526                {
527                        g_free( cmds );
528                        return;
529                }
530               
531                s = cmd[0] + strlen( cmd[0] ) - 1;
532                if( s > cmd[0] && ( *s == ':' || *s == ',' ) )
533                {
534                        *s = '\0';
535                       
536                        if( ( bu = bee_user_by_handle( ic->bee, ic, cmd[0] ) ) )
537                        {
538                                struct twitter_user_data *tud = bu->data;
539                               
540                                new = g_strdup_printf( "@%s %s", bu->handle,
541                                                       message + ( s - cmd[0] ) + 2 );
542                                message = new;
543                               
544                                if( time( NULL ) < tud->last_time +
545                                    set_getint( &ic->acc->set, "auto_reply_timeout" ) )
546                                        in_reply_to = tud->last_id;
547                        }
548                }
549               
550                /* If the user runs undo between this request and its response
551                   this would delete the second-last Tweet. Prevent that. */
552                td->last_status_id = 0;
553                twitter_post_status( ic, message, in_reply_to );
554                g_free( new );
555        }
556        g_free( cmds );
557}
558
559void twitter_initmodule()
560{
561        struct prpl *ret = g_new0(struct prpl, 1);
562       
563        ret->options = OPT_NOOTR;
564        ret->name = "twitter";
565        ret->login = twitter_login;
566        ret->init = twitter_init;
567        ret->logout = twitter_logout;
568        ret->buddy_msg = twitter_buddy_msg;
569        ret->get_info = twitter_get_info;
570        ret->set_my_name = twitter_set_my_name;
571        ret->add_buddy = twitter_add_buddy;
572        ret->remove_buddy = twitter_remove_buddy;
573        ret->chat_msg = twitter_chat_msg;
574        ret->chat_invite = twitter_chat_invite;
575        ret->chat_leave = twitter_chat_leave;
576        ret->keepalive = twitter_keepalive;
577        ret->add_permit = twitter_add_permit;
578        ret->rem_permit = twitter_rem_permit;
579        ret->add_deny = twitter_add_deny;
580        ret->rem_deny = twitter_rem_deny;
581        ret->buddy_data_add = twitter_buddy_data_add;
582        ret->buddy_data_free = twitter_buddy_data_free;
583        ret->handle_cmp = g_strcasecmp;
584       
585        register_protocol(ret);
586
587        /* And an identi.ca variant: */
588        ret = g_memdup(ret, sizeof(struct prpl));
589        ret->name = "identica";
590        register_protocol(ret);
591}
Note: See TracBrowser for help on using the repository browser.