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