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