r676 - perltidy. Also, give an error if we failed to save a beta download.
[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: 676 $' =~ /(\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-07-22 11:05:52 -0700 (Wed, 22 Jul 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     );
500
501     unless ( $twit->verify_credentials() ) {
502         &notice("Login as $user\@$service failed");
503         $twit = undef;
504         if ( keys %twits ) {
505             &cmd_switch( ( keys %twits )[0], $server, $win );
506         }
507         return;
508     }
509
510     if ($twit) {
511         my $rate_limit = $twit->rate_limit_status();
512         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
513             &notice(
514                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
515             );
516             $twit = undef;
517             return;
518         }
519
520         $twits{"$user\@$service"} = $twit;
521         Irssi::timeout_remove($poll) if $poll;
522         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
523         &notice("Logged in as $user\@$service, loading friends list...");
524         &load_friends();
525         &notice( "loaded friends: ", scalar keys %friends );
526         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
527             Irssi::settings_set_bool( "twirssi_first_run", 0 );
528             unless ( exists $friends{twirssi} ) {
529                 &notice("Welcome to twirssi!"
530                       . "  Perhaps you should add \@twirssi to your friends list,"
531                       . " so you can be notified when a new version is release?"
532                       . "  Just type /twitter_follow twirssi." );
533             }
534         }
535         %nicks = %friends;
536         $nicks{$user} = 0;
537         return 1;
538     } else {
539         &notice("Login failed");
540     }
541 }
542
543 sub cmd_add_search {
544     my ( $data, $server, $win ) = @_;
545
546     unless ( $twit and $twit->can('search') ) {
547         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
548               . "doesn't support searches." );
549         return;
550     }
551
552     $data =~ s/^\s+|\s+$//;
553     $data = lc $data;
554
555     unless ($data) {
556         &notice("Usage: /twitter_subscribe <topic>");
557         return;
558     }
559
560     if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
561         &notice("Already had a subscription for '$data'");
562         return;
563     }
564
565     $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
566     &notice("Added subscription for '$data'");
567 }
568
569 sub cmd_del_search {
570     my ( $data, $server, $win ) = @_;
571
572     unless ( $twit and $twit->can('search') ) {
573         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
574               . "doesn't support searches." );
575         return;
576     }
577     $data =~ s/^\s+|\s+$//;
578     $data = lc $data;
579
580     unless ($data) {
581         &notice("Usage: /twitter_unsubscribe <topic>");
582         return;
583     }
584
585     unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
586         &notice("No subscription found for '$data'");
587         return;
588     }
589
590     delete $id_map{__searches}{"$user\@$defservice"}{$data};
591     &notice("Removed subscription for '$data'");
592 }
593
594 sub cmd_list_search {
595     my ( $data, $server, $win ) = @_;
596
597     my $found = 0;
598     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
599         my $topics;
600         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
601             $topics = $topics ? "$topics, $topic" : $topic;
602         }
603         if ($topics) {
604             $found = 1;
605             &notice("Search subscriptions for \@$suser: $topics");
606         }
607     }
608
609     unless ($found) {
610         &notice("No search subscriptions set up");
611     }
612 }
613
614 sub cmd_upgrade {
615     my ( $data, $server, $win ) = @_;
616
617     my $loc = Irssi::settings_get_str("twirssi_location");
618     unless ( -w $loc ) {
619         &notice(
620 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
621         );
622         return;
623     }
624
625     my $md5;
626     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
627         eval { use Digest::MD5; };
628
629         if ($@) {
630             &notice(
631 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
632             );
633             return;
634         }
635
636         $md5 = get("http://twirssi.com/md5sum");
637         chomp $md5;
638         $md5 =~ s/ .*//;
639         unless ($md5) {
640             &notice("Failed to download md5sum from peeron!  Aborting.");
641             return;
642         }
643
644         unless ( open( CUR, $loc ) ) {
645             &notice(
646 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
647             );
648             return;
649         }
650
651         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
652         close CUR;
653
654         if ( $cur_md5 eq $md5 ) {
655             &notice("Current twirssi seems to be up to date.");
656             return;
657         }
658     }
659
660     my $URL =
661       Irssi::settings_get_bool("twirssi_upgrade_beta")
662       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
663       : "http://twirssi.com/twirssi.pl";
664     &notice("Downloading twirssi from $URL");
665     LWP::Simple::getstore( $URL, "$loc.upgrade" );
666
667     unless ( -s "$loc.upgrade" ) {
668         &notice("Failed to save $loc.upgrade."
669               . "  Check that /set twirssi_location is set to the correct location."
670         );
671         return;
672     }
673
674     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
675         unless ( open( NEW, "$loc.upgrade" ) ) {
676             &notice("Failed to read $loc.upgrade."
677                   . "  Check that /set twirssi_location is set to the correct location."
678             );
679             return;
680         }
681
682         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
683         close NEW;
684
685         if ( $new_md5 ne $md5 ) {
686             &notice("MD5 verification failed. expected $md5, got $new_md5");
687             return;
688         }
689     }
690
691     rename $loc, "$loc.backup"
692       or &notice("Failed to back up $loc: $!.  Aborting")
693       and return;
694     rename "$loc.upgrade", $loc
695       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
696       and return;
697
698     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
699     if ( -e "$dir/autorun/$file" ) {
700         &notice("Updating $dir/autorun/$file");
701         unlink "$dir/autorun/$file"
702           or &notice("Failed to remove old $file from autorun: $!");
703         symlink "../$file", "$dir/autorun/$file"
704           or &notice("Failed to create symlink in autorun directory: $!");
705     }
706
707     &notice("Download complete.  Reload twirssi with /script load $file");
708 }
709
710 sub load_friends {
711     my $fh   = shift;
712     my $page = 1;
713     my %new_friends;
714     eval {
715         while (1)
716         {
717             print $fh "type:debug Loading friends page $page...\n"
718               if ( $fh and &debug );
719             my $friends = $twit->friends( { page => $page } );
720             last unless $friends;
721             $new_friends{ $_->{screen_name} } = time foreach @$friends;
722             $page++;
723             last if @$friends == 0 or $page == 10;
724         }
725     };
726
727     if ($@) {
728         print $fh "type:debug Error during friends list update.  Aborted.\n";
729         return;
730     }
731
732     my ( $added, $removed ) = ( 0, 0 );
733     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
734     foreach ( keys %new_friends ) {
735         next if exists $friends{$_};
736         $friends{$_} = time;
737         $added++;
738     }
739
740     print $fh "type:debug Scanning for removed friends...\n"
741       if ( $fh and &debug );
742     foreach ( keys %friends ) {
743         next if exists $new_friends{$_};
744         delete $friends{$_};
745         $removed++;
746     }
747
748     return ( $added, $removed );
749 }
750
751 sub get_updates {
752     print scalar localtime, " - get_updates starting" if &debug;
753
754     $window =
755       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
756     unless ($window) {
757         Irssi::active_win()
758           ->print( "Can't find a window named '"
759               . Irssi::settings_get_str('twitter_window')
760               . "'.  Create it or change the value of twitter_window" );
761     }
762
763     return unless &logged_in($twit);
764
765     my ( $fh, $filename ) = File::Temp::tempfile();
766     binmode( $fh, ":utf8" );
767     my $pid = fork();
768
769     if ($pid) {    # parent
770         Irssi::timeout_add_once( 5000, 'monitor_child',
771             [ "$filename.done", 0 ] );
772         Irssi::pidwait_add($pid);
773     } elsif ( defined $pid ) {    # child
774         close STDIN;
775         close STDOUT;
776         close STDERR;
777
778         my $new_poll = time;
779
780         my $error = 0;
781         my %context_cache;
782         foreach ( keys %twits ) {
783             $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
784         }
785
786         print $fh "__friends__\n";
787         if (
788             time - $last_friends_poll >
789             Irssi::settings_get_int('twitter_friends_poll') )
790         {
791             print $fh "__updated ", time, "\n";
792             my ( $added, $removed ) = &load_friends($fh);
793             if ( $added + $removed ) {
794                 print $fh "type:debug %R***%n Friends list updated: ",
795                   join( ", ",
796                     sprintf( "%d added",   $added ),
797                     sprintf( "%d removed", $removed ) ),
798                   "\n";
799             }
800         }
801
802         foreach ( sort keys %friends ) {
803             print $fh "$_ $friends{$_}\n";
804         }
805
806         if ($error) {
807             print $fh "type:debug Update encountered errors.  Aborted\n";
808             print $fh "-- $last_poll";
809         } else {
810             print $fh "-- $new_poll";
811         }
812         close $fh;
813         rename $filename, "$filename.done";
814         exit;
815     } else {
816         &ccrap("Failed to fork for updating: $!");
817     }
818     print scalar localtime, " - get_updates ends" if &debug;
819 }
820
821 sub do_updates {
822     my ( $fh, $username, $obj, $cache ) = @_;
823
824     my $rate_limit = $obj->rate_limit_status();
825     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
826         &notice("Rate limit exceeded for $username");
827         return undef;
828     }
829
830     print scalar localtime, " - Polling for updates for $username" if &debug;
831     my $tweets;
832     my $new_poll_id = 0;
833     eval {
834         if ( $id_map{__last_id}{$username}{timeline} )
835         {
836             $tweets = $obj->friends_timeline( { count => 100 } );
837         } else {
838             $tweets = $obj->friends_timeline();
839         }
840     };
841
842     if ($@) {
843         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
844         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
845         return undef;
846     }
847
848     unless ( ref $tweets ) {
849         if ( $obj->can("get_error") ) {
850             my $error = "Unknown error";
851             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
852             unless ($@) { $error = $obj->get_error() }
853             print $fh
854               "type:debug API Error during friends_timeline call: Aborted\n";
855             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
856
857         } else {
858             print $fh
859               "type:debug API Error during friends_timeline call. Aborted.\n";
860         }
861         return undef;
862     }
863
864     foreach my $t ( reverse @$tweets ) {
865         my $text = decode_entities( $t->{text} );
866         $text =~ s/[\n\r]/ /g;
867         my $reply = "tweet";
868         if (    Irssi::settings_get_bool("show_reply_context")
869             and $t->{in_reply_to_screen_name} ne $username
870             and $t->{in_reply_to_screen_name}
871             and not exists $friends{ $t->{in_reply_to_screen_name} } )
872         {
873             $nicks{ $t->{in_reply_to_screen_name} } = time;
874             my $context;
875             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
876                 eval {
877                     $cache->{ $t->{in_reply_to_status_id} } =
878                       $obj->show_status( $t->{in_reply_to_status_id} );
879                 };
880
881             }
882             $context = $cache->{ $t->{in_reply_to_status_id} };
883
884             if ($context) {
885                 my $ctext = decode_entities( $context->{text} );
886                 $ctext =~ s/[\n\r]/ /g;
887                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
888                     $ctext .=
889                         " -- http://twitter.com/$context->{user}{screen_name}"
890                       . "/status/$context->{id}";
891                 }
892                 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
893                   $context->{id}, $username,
894                   $context->{user}{screen_name}, $ctext;
895                 $reply = "reply";
896             }
897         }
898         next
899           if $t->{user}{screen_name} eq $username
900               and not Irssi::settings_get_bool("show_own_tweets");
901         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
902             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
903               . "/status/$t->{id}";
904         }
905         printf $fh "id:%u account:%s nick:%s type:%s %s\n",
906           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
907         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
908     }
909     printf $fh "id:%u account:%s type:last_id timeline\n",
910       $new_poll_id, $username;
911
912     print scalar localtime, " - Polling for replies" if &debug;
913     $new_poll_id = 0;
914     eval {
915         if ( $id_map{__last_id}{$username}{reply} )
916         {
917             $tweets = $obj->replies(
918                 { since_id => $id_map{__last_id}{$username}{reply} } )
919               || [];
920         } else {
921             $tweets = $obj->replies() || [];
922         }
923     };
924
925     if ($@) {
926         print $fh "type:debug Error during replies call.  Aborted.\n";
927         return undef;
928     }
929
930     foreach my $t ( reverse @$tweets ) {
931         next
932           if exists $friends{ $t->{user}{screen_name} };
933
934         my $text = decode_entities( $t->{text} );
935         $text =~ s/[\n\r]/ /g;
936         if ( $t->{truncated} ) {
937             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
938               . "/status/$t->{id}";
939         }
940         printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
941           $t->{id}, $username, $t->{user}{screen_name}, $text;
942         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
943     }
944     printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
945
946     print scalar localtime, " - Polling for DMs" if &debug;
947     $new_poll_id = 0;
948     eval {
949         if ( $id_map{__last_id}{$username}{dm} )
950         {
951             $tweets = $obj->direct_messages(
952                 { since_id => $id_map{__last_id}{$username}{dm} } )
953               || [];
954         } else {
955             $tweets = $obj->direct_messages() || [];
956         }
957     };
958
959     if ($@) {
960         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
961         return undef;
962     }
963
964     foreach my $t ( reverse @$tweets ) {
965         my $text = decode_entities( $t->{text} );
966         $text =~ s/[\n\r]/ /g;
967         printf $fh "id:%u account:%s nick:%s type:dm %s\n",
968           $t->{id}, $username, $t->{sender_screen_name}, $text;
969         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
970     }
971     printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
972
973     print scalar localtime, " - Polling for subscriptions" if &debug;
974     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
975         my $search;
976         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
977             print $fh "type:debug searching for $topic since ",
978               "$id_map{__searches}{$username}{$topic}\n";
979             eval {
980                 $search = $obj->search(
981                     {
982                         q        => $topic,
983                         since_id => $id_map{__searches}{$username}{$topic}
984                     }
985                 );
986             };
987
988             if ($@) {
989                 print $fh
990                   "type:debug Error during search($topic) call.  Aborted.\n";
991                 return undef;
992             }
993
994             unless ( $search->{max_id} ) {
995                 print $fh "type:debug Invalid search results when searching",
996                   " for $topic. Aborted.\n";
997                 return undef;
998             }
999
1000             $id_map{__searches}{$username}{$topic} = $search->{max_id};
1001             printf $fh "id:%u account:%s type:searchid topic:%s\n",
1002               $search->{max_id}, $username, $topic;
1003
1004             foreach my $t ( reverse @{ $search->{results} } ) {
1005                 my $text = decode_entities( $t->{text} );
1006                 $text =~ s/[\n\r]/ /g;
1007                 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
1008                   $t->{id}, $username, $t->{from_user}, $topic, $text;
1009                 $new_poll_id = $t->{id}
1010                   if not $new_poll_id
1011                       or $t->{id} < $new_poll_id;
1012             }
1013         }
1014     }
1015
1016     print scalar localtime, " - Done" if &debug;
1017
1018     return 1;
1019 }
1020
1021 sub monitor_child {
1022     my ($data)   = @_;
1023     my $filename = $data->[0];
1024     my $attempt  = $data->[1];
1025
1026     print scalar localtime, " - checking child log at $filename ($attempt)"
1027       if &debug;
1028     my ($new_last_poll);
1029
1030     # first time we run we don't want to print out *everything*, so we just
1031     # pretend
1032
1033     if ( open FILE, $filename ) {
1034         my @lines;
1035         my %new_cache;
1036         while (<FILE>) {
1037             last if /^__friends__/;
1038             unless (/\n$/) {    # skip partial lines
1039                                 # print "Skipping partial line: $_" if &debug;
1040                 next;
1041             }
1042             chomp;
1043             my $hilight = 0;
1044             my %meta;
1045
1046             foreach my $key (qw/id account nick type topic/) {
1047                 if (s/^$key:(\S+)\s*//) {
1048                     $meta{$key} = $1;
1049                 }
1050             }
1051
1052             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1053                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1054                     next;
1055                 }
1056
1057                 $new_cache{ $meta{id} } = time;
1058
1059                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1060                     next;
1061                 }
1062             }
1063
1064             my $account = "";
1065             $meta{account} =~ s/\@(\w+)$//;
1066             $meta{service} = $1;
1067             if (
1068                 lc $meta{service} eq
1069                 lc Irssi::settings_get_str("twirssi_default_service") )
1070             {
1071                 $account = "$meta{account}: "
1072                   if lc "$meta{account}\@$meta{service}" ne lc
1073                       "$user\@$defservice";
1074             } else {
1075                 $account = "$meta{account}\@$meta{service}: ";
1076             }
1077
1078             my $marker = "";
1079             if (    $meta{type} ne 'dm'
1080                 and Irssi::settings_get_bool("twirssi_track_replies")
1081                 and $meta{nick}
1082                 and $meta{id} )
1083             {
1084                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1085                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1086                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1087                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1088                 $marker                                      = ":$marker";
1089             }
1090
1091             my $hilight_color =
1092               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1093             my $nick = "\@$meta{account}";
1094             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1095                 and Irssi::settings_get_bool("twirssi_hilights") )
1096             {
1097                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1098                 $hilight = MSGLEVEL_HILIGHT;
1099             }
1100
1101             if ( $meta{type} =~ /tweet|reply/ ) {
1102                 push @lines,
1103                   [
1104                     ( MSGLEVEL_PUBLIC | $hilight ),
1105                     $meta{type}, $account, $meta{nick}, $marker, $_
1106                   ];
1107             } elsif ( $meta{type} eq 'search' ) {
1108                 push @lines,
1109                   [
1110                     ( MSGLEVEL_PUBLIC | $hilight ),
1111                     $meta{type}, $account, $meta{topic},
1112                     $meta{nick}, $marker,  $_
1113                   ];
1114                 if (
1115                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1116                     and $meta{id} >
1117                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1118                 {
1119                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1120                       $meta{id};
1121                 }
1122             } elsif ( $meta{type} eq 'dm' ) {
1123                 push @lines,
1124                   [
1125                     ( MSGLEVEL_MSGS | $hilight ),
1126                     $meta{type}, $account, $meta{nick}, $_
1127                   ];
1128             } elsif ( $meta{type} eq 'searchid' ) {
1129                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1130                 if (
1131                     not
1132                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1133                     or $meta{id} >=
1134                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1135                 {
1136                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1137                       $meta{id};
1138                 } elsif (&debug) {
1139                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1140                 }
1141             } elsif ( $meta{type} eq 'last_id' ) {
1142                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1143                   $meta{id}
1144                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1145                       $meta{id};
1146             } elsif ( $meta{type} eq 'error' ) {
1147                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1148             } elsif ( $meta{type} eq 'debug' ) {
1149                 print "$_" if &debug,;
1150             } else {
1151                 print "Unknown line type $meta{type}: $_" if &debug,;
1152             }
1153         }
1154
1155         %friends = ();
1156         while (<FILE>) {
1157             if (/^__updated (\d+)$/) {
1158                 $last_friends_poll = $1;
1159                 print "Friend list updated" if &debug;
1160                 next;
1161             }
1162
1163             if (/^-- (\d+)$/) {
1164                 ($new_last_poll) = ($1);
1165                 last;
1166             }
1167             my ( $f, $t ) = split ' ', $_;
1168             $nicks{$f} = $friends{$f} = $t;
1169         }
1170
1171         if ($new_last_poll) {
1172             print "new last_poll    = $new_last_poll" if &debug;
1173             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1174             if ($first_call) {
1175                 print "First call, not printing updates" if &debug;
1176             } else {
1177                 foreach my $line (@lines) {
1178                     $window->printformat(
1179                         $line->[0],
1180                         "twirssi_" . $line->[1],
1181                         @$line[ 2 .. $#$line - 1 ],
1182                         &hilight( $line->[-1] )
1183                     );
1184                 }
1185             }
1186
1187             close FILE;
1188             unlink $filename
1189               or warn "Failed to remove $filename: $!"
1190               unless &debug;
1191
1192             # commit the pending cache lines to the actual cache, now that
1193             # we've printed our output
1194             %tweet_cache = ( %tweet_cache, %new_cache );
1195
1196             # keep enough cached tweets, to make sure we don't show duplicates.
1197             foreach ( keys %tweet_cache ) {
1198                 next if $tweet_cache{$_} >= $last_poll - 3600;
1199                 delete $tweet_cache{$_};
1200             }
1201             $last_poll = $new_last_poll;
1202
1203             # save id_map hash
1204             if ( keys %id_map
1205                 and my $file =
1206                 Irssi::settings_get_str("twirssi_replies_store") )
1207             {
1208                 if ( open JSON, ">$file" ) {
1209                     print JSON JSON::Any->objToJson( \%id_map );
1210                     close JSON;
1211                 } else {
1212                     &ccrap("Failed to write replies to $file: $!");
1213                 }
1214             }
1215             $failwhale  = 0;
1216             $first_call = 0;
1217             return;
1218         }
1219     }
1220
1221     close FILE;
1222
1223     if ( $attempt < 24 ) {
1224         Irssi::timeout_add_once( 5000, 'monitor_child',
1225             [ $filename, $attempt + 1 ] );
1226     } else {
1227         print "Giving up on polling $filename" if &debug;
1228         unlink $filename unless &debug;
1229
1230         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1231
1232         my $since;
1233         my @time = localtime($last_poll);
1234         if ( time - $last_poll < 24 * 60 * 60 ) {
1235             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1236         } else {
1237             $since = scalar localtime($last_poll);
1238         }
1239
1240         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1241             foreach my $whale (
1242                 q{     v  v        v},
1243                 q{     |  |  v     |  v},
1244                 q{     | .-, |     |  |},
1245                 q{  .--./ /  |  _.---.| },
1246                 q{   '-. (__..-"       \\},
1247                 q{      \\          a    |},
1248                 q{       ',.__.   ,__.-'/},
1249                 q{         '--/_.'----'`}
1250               )
1251             {
1252                 &ccrap($whale);
1253             }
1254             $failwhale = 1;
1255         }
1256
1257         if ( time - $last_poll < 600 ) {
1258             &ccrap("Haven't been able to get updated tweets since $since");
1259         }
1260     }
1261 }
1262
1263 sub debug {
1264     return Irssi::settings_get_bool("twirssi_debug");
1265 }
1266
1267 sub notice {
1268     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1269 }
1270
1271 sub ccrap {
1272     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1273 }
1274
1275 sub update_away {
1276     my $data = shift;
1277
1278     if (    Irssi::settings_get_bool("tweet_to_away")
1279         and $data !~ /\@\w/
1280         and $data !~ /^[dD] / )
1281     {
1282         my $server =
1283           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1284         if ($server) {
1285             $server->send_raw("away :$data");
1286             return 1;
1287         } else {
1288             &ccrap( "Can't find bitlbee server.",
1289                 "Update bitlbee_server or disable tweet_to_away" );
1290             return 0;
1291         }
1292     }
1293
1294     return 0;
1295 }
1296
1297 sub too_long {
1298     my $data    = shift;
1299     my $noalert = shift;
1300
1301     if ( length $data > 140 ) {
1302         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1303           unless $noalert;
1304         return 1;
1305     }
1306
1307     return 0;
1308 }
1309
1310 sub valid_username {
1311     my $username = shift;
1312
1313     $username = &normalize_username($username);
1314
1315     unless ( exists $twits{$username} ) {
1316         &notice("Unknown username $username");
1317         return undef;
1318     }
1319
1320     return $username;
1321 }
1322
1323 sub logged_in {
1324     my $obj = shift;
1325     unless ($obj) {
1326         &notice("Not logged in!  Use /twitter_login username pass!");
1327         return 0;
1328     }
1329
1330     return 1;
1331 }
1332
1333 sub sig_complete {
1334     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1335
1336     if (
1337         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1338         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1339             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1340       )
1341     {    # /twitter_reply gets a nick:num
1342         $word =~ s/^@//;
1343         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1344           sort { $nicks{$b} <=> $nicks{$a} }
1345           grep /^\Q$word/i,
1346           keys %{ $id_map{__indexes} };
1347     }
1348
1349     if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1350     {    # /twitter_unfriend gets a nick
1351         $word =~ s/^@//;
1352         push @$complist, grep /^\Q$word/i,
1353           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1354     }
1355
1356     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1357     # arg to dm)
1358     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1359         my $prefix = $word =~ s/^@//;
1360         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1361         push @$complist, grep /^\Q$word/i,
1362           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1363         @$complist = map { "\@$_" } @$complist if $prefix;
1364     }
1365 }
1366
1367 sub event_send_text {
1368     my ( $line, $server, $win ) = @_;
1369     my $awin = Irssi::active_win();
1370
1371     # if the window where we got our text was the twitter window, and the user
1372     # wants to be lazy, tweet away!
1373     if ( ( $awin->get_active_name() eq $window->{name} )
1374         and Irssi::settings_get_bool("tweet_window_input") )
1375     {
1376         &cmd_tweet( $line, $server, $win );
1377     }
1378 }
1379
1380 sub get_poll_time {
1381     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1382     return $poll if $poll >= 60;
1383     return 60;
1384 }
1385
1386 sub hilight {
1387     my $text = shift;
1388
1389     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1390         my $c = Irssi::settings_get_str("twirssi_nick_color");
1391         $c = $irssi_to_mirc_colors{$c};
1392         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1393     }
1394     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1395         my $c = Irssi::settings_get_str("twirssi_topic_color");
1396         $c = $irssi_to_mirc_colors{$c};
1397         $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1398     }
1399     $text =~ s/[\n\r]/ /g;
1400
1401     return $text;
1402 }
1403
1404 sub shorten {
1405     my $data = shift;
1406
1407     my $provider = Irssi::settings_get_str("short_url_provider");
1408     if (
1409         (
1410             Irssi::settings_get_bool("twirssi_always_shorten")
1411             or &too_long( $data, 1 )
1412         )
1413         and $provider
1414       )
1415     {
1416         my @args;
1417         if ( $provider eq 'Bitly' ) {
1418             @args[ 1, 2 ] = split ',',
1419               Irssi::settings_get_str("short_url_args"), 2;
1420             unless ( @args == 3 ) {
1421                 &ccrap(
1422                     "WWW::Shorten::Bitly requires a username and API key.",
1423                     "Set short_url_args to username,API_key or change your",
1424                     "short_url_provider."
1425                 );
1426                 return $data;
1427             }
1428         }
1429
1430         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1431             eval {
1432                 $args[0] = $url;
1433                 my $short = makeashorterlink(@args);
1434                 if ($short) {
1435                     $data =~ s/\Q$url/$short/g;
1436                 } else {
1437                     &notice("Failed to shorten $url!");
1438                 }
1439             };
1440         }
1441     }
1442
1443     return decode "utf8", $data;
1444 }
1445
1446 sub normalize_username {
1447     my $user = shift;
1448
1449     my ( $username, $service ) = split /\@/, $user, 2;
1450     if ($service) {
1451         $service = ucfirst lc $service;
1452     } else {
1453         $service =
1454           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1455         unless ( exists $twits{"$username\@$service"} ) {
1456             $service = undef;
1457             foreach my $t ( sort keys %twits ) {
1458                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1459                 $service = $1;
1460                 last;
1461             }
1462
1463             unless ($service) {
1464                 &notice("Can't find a logged in user '$user'");
1465             }
1466         }
1467     }
1468
1469     return "$username\@$service";
1470 }
1471
1472 Irssi::signal_add( "send text", "event_send_text" );
1473
1474 Irssi::theme_register(
1475     [
1476         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1477         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1478         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1479         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1480         'twirssi_error',  'ERROR: $0',
1481     ]
1482 );
1483
1484 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1485 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1486 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1487 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1488 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1489 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1490 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1491 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1492 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1493 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1494 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1495     'RT $n: "$t" ${-- $c$}' );
1496 Irssi::settings_add_str( "twirssi", "twirssi_location",
1497     ".irssi/scripts/twirssi.pl" );
1498 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1499     ".irssi/scripts/twirssi.json" );
1500
1501 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1502
1503 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1504 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1505 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1506 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1507 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1508 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1509 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1510 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1511 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1512 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1513 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1514 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1515 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1516
1517 $last_poll = time - &get_poll_time;
1518 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1519 if ( !$window ) {
1520     Irssi::active_win()
1521       ->print( "Couldn't find a window named '"
1522           . Irssi::settings_get_str('twitter_window')
1523           . "', trying to create it." );
1524     $window =
1525       Irssi::Windowitem::window_create(
1526         Irssi::settings_get_str('twitter_window'), 1 );
1527     $window->set_name( Irssi::settings_get_str('twitter_window') );
1528 }
1529
1530 if ($window) {
1531     Irssi::command_bind( "dm",                         "cmd_direct" );
1532     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1533     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1534     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1535     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1536     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1537     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1538     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1539     Irssi::command_bind( "twitter_login",              "cmd_login" );
1540     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1541     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1542     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1543     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1544     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1545     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1546     Irssi::command_bind( "twitter_updates",            "get_updates" );
1547     Irssi::command_bind( "bitlbee_away",               "update_away" );
1548     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1549         Irssi::command_bind( "reply",    "cmd_reply" );
1550         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1551     }
1552     Irssi::command_bind(
1553         "twirssi_dump",
1554         sub {
1555             print "twits: ", join ", ",
1556               map { "u: $_->{username}\@" . ref($_) } values %twits;
1557             print "selected: $user\@$defservice";
1558             print "friends: ", join ", ", sort keys %friends;
1559             print "nicks: ",   join ", ", sort keys %nicks;
1560             print "searches: ", Dumper \%{ $id_map{__searches} };
1561             print "last poll: $last_poll";
1562             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1563                 print DUMP Dumper \%tweet_cache;
1564                 close DUMP;
1565                 print "cache written out to /tmp/twirssi.cache.txt";
1566             }
1567         }
1568     );
1569     Irssi::command_bind(
1570         "twirssi_version",
1571         sub {
1572             &notice("Twirssi v$VERSION (r$REV); "
1573                   . "Net::Twitter v$Net::Twitter::VERSION. "
1574                   . "JSON in use: "
1575                   . JSON::Any::handler()
1576                   . ".  See details at http://twirssi.com/" );
1577         }
1578     );
1579     Irssi::command_bind(
1580         "twitter_follow",
1581         &gen_cmd(
1582             "/twitter_follow <username>",
1583             "create_friend",
1584             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1585         )
1586     );
1587     Irssi::command_bind(
1588         "twitter_unfollow",
1589         &gen_cmd(
1590             "/twitter_unfriend <username>",
1591             "destroy_friend",
1592             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1593         )
1594     );
1595     Irssi::command_bind(
1596         "twitter_device_updates",
1597         &gen_cmd(
1598             "/twitter_device_updates none|im|sms",
1599             "update_delivery_device",
1600             sub { &notice("Device updated to $_[0]"); }
1601         )
1602     );
1603     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1604
1605     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1606     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1607     &notice(
1608         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1609
1610     my $file = Irssi::settings_get_str("twirssi_replies_store");
1611     if ( $file and -r $file ) {
1612         if ( open( JSON, $file ) ) {
1613             local $/;
1614             my $json = <JSON>;
1615             close JSON;
1616             eval {
1617                 my $ref = JSON::Any->jsonToObj($json);
1618                 %id_map = %$ref;
1619                 my $num = keys %{ $id_map{__indexes} };
1620                 &notice( sprintf "Loaded old replies from %d contact%s.",
1621                     $num, ( $num == 1 ? "" : "s" ) );
1622                 &cmd_list_search;
1623             };
1624         } else {
1625             &notice("Failed to load old replies from $file: $!");
1626         }
1627     }
1628
1629     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1630         &notice("Loading WWW::Shorten::$provider...");
1631         eval "use WWW::Shorten::$provider;";
1632
1633         if ($@) {
1634             &notice(
1635                 "Failed to load WWW::Shorten::$provider - either clear",
1636                 "short_url_provider or install the CPAN module"
1637             );
1638         }
1639     }
1640
1641     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1642         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1643     {
1644         &cmd_login();
1645         &get_updates;
1646     }
1647
1648 } else {
1649     Irssi::active_win()
1650       ->print( "Create a window named "
1651           . Irssi::settings_get_str('twitter_window')
1652           . " or change the value of twitter_window.  Then, reload twirssi." );
1653 }
1654
1655 # vim: set sts=4 expandtab: