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