Make sure N:T has the ua method before calling it
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use HTTP::Date;
5 use HTML::Entities;
6 use File::Temp;
7 use LWP::Simple;
8 use Data::Dumper;
9 use Encode;
10 $Data::Dumper::Indent = 1;
11
12 use vars qw($VERSION %IRSSI);
13
14 $VERSION = "2.2.5beta";
15 my ($REV) = '$Rev: 687 $' =~ /(\d+)/;
16 %IRSSI = (
17     authors     => 'Dan Boger',
18     contact     => 'zigdon@gmail.com',
19     name        => 'twirssi',
20     description => 'Send twitter updates using /tweet.  '
21       . 'Can optionally set your bitlbee /away message to same',
22     license => 'GNU GPL v2',
23     url     => 'http://twirssi.com',
24     changed => '$Date: 2009-08-07 01:24:53 -0700 (Fri, 07 Aug 2009) $',
25 );
26
27 my $window;
28 my $twit;
29 my %twits;
30 my $user;
31 my $defservice;
32 my $poll;
33 my $last_poll;
34 my $last_friends_poll = 0;
35 my %nicks;
36 my %friends;
37 my %tweet_cache;
38 my %id_map;
39 my $failwhale  = 0;
40 my $first_call = 1;
41
42 my %irssi_to_mirc_colors = (
43     '%k' => '01',
44     '%r' => '05',
45     '%g' => '03',
46     '%y' => '07',
47     '%b' => '02',
48     '%m' => '06',
49     '%c' => '10',
50     '%w' => '15',
51     '%K' => '14',
52     '%R' => '04',
53     '%G' => '09',
54     '%Y' => '08',
55     '%B' => '12',
56     '%M' => '13',
57     '%C' => '11',
58     '%W' => '00',
59 );
60
61 sub cmd_direct {
62     my ( $data, $server, $win ) = @_;
63
64     return unless &logged_in($twit);
65
66     my ( $target, $text ) = split ' ', $data, 2;
67     unless ( $target and $text ) {
68         &notice("Usage: /dm <nick> <message>");
69         return;
70     }
71
72     &cmd_direct_as( "$user $data", $server, $win );
73 }
74
75 sub cmd_direct_as {
76     my ( $data, $server, $win ) = @_;
77
78     return unless &logged_in($twit);
79
80     my ( $username, $target, $text ) = split ' ', $data, 3;
81     unless ( $username and $target and $text ) {
82         &notice("Usage: /dm_as <username> <nick> <message>");
83         return;
84     }
85
86     return unless $username = &valid_username($username);
87
88     eval {
89         if ( $twits{$username}
90             ->new_direct_message( { user => $target, text => $text } ) )
91         {
92             &notice("DM sent to $target");
93             $nicks{$target} = time;
94         } else {
95             my $error;
96             eval {
97                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
98                 $error = $error->{error};
99             };
100             die $error if $error;
101             &notice("DM to $target failed");
102         }
103     };
104
105     if ($@) {
106         &notice("DM caused an error: $@");
107         return;
108     }
109 }
110
111 sub cmd_retweet {
112     my ( $data, $server, $win ) = @_;
113
114     return unless &logged_in($twit);
115
116     $data =~ s/^\s+|\s+$//;
117     unless ($data) {
118         &notice("Usage: /retweet <nick[:num]> [comment]");
119         return;
120     }
121
122     my ( $id, $data ) = split ' ', $data, 2;
123
124     &cmd_retweet_as( "$user $id $data", $server, $win );
125 }
126
127 sub cmd_retweet_as {
128     my ( $data, $server, $win ) = @_;
129
130     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
131         &notice("twirssi_track_replies is required in order to reteet.");
132         return;
133     }
134
135     return unless &logged_in($twit);
136
137     $data =~ s/^\s+|\s+$//;
138     my ( $username, $id, $data ) = split ' ', $data, 3;
139
140     unless ($username) {
141         &notice("Usage: /retweet_as <username> <nick[:num]> [comment]");
142         return;
143     }
144
145     return unless $username = &valid_username($username);
146
147     my $nick;
148     $id =~ s/[^\w\d\-:]+//g;
149     ( $nick, $id ) = split /:/, $id;
150     unless ( exists $id_map{ lc $nick } ) {
151         &notice("Can't find a tweet from $nick to retweet!");
152         return;
153     }
154
155     $id = $id_map{__indexes}{$nick} unless $id;
156     unless ( $id_map{ lc $nick }[$id] ) {
157         &notice("Can't find a tweet numbered $id from $nick to retweet!");
158         return;
159     }
160
161     unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
162         &notice("The text of this tweet isn't saved, sorry!");
163         return;
164     }
165
166 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
167     my $text = Irssi::settings_get_str("twirssi_retweet_format");
168     $text =~ s/\$n/\@$nick/g;
169     if ($data) {
170         $text =~ s/\${|\$}//g;
171         $text =~ s/\$c/$data/;
172     } else {
173         $text =~ s/\${.*?\$}//;
174     }
175     $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
176
177     $data = &shorten($text);
178
179     return if &too_long($data);
180
181     my $success = 1;
182     eval {
183         unless (
184             $twits{$username}->update(
185                 {
186                     status => $data,
187
188                     # in_reply_to_status_id => $id_map{ lc $nick }[$id]
189                 }
190             )
191           )
192         {
193             &notice("Update failed");
194             $success = 0;
195         }
196     };
197     return unless $success;
198
199     if ($@) {
200         &notice("Update caused an error: $@.  Aborted");
201         return;
202     }
203
204     foreach ( $data =~ /@([-\w]+)/ ) {
205         $nicks{$1} = time;
206     }
207
208     &notice("Retweet sent");
209 }
210
211 sub cmd_tweet {
212     my ( $data, $server, $win ) = @_;
213
214     return unless &logged_in($twit);
215
216     $data =~ s/^\s+|\s+$//;
217     unless ($data) {
218         &notice("Usage: /tweet <update>");
219         return;
220     }
221
222     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
223 }
224
225 sub cmd_tweet_as {
226     my ( $data, $server, $win ) = @_;
227
228     return unless &logged_in($twit);
229
230     $data =~ s/^\s+|\s+$//;
231     $data =~ s/\s\s+/ /g;
232     my ( $username, $data ) = split ' ', $data, 2;
233
234     unless ( $username and $data ) {
235         &notice("Usage: /tweet_as <username> <update>");
236         return;
237     }
238
239     return unless $username = &valid_username($username);
240
241     $data = &shorten($data);
242
243     return if &too_long($data);
244
245     my $success = 1;
246     eval {
247         unless ( $twits{$username}->update($data) )
248         {
249             &notice("Update failed");
250             $success = 0;
251         }
252     };
253     return unless $success;
254
255     if ($@) {
256         &notice("Update caused an error: $@.  Aborted.");
257         return;
258     }
259
260     foreach ( $data =~ /@([-\w]+)/ ) {
261         $nicks{$1} = time;
262     }
263
264     my $away = &update_away($data);
265
266     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
267 }
268
269 sub cmd_reply {
270     my ( $data, $server, $win ) = @_;
271
272     return unless &logged_in($twit);
273
274     $data =~ s/^\s+|\s+$//;
275     unless ($data) {
276         &notice("Usage: /reply <nick[:num]> <update>");
277         return;
278     }
279
280     my ( $id, $data ) = split ' ', $data, 2;
281     unless ( $id and $data ) {
282         &notice("Usage: /reply <nick[:num]> <update>");
283         return;
284     }
285
286     &cmd_reply_as( "$user $id $data", $server, $win );
287 }
288
289 sub cmd_reply_as {
290     my ( $data, $server, $win ) = @_;
291
292     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
293         &notice("twirssi_track_replies is required in order to reply to "
294               . "specific tweets.  Either enable it, or just use /tweet "
295               . "\@username <text>." );
296         return;
297     }
298
299     return unless &logged_in($twit);
300
301     $data =~ s/^\s+|\s+$//;
302     my ( $username, $id, $data ) = split ' ', $data, 3;
303
304     unless ( $username and $data ) {
305         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
306         return;
307     }
308
309     return unless $username = &valid_username($username);
310
311     my $nick;
312     $id =~ s/[^\w\d\-:]+//g;
313     ( $nick, $id ) = split /:/, $id;
314     unless ( exists $id_map{ lc $nick } ) {
315         &notice("Can't find a tweet from $nick to reply to!");
316         return;
317     }
318
319     $id = $id_map{__indexes}{$nick} unless $id;
320     unless ( $id_map{ lc $nick }[$id] ) {
321         &notice("Can't find a tweet numbered $id from $nick to reply to!");
322         return;
323     }
324
325     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
326
327         # remove any @nick at the beginning of the reply, as we'll add it anyway
328         $data =~ s/^\s*\@?$nick\s*//;
329         $data = "\@$nick " . $data;
330     }
331
332     $data = &shorten($data);
333
334     return if &too_long($data);
335
336     my $success = 1;
337     eval {
338         unless (
339             $twits{$username}->update(
340                 {
341                     status                => $data,
342                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
343                 }
344             )
345           )
346         {
347             &notice("Update failed");
348             $success = 0;
349         }
350     };
351     return unless $success;
352
353     if ($@) {
354         &notice("Update caused an error: $@.  Aborted");
355         return;
356     }
357
358     foreach ( $data =~ /@([-\w]+)/ ) {
359         $nicks{$1} = time;
360     }
361
362     my $away = &update_away($data);
363
364     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
365 }
366
367 sub gen_cmd {
368     my ( $usage_str, $api_name, $post_ref ) = @_;
369
370     return sub {
371         my ( $data, $server, $win ) = @_;
372
373         return unless &logged_in($twit);
374
375         $data =~ s/^\s+|\s+$//;
376         unless ($data) {
377             &notice("Usage: $usage_str");
378             return;
379         }
380
381         my $success = 1;
382         eval {
383             unless ( $twit->$api_name($data) )
384             {
385                 &notice("$api_name failed");
386                 $success = 0;
387             }
388         };
389         return unless $success;
390
391         if ($@) {
392             &notice("$api_name caused an error.  Aborted.");
393             return;
394         }
395
396         &$post_ref($data) if $post_ref;
397       }
398 }
399
400 sub cmd_switch {
401     my ( $data, $server, $win ) = @_;
402
403     $data =~ s/^\s+|\s+$//g;
404     $data = &normalize_username($data);
405     if ( exists $twits{$data} ) {
406         &notice("Switching to $data");
407         $twit = $twits{$data};
408         if ( $data =~ /(.*)\@(.*)/ ) {
409             $user       = $1;
410             $defservice = $2;
411         } else {
412             &notice("Couldn't figure out what service '$data' is on");
413         }
414     } else {
415         &notice("Unknown user $data");
416     }
417 }
418
419 sub cmd_logout {
420     my ( $data, $server, $win ) = @_;
421
422     $data =~ s/^\s+|\s+$//g;
423     $data = $user unless $data;
424     return unless $data = &valid_username($data);
425
426     &notice("Logging out $data...");
427     $twits{$data}->end_session();
428     delete $twits{$data};
429     undef $twit;
430     if ( keys %twits ) {
431         &cmd_switch( ( keys %twits )[0], $server, $win );
432     } else {
433         Irssi::timeout_remove($poll) if $poll;
434         undef $poll;
435     }
436 }
437
438 sub cmd_login {
439     my ( $data, $server, $win ) = @_;
440     my $pass;
441     if ($data) {
442         ( $user, $pass ) = split ' ', $data, 2;
443     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
444         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
445     {
446         my @user = split /\s*,\s*/, $autouser;
447         my @pass = split /\s*,\s*/, $autopass;
448
449         # if a password ends with a '\', it was meant to escape the comma, and
450         # it should be concatinated with the next one
451         my @unescaped;
452         while (@pass) {
453             my $p = shift @pass;
454             while ( $p =~ /\\$/ and @pass ) {
455                 $p .= "," . shift @pass;
456             }
457             push @unescaped, $p;
458         }
459
460         if ( @user != @unescaped ) {
461             &notice("Number of usernames doesn't match "
462                   . "the number of passwords - auto-login failed" );
463         } else {
464             my ( $u, $p );
465             while ( @user and @unescaped ) {
466                 $u = shift @user;
467                 $p = shift @unescaped;
468                 &cmd_login("$u $p");
469             }
470             return;
471         }
472     } else {
473         &notice("/twitter_login requires either a username and password "
474               . "or twitter_usernames and twitter_passwords to be set." );
475         return;
476     }
477
478     %friends = %nicks = ();
479
480     my $service;
481     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
482         ( $user, $service ) = ( $1, $2 );
483     } else {
484         $service = Irssi::settings_get_str("twirssi_default_service");
485     }
486     $defservice = $service = ucfirst lc $service;
487
488     eval "use Net::$service";
489     if ($@) {
490         &notice(
491             "Failed to load Net::$service when trying to log in as $user: $@");
492         return;
493     }
494
495     $twit = "Net::$service"->new(
496         username => $user,
497         password => $pass,
498         source   => "twirssi",
499         ssl      => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
500     );
501
502     unless ($twit) {
503         &notice("Failed to create Net::$service object!  Aborting.");
504         return;
505     }
506
507     if ( my $timeout = Irssi::settings_get_int("twitter_timeout") and $twit->can('ua')) {
508         $twit->ua->timeout($timeout);
509     }
510
511     unless ( $twit->verify_credentials() ) {
512         &notice("Login as $user\@$service failed");
513         $twit = undef;
514         if ( keys %twits ) {
515             &cmd_switch( ( keys %twits )[0], $server, $win );
516         }
517         return;
518     }
519
520     if ($twit) {
521         my $rate_limit = $twit->rate_limit_status();
522         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
523             &notice(
524                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
525             );
526             $twit = undef;
527             return;
528         }
529
530         $twits{"$user\@$service"} = $twit;
531         Irssi::timeout_remove($poll) if $poll;
532         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
533         &notice("Logged in as $user\@$service, loading friends list...");
534         &load_friends();
535         &notice( "loaded friends: ", scalar keys %friends );
536         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
537             Irssi::settings_set_bool( "twirssi_first_run", 0 );
538             unless ( exists $friends{twirssi} ) {
539                 &notice("Welcome to twirssi!"
540                       . "  Perhaps you should add \@twirssi to your friends list,"
541                       . " so you can be notified when a new version is release?"
542                       . "  Just type /twitter_follow twirssi." );
543             }
544         }
545         %nicks = %friends;
546         $nicks{$user} = 0;
547         return 1;
548     } else {
549         &notice("Login failed");
550     }
551 }
552
553 sub cmd_add_search {
554     my ( $data, $server, $win ) = @_;
555
556     unless ( $twit and $twit->can('search') ) {
557         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
558               . "doesn't support searches." );
559         return;
560     }
561
562     $data =~ s/^\s+|\s+$//;
563     $data = lc $data;
564
565     unless ($data) {
566         &notice("Usage: /twitter_subscribe <topic>");
567         return;
568     }
569
570     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
571         &notice("Already had a subscription for '$data'");
572         return;
573     }
574
575     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
576     &notice("Added subscription for '$data'");
577 }
578
579 sub cmd_del_search {
580     my ( $data, $server, $win ) = @_;
581
582     unless ( $twit and $twit->can('search') ) {
583         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
584               . "doesn't support searches." );
585         return;
586     }
587     $data =~ s/^\s+|\s+$//;
588     $data = lc $data;
589
590     unless ($data) {
591         &notice("Usage: /twitter_unsubscribe <topic>");
592         return;
593     }
594
595     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
596         &notice("No subscription found for '$data'");
597         return;
598     }
599
600     delete $id_map{__searches}{"$user\@$defservice"}{$data};
601     &notice("Removed subscription for '$data'");
602 }
603
604 sub cmd_list_search {
605     my ( $data, $server, $win ) = @_;
606
607     my $found = 0;
608     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
609         my $topics;
610         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
611             $topics = $topics ? "$topics, $topic" : $topic;
612         }
613         if ($topics) {
614             $found = 1;
615             &notice("Search subscriptions for \@$suser: $topics");
616         }
617     }
618
619     unless ($found) {
620         &notice("No search subscriptions set up");
621     }
622 }
623
624 sub cmd_upgrade {
625     my ( $data, $server, $win ) = @_;
626
627     my $loc = Irssi::settings_get_str("twirssi_location");
628     unless ( -w $loc ) {
629         &notice(
630 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
631         );
632         return;
633     }
634
635     my $md5;
636     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
637         eval { use Digest::MD5; };
638
639         if ($@) {
640             &notice(
641 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
642             );
643             return;
644         }
645
646         $md5 = get("http://twirssi.com/md5sum");
647         chomp $md5;
648         $md5 =~ s/ .*//;
649         unless ($md5) {
650             &notice("Failed to download md5sum from peeron!  Aborting.");
651             return;
652         }
653
654         unless ( open( CUR, $loc ) ) {
655             &notice(
656 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
657             );
658             return;
659         }
660
661         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
662         close CUR;
663
664         if ( $cur_md5 eq $md5 ) {
665             &notice("Current twirssi seems to be up to date.");
666             return;
667         }
668     }
669
670     my $URL =
671       Irssi::settings_get_bool("twirssi_upgrade_beta")
672       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
673       : "http://twirssi.com/twirssi.pl";
674     &notice("Downloading twirssi from $URL");
675     LWP::Simple::getstore( $URL, "$loc.upgrade" );
676
677     unless ( -s "$loc.upgrade" ) {
678         &notice("Failed to save $loc.upgrade."
679               . "  Check that /set twirssi_location is set to the correct location."
680         );
681         return;
682     }
683
684     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
685         unless ( open( NEW, "$loc.upgrade" ) ) {
686             &notice("Failed to read $loc.upgrade."
687                   . "  Check that /set twirssi_location is set to the correct location."
688             );
689             return;
690         }
691
692         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
693         close NEW;
694
695         if ( $new_md5 ne $md5 ) {
696             &notice("MD5 verification failed. expected $md5, got $new_md5");
697             return;
698         }
699     }
700
701     rename $loc, "$loc.backup"
702       or &notice("Failed to back up $loc: $!.  Aborting")
703       and return;
704     rename "$loc.upgrade", $loc
705       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
706       and return;
707
708     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
709     if ( -e "$dir/autorun/$file" ) {
710         &notice("Updating $dir/autorun/$file");
711         unlink "$dir/autorun/$file"
712           or &notice("Failed to remove old $file from autorun: $!");
713         symlink "../$file", "$dir/autorun/$file"
714           or &notice("Failed to create symlink in autorun directory: $!");
715     }
716
717     &notice("Download complete.  Reload twirssi with /script load $file");
718 }
719
720 sub load_friends {
721     my $fh   = shift;
722     my $page = 1;
723     my %new_friends;
724     eval {
725         while (1)
726         {
727             print $fh "type:debug Loading friends page $page...\n"
728               if ( $fh and &debug );
729             my $friends = $twit->friends( { page => $page } );
730             last unless $friends;
731             $new_friends{ $_->{screen_name} } = time foreach @$friends;
732             $page++;
733             last if @$friends == 0 or $page == 10;
734         }
735     };
736
737     if ($@) {
738         print $fh "type:debug Error during friends list update.  Aborted.\n";
739         return;
740     }
741
742     my ( $added, $removed ) = ( 0, 0 );
743     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
744     foreach ( keys %new_friends ) {
745         next if exists $friends{$_};
746         $friends{$_} = time;
747         $added++;
748     }
749
750     print $fh "type:debug Scanning for removed friends...\n"
751       if ( $fh and &debug );
752     foreach ( keys %friends ) {
753         next if exists $new_friends{$_};
754         delete $friends{$_};
755         $removed++;
756     }
757
758     return ( $added, $removed );
759 }
760
761 sub get_updates {
762     print scalar localtime, " - get_updates starting" if &debug;
763
764     $window =
765       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
766     unless ($window) {
767         Irssi::active_win()
768           ->print( "Can't find a window named '"
769               . Irssi::settings_get_str('twitter_window')
770               . "'.  Create it or change the value of twitter_window" );
771     }
772
773     return unless &logged_in($twit);
774
775     my ( $fh, $filename ) = File::Temp::tempfile();
776     binmode( $fh, ":utf8" );
777     my $pid = fork();
778
779     if ($pid) {    # parent
780         Irssi::timeout_add_once( 5000, 'monitor_child',
781             [ "$filename.done", 0 ] );
782         Irssi::pidwait_add($pid);
783     } elsif ( defined $pid ) {    # child
784         close STDIN;
785         close STDOUT;
786         close STDERR;
787
788         my $new_poll = time;
789
790         my $error = 0;
791         my %context_cache;
792         foreach ( keys %twits ) {
793             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
794         }
795
796         print $fh "__friends__\n";
797         if (
798             time - $last_friends_poll >
799             Irssi::settings_get_int('twitter_friends_poll') )
800         {
801             print $fh "__updated ", time, "\n";
802             my ( $added, $removed ) = &load_friends($fh);
803             if ( $added + $removed ) {
804                 print $fh "type:debug %R***%n Friends list updated: ",
805                   join( ", ",
806                     sprintf( "%d added",   $added ),
807                     sprintf( "%d removed", $removed ) ),
808                   "\n";
809             }
810         }
811
812         foreach ( sort keys %friends ) {
813             print $fh "$_ $friends{$_}\n";
814         }
815
816         if ($error) {
817             print $fh "type:debug Update encountered errors.  Aborted\n";
818             print $fh "-- $last_poll";
819         } else {
820             print $fh "-- $new_poll";
821         }
822         close $fh;
823         rename $filename, "$filename.done";
824         exit;
825     } else {
826         &ccrap("Failed to fork for updating: $!");
827     }
828     print scalar localtime, " - get_updates ends" if &debug;
829 }
830
831 sub do_updates {
832     my ( $fh, $username, $obj, $cache ) = @_;
833
834     my $rate_limit = $obj->rate_limit_status();
835     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
836         &notice("Rate limit exceeded for $username");
837         return undef;
838     }
839
840     print scalar localtime, " - Polling for updates for $username" if &debug;
841     my $tweets;
842     my $new_poll_id = 0;
843     eval {
844         if ( $id_map{__last_id}{$username}{timeline} )
845         {
846             $tweets = $obj->friends_timeline( { count => 100 } );
847         } else {
848             $tweets = $obj->friends_timeline();
849         }
850     };
851
852     if ($@) {
853         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
854         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
855         return undef;
856     }
857
858     unless ( ref $tweets ) {
859         if ( $obj->can("get_error") ) {
860             my $error = "Unknown error";
861             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
862             unless ($@) { $error = $obj->get_error() }
863             print $fh
864               "type:debug API Error during friends_timeline call: Aborted\n";
865             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
866
867         } else {
868             print $fh
869               "type:debug API Error during friends_timeline call. Aborted.\n";
870         }
871         return undef;
872     }
873
874     foreach my $t ( reverse @$tweets ) {
875         my $text = decode_entities( $t->{text} );
876         $text =~ s/[\n\r]/ /g;
877         my $reply = "tweet";
878         if (    Irssi::settings_get_bool("show_reply_context")
879             and $t->{in_reply_to_screen_name} ne $username
880             and $t->{in_reply_to_screen_name}
881             and not exists $friends{ $t->{in_reply_to_screen_name} } )
882         {
883             $nicks{ $t->{in_reply_to_screen_name} } = time;
884             my $context;
885             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
886                 eval {
887                     $cache->{ $t->{in_reply_to_status_id} } =
888                       $obj->show_status( $t->{in_reply_to_status_id} );
889                 };
890
891             }
892             $context = $cache->{ $t->{in_reply_to_status_id} };
893
894             if ($context) {
895                 my $ctext = decode_entities( $context->{text} );
896                 $ctext =~ s/[\n\r]/ /g;
897                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
898                     $ctext .=
899                         " -- http://twitter.com/$context->{user}{screen_name}"
900                       . "/status/$context->{id}";
901                 }
902                 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
903                   $context->{id}, $username,
904                   $context->{user}{screen_name}, $ctext;
905                 $reply = "reply";
906             }
907         }
908         next
909           if $t->{user}{screen_name} eq $username
910               and not Irssi::settings_get_bool("show_own_tweets");
911         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
912             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
913               . "/status/$t->{id}";
914         }
915         printf $fh "id:%u account:%s nick:%s type:%s %s\n",
916           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
917         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
918     }
919     printf $fh "id:%u account:%s type:last_id timeline\n",
920       $new_poll_id, $username;
921
922     print scalar localtime, " - Polling for replies since ",
923       $id_map{__last_id}{$username}{reply}
924       if &debug;
925     $new_poll_id = 0;
926     eval {
927         if ( $id_map{__last_id}{$username}{reply} )
928         {
929             $tweets = $obj->replies(
930                 { since_id => $id_map{__last_id}{$username}{reply} } )
931               || [];
932         } else {
933             $tweets = $obj->replies() || [];
934         }
935     };
936
937     if ($@) {
938         print $fh "type:debug Error during replies call.  Aborted.\n";
939         return undef;
940     }
941
942     foreach my $t ( reverse @$tweets ) {
943         next
944           if exists $friends{ $t->{user}{screen_name} };
945
946         my $text = decode_entities( $t->{text} );
947         $text =~ s/[\n\r]/ /g;
948         if ( $t->{truncated} ) {
949             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
950               . "/status/$t->{id}";
951         }
952         printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
953           $t->{id}, $username, $t->{user}{screen_name}, $text;
954         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
955     }
956     printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
957
958     print scalar localtime, " - Polling for DMs" if &debug;
959     $new_poll_id = 0;
960     eval {
961         if ( $id_map{__last_id}{$username}{dm} )
962         {
963             $tweets = $obj->direct_messages(
964                 { since_id => $id_map{__last_id}{$username}{dm} } )
965               || [];
966         } else {
967             $tweets = $obj->direct_messages() || [];
968         }
969     };
970
971     if ($@) {
972         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
973         return undef;
974     }
975
976     foreach my $t ( reverse @$tweets ) {
977         my $text = decode_entities( $t->{text} );
978         $text =~ s/[\n\r]/ /g;
979         printf $fh "id:%u account:%s nick:%s type:dm %s\n",
980           $t->{id}, $username, $t->{sender_screen_name}, $text;
981         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
982     }
983     printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
984
985     print scalar localtime, " - Polling for subscriptions" if &debug;
986     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
987         my $search;
988         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
989             print $fh "type:debug searching for $topic since ",
990               "$id_map{__searches}{$username}{$topic}\n";
991             eval {
992                 $search = $obj->search(
993                     {
994                         q        => $topic,
995                         since_id => $id_map{__searches}{$username}{$topic}
996                     }
997                 );
998             };
999
1000             if ($@) {
1001                 print $fh
1002                   "type:debug Error during search($topic) call.  Aborted.\n";
1003                 return undef;
1004             }
1005
1006             unless ( $search->{max_id} ) {
1007                 print $fh "type:debug Invalid search results when searching",
1008                   " for $topic. Aborted.\n";
1009                 return undef;
1010             }
1011
1012             $id_map{__searches}{$username}{$topic} = $search->{max_id};
1013             printf $fh "id:%u account:%s type:searchid topic:%s\n",
1014               $search->{max_id}, $username, $topic;
1015
1016             foreach my $t ( reverse @{ $search->{results} } ) {
1017                 my $text = decode_entities( $t->{text} );
1018                 $text =~ s/[\n\r]/ /g;
1019                 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
1020                   $t->{id}, $username, $t->{from_user}, $topic, $text;
1021                 $new_poll_id = $t->{id}
1022                   if not $new_poll_id
1023                       or $t->{id} < $new_poll_id;
1024             }
1025         }
1026     }
1027
1028     print scalar localtime, " - Done" if &debug;
1029
1030     return 1;
1031 }
1032
1033 sub monitor_child {
1034     my ($data)   = @_;
1035     my $filename = $data->[0];
1036     my $attempt  = $data->[1];
1037
1038     print scalar localtime, " - checking child log at $filename ($attempt)"
1039       if &debug;
1040     my ($new_last_poll);
1041
1042     # first time we run we don't want to print out *everything*, so we just
1043     # pretend
1044
1045     if ( open FILE, $filename ) {
1046         binmode FILE, ":utf8";
1047         my @lines;
1048         my %new_cache;
1049         while (<FILE>) {
1050             last if /^__friends__/;
1051             unless (/\n$/) {    # skip partial lines
1052                                 # print "Skipping partial line: $_" if &debug;
1053                 next;
1054             }
1055             chomp;
1056             my $hilight = 0;
1057             my %meta;
1058
1059             foreach my $key (qw/id account nick type topic/) {
1060                 if (s/^$key:(\S+)\s*//) {
1061                     $meta{$key} = $1;
1062                 }
1063             }
1064
1065             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1066                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1067                     next;
1068                 }
1069
1070                 $new_cache{ $meta{id} } = time;
1071
1072                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1073                     next;
1074                 }
1075             }
1076
1077             my $account = "";
1078             $meta{account} =~ s/\@(\w+)$//;
1079             $meta{service} = $1;
1080             if (
1081                 lc $meta{service} eq
1082                 lc Irssi::settings_get_str("twirssi_default_service") )
1083             {
1084                 $account = "$meta{account}: "
1085                   if lc "$meta{account}\@$meta{service}" ne lc
1086                       "$user\@$defservice";
1087             } else {
1088                 $account = "$meta{account}\@$meta{service}: ";
1089             }
1090
1091             my $marker = "";
1092             if (    $meta{type} ne 'dm'
1093                 and Irssi::settings_get_bool("twirssi_track_replies")
1094                 and $meta{nick}
1095                 and $meta{id} )
1096             {
1097                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1098                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1099                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1100                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1101                 $marker                                      = ":$marker";
1102             }
1103
1104             my $hilight_color =
1105               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1106             my $nick = "\@$meta{account}";
1107             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1108                 and Irssi::settings_get_bool("twirssi_hilights") )
1109             {
1110                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1111                 $hilight = MSGLEVEL_HILIGHT;
1112             }
1113
1114             if ( $meta{type} =~ /tweet|reply/ ) {
1115                 push @lines,
1116                   [
1117                     ( MSGLEVEL_PUBLIC | $hilight ),
1118                     $meta{type}, $account, $meta{nick}, $marker, $_
1119                   ];
1120             } elsif ( $meta{type} eq 'search' ) {
1121                 push @lines,
1122                   [
1123                     ( MSGLEVEL_PUBLIC | $hilight ),
1124                     $meta{type}, $account, $meta{topic},
1125                     $meta{nick}, $marker,  $_
1126                   ];
1127                 if (
1128                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1129                     and $meta{id} >
1130                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1131                 {
1132                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1133                       $meta{id};
1134                 }
1135             } elsif ( $meta{type} eq 'dm' ) {
1136                 push @lines,
1137                   [
1138                     ( MSGLEVEL_MSGS | $hilight ),
1139                     $meta{type}, $account, $meta{nick}, $_
1140                   ];
1141             } elsif ( $meta{type} eq 'searchid' ) {
1142                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1143                 if (
1144                     not
1145                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1146                     or $meta{id} >=
1147                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1148                 {
1149                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1150                       $meta{id};
1151                 } elsif (&debug) {
1152                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1153                 }
1154             } elsif ( $meta{type} eq 'last_id' ) {
1155                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1156                   $meta{id}
1157                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1158                       $meta{id};
1159             } elsif ( $meta{type} eq 'error' ) {
1160                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1161             } elsif ( $meta{type} eq 'debug' ) {
1162                 print "$_" if &debug,;
1163             } else {
1164                 print "Unknown line type $meta{type}: $_" if &debug,;
1165             }
1166         }
1167
1168         %friends = ();
1169         while (<FILE>) {
1170             if (/^__updated (\d+)$/) {
1171                 $last_friends_poll = $1;
1172                 print "Friend list updated" if &debug;
1173                 next;
1174             }
1175
1176             if (/^-- (\d+)$/) {
1177                 $new_last_poll = $1;
1178                 if ( $new_last_poll >= $last_poll ) {
1179                     last;
1180                 } else {
1181                     print "Impossible!  ",
1182                       "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1183                       if &debug;
1184                     undef $new_last_poll;
1185                     next;
1186                 }
1187             }
1188             my ( $f, $t ) = split ' ', $_;
1189             $nicks{$f} = $friends{$f} = $t;
1190         }
1191
1192         if ($new_last_poll) {
1193             print "new last_poll    = $new_last_poll" if &debug;
1194             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1195             if ($first_call) {
1196                 print "First call, not printing updates" if &debug;
1197             } else {
1198                 foreach my $line (@lines) {
1199                     $window->printformat(
1200                         $line->[0],
1201                         "twirssi_" . $line->[1],
1202                         @$line[ 2 .. $#$line - 1 ],
1203                         &hilight( $line->[-1] )
1204                     );
1205                 }
1206             }
1207
1208             close FILE;
1209             unlink $filename
1210               or warn "Failed to remove $filename: $!"
1211               unless &debug;
1212
1213             # commit the pending cache lines to the actual cache, now that
1214             # we've printed our output
1215             %tweet_cache = ( %tweet_cache, %new_cache );
1216
1217             # keep enough cached tweets, to make sure we don't show duplicates.
1218             foreach ( keys %tweet_cache ) {
1219                 next if $tweet_cache{$_} >= $last_poll - 3600;
1220                 delete $tweet_cache{$_};
1221             }
1222             $last_poll = $new_last_poll;
1223
1224             # save id_map hash
1225             if ( keys %id_map
1226                 and my $file =
1227                 Irssi::settings_get_str("twirssi_replies_store") )
1228             {
1229                 if ( open JSON, ">$file" ) {
1230                     print JSON JSON::Any->objToJson( \%id_map );
1231                     close JSON;
1232                 } else {
1233                     &ccrap("Failed to write replies to $file: $!");
1234                 }
1235             }
1236             $failwhale  = 0;
1237             $first_call = 0;
1238             return;
1239         }
1240     }
1241
1242     close FILE;
1243
1244     if ( $attempt < 24 ) {
1245         Irssi::timeout_add_once( 5000, 'monitor_child',
1246             [ $filename, $attempt + 1 ] );
1247     } else {
1248         print "Giving up on polling $filename" if &debug;
1249         unlink $filename unless &debug;
1250
1251         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1252
1253         my $since;
1254         my @time = localtime($last_poll);
1255         if ( time - $last_poll < 24 * 60 * 60 ) {
1256             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1257         } else {
1258             $since = scalar localtime($last_poll);
1259         }
1260
1261         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1262             foreach my $whale (
1263                 q{     v  v        v},
1264                 q{     |  |  v     |  v},
1265                 q{     | .-, |     |  |},
1266                 q{  .--./ /  |  _.---.| },
1267                 q{   '-. (__..-"       \\},
1268                 q{      \\          a    |},
1269                 q{       ',.__.   ,__.-'/},
1270                 q{         '--/_.'----'`}
1271               )
1272             {
1273                 &ccrap($whale);
1274             }
1275             $failwhale = 1;
1276         }
1277
1278         if ( time - $last_poll < 600 ) {
1279             &ccrap("Haven't been able to get updated tweets since $since");
1280         }
1281     }
1282 }
1283
1284 sub debug {
1285     return Irssi::settings_get_bool("twirssi_debug");
1286 }
1287
1288 sub notice {
1289     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1290 }
1291
1292 sub ccrap {
1293     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1294 }
1295
1296 sub update_away {
1297     my $data = shift;
1298
1299     if (    Irssi::settings_get_bool("tweet_to_away")
1300         and $data !~ /\@\w/
1301         and $data !~ /^[dD] / )
1302     {
1303         my $server =
1304           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1305         if ($server) {
1306             $server->send_raw("away :$data");
1307             return 1;
1308         } else {
1309             &ccrap( "Can't find bitlbee server.",
1310                 "Update bitlbee_server or disable tweet_to_away" );
1311             return 0;
1312         }
1313     }
1314
1315     return 0;
1316 }
1317
1318 sub too_long {
1319     my $data    = shift;
1320     my $noalert = shift;
1321
1322     if ( length $data > 140 ) {
1323         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1324           unless $noalert;
1325         return 1;
1326     }
1327
1328     return 0;
1329 }
1330
1331 sub valid_username {
1332     my $username = shift;
1333
1334     $username = &normalize_username($username);
1335
1336     unless ( exists $twits{$username} ) {
1337         &notice("Unknown username $username");
1338         return undef;
1339     }
1340
1341     return $username;
1342 }
1343
1344 sub logged_in {
1345     my $obj = shift;
1346     unless ($obj) {
1347         &notice("Not logged in!  Use /twitter_login username pass!");
1348         return 0;
1349     }
1350
1351     return 1;
1352 }
1353
1354 sub sig_complete {
1355     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1356
1357     if (
1358         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1359         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1360             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1361       )
1362     {    # /twitter_reply gets a nick:num
1363         $word =~ s/^@//;
1364         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1365           sort { $nicks{$b} <=> $nicks{$a} }
1366           grep /^\Q$word/i,
1367           keys %{ $id_map{__indexes} };
1368     }
1369
1370     if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1371     {    # /twitter_unfriend gets a nick
1372         $word =~ s/^@//;
1373         push @$complist, grep /^\Q$word/i,
1374           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1375     }
1376
1377     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1378     # arg to dm)
1379     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1380         my $prefix = $word =~ s/^@//;
1381         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1382         push @$complist, grep /^\Q$word/i,
1383           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1384         @$complist = map { "\@$_" } @$complist if $prefix;
1385     }
1386 }
1387
1388 sub event_send_text {
1389     my ( $line, $server, $win ) = @_;
1390     my $awin = Irssi::active_win();
1391
1392     # if the window where we got our text was the twitter window, and the user
1393     # wants to be lazy, tweet away!
1394     if ( ( $awin->get_active_name() eq $window->{name} )
1395         and Irssi::settings_get_bool("tweet_window_input") )
1396     {
1397         &cmd_tweet( $line, $server, $win );
1398     }
1399 }
1400
1401 sub get_poll_time {
1402     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1403     return $poll if $poll >= 60;
1404     return 60;
1405 }
1406
1407 sub hilight {
1408     my $text = shift;
1409
1410     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1411         my $c = Irssi::settings_get_str("twirssi_nick_color");
1412         $c = $irssi_to_mirc_colors{$c};
1413         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1414     }
1415     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1416         my $c = Irssi::settings_get_str("twirssi_topic_color");
1417         $c = $irssi_to_mirc_colors{$c};
1418         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1419     }
1420     $text =~ s/[\n\r]/ /g;
1421
1422     return $text;
1423 }
1424
1425 sub shorten {
1426     my $data = shift;
1427
1428     my $provider = Irssi::settings_get_str("short_url_provider");
1429     if (
1430         (
1431             Irssi::settings_get_bool("twirssi_always_shorten")
1432             or &too_long( $data, 1 )
1433         )
1434         and $provider
1435       )
1436     {
1437         my @args;
1438         if ( $provider eq 'Bitly' ) {
1439             @args[ 1, 2 ] = split ',',
1440               Irssi::settings_get_str("short_url_args"), 2;
1441             unless ( @args == 3 ) {
1442                 &ccrap(
1443                     "WWW::Shorten::Bitly requires a username and API key.",
1444                     "Set short_url_args to username,API_key or change your",
1445                     "short_url_provider."
1446                 );
1447                 return $data;
1448             }
1449         }
1450
1451         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1452             eval {
1453                 $args[0] = $url;
1454                 my $short = makeashorterlink(@args);
1455                 if ($short) {
1456                     $data =~ s/\Q$url/$short/g;
1457                 } else {
1458                     &notice("Failed to shorten $url!");
1459                 }
1460             };
1461         }
1462     }
1463
1464     return decode "utf8", $data;
1465 }
1466
1467 sub normalize_username {
1468     my $user = shift;
1469
1470     my ( $username, $service ) = split /\@/, $user, 2;
1471     if ($service) {
1472         $service = ucfirst lc $service;
1473     } else {
1474         $service =
1475           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1476         unless ( exists $twits{"$username\@$service"} ) {
1477             $service = undef;
1478             foreach my $t ( sort keys %twits ) {
1479                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1480                 $service = $1;
1481                 last;
1482             }
1483
1484             unless ($service) {
1485                 &notice("Can't find a logged in user '$user'");
1486             }
1487         }
1488     }
1489
1490     return "$username\@$service";
1491 }
1492
1493 Irssi::signal_add( "send text", "event_send_text" );
1494
1495 Irssi::theme_register(
1496     [
1497         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1498         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1499         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1500         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1501         'twirssi_error',  'ERROR: $0',
1502     ]
1503 );
1504
1505 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1506 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1507 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1508 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1509 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1510 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1511 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1512 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1513 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1514 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1515 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1516     'RT $n: "$t" ${-- $c$}' );
1517 Irssi::settings_add_str( "twirssi", "twirssi_location",
1518     ".irssi/scripts/twirssi.pl" );
1519 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1520     ".irssi/scripts/twirssi.json" );
1521
1522 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1523 Irssi::settings_add_int( "twirssi", "twitter_timeout", 30 );
1524
1525 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1526 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1527 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1528 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1529 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1530 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1531 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1532 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1533 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1534 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1535 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1536 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1537 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1538 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl",         0 );
1539
1540 $last_poll = time - &get_poll_time;
1541 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1542 if ( !$window ) {
1543     Irssi::active_win()
1544       ->print( "Couldn't find a window named '"
1545           . Irssi::settings_get_str('twitter_window')
1546           . "', trying to create it." );
1547     $window =
1548       Irssi::Windowitem::window_create(
1549         Irssi::settings_get_str('twitter_window'), 1 );
1550     $window->set_name( Irssi::settings_get_str('twitter_window') );
1551 }
1552
1553 if ($window) {
1554     Irssi::command_bind( "dm",                         "cmd_direct" );
1555     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1556     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1557     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1558     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1559     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1560     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1561     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1562     Irssi::command_bind( "twitter_login",              "cmd_login" );
1563     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1564     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1565     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1566     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1567     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1568     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1569     Irssi::command_bind( "twitter_updates",            "get_updates" );
1570     Irssi::command_bind( "bitlbee_away",               "update_away" );
1571     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1572         Irssi::command_bind( "reply",    "cmd_reply" );
1573         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1574     }
1575     Irssi::command_bind(
1576         "twirssi_dump",
1577         sub {
1578             print "twits: ", join ", ",
1579               map { "u: $_->{username}\@" . ref($_) } values %twits;
1580             print "selected: $user\@$defservice";
1581             print "friends: ", join ", ", sort keys %friends;
1582             print "nicks: ",   join ", ", sort keys %nicks;
1583             print "searches: ", Dumper \%{ $id_map{__searches} };
1584             print "last poll: $last_poll";
1585             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1586                 print DUMP Dumper \%tweet_cache;
1587                 close DUMP;
1588                 print "cache written out to /tmp/twirssi.cache.txt";
1589             }
1590         }
1591     );
1592     Irssi::command_bind(
1593         "twirssi_version",
1594         sub {
1595             &notice("Twirssi v$VERSION (r$REV); "
1596                   . "Net::Twitter v$Net::Twitter::VERSION. "
1597                   . "JSON in use: "
1598                   . JSON::Any::handler()
1599                   . ".  See details at http://twirssi.com/" );
1600         }
1601     );
1602     Irssi::command_bind(
1603         "twitter_follow",
1604         &gen_cmd(
1605             "/twitter_follow <username>",
1606             "create_friend",
1607             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1608         )
1609     );
1610     Irssi::command_bind(
1611         "twitter_unfollow",
1612         &gen_cmd(
1613             "/twitter_unfriend <username>",
1614             "destroy_friend",
1615             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1616         )
1617     );
1618     Irssi::command_bind(
1619         "twitter_device_updates",
1620         &gen_cmd(
1621             "/twitter_device_updates none|im|sms",
1622             "update_delivery_device",
1623             sub { &notice("Device updated to $_[0]"); }
1624         )
1625     );
1626     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1627
1628     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1629     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1630     &notice(
1631         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1632
1633     my $file = Irssi::settings_get_str("twirssi_replies_store");
1634     if ( $file and -r $file ) {
1635         if ( open( JSON, $file ) ) {
1636             local $/;
1637             my $json = <JSON>;
1638             close JSON;
1639             eval {
1640                 my $ref = JSON::Any->jsonToObj($json);
1641                 %id_map = %$ref;
1642                 my $num = keys %{ $id_map{__indexes} };
1643                 &notice( sprintf "Loaded old replies from %d contact%s.",
1644                     $num, ( $num == 1 ? "" : "s" ) );
1645                 &cmd_list_search;
1646             };
1647         } else {
1648             &notice("Failed to load old replies from $file: $!");
1649         }
1650     }
1651
1652     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1653         &notice("Loading WWW::Shorten::$provider...");
1654         eval "use WWW::Shorten::$provider;";
1655
1656         if ($@) {
1657             &notice(
1658                 "Failed to load WWW::Shorten::$provider - either clear",
1659                 "short_url_provider or install the CPAN module"
1660             );
1661         }
1662     }
1663
1664     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1665         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1666     {
1667         &cmd_login();
1668         &get_updates;
1669     }
1670
1671 } else {
1672     Irssi::active_win()
1673       ->print( "Create a window named "
1674           . Irssi::settings_get_str('twitter_window')
1675           . " or change the value of twitter_window.  Then, reload twirssi." );
1676 }
1677
1678 # vim: set sts=4 expandtab: