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