r619 - Fixed nick hilighting thanks to a pointer from @g45g
[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: 619 $' =~ /(\d+)/;
15 %IRSSI = (
16     authors     => 'Dan Boger',
17     contact     => 'zigdon@gmail.com',
18     name        => 'twirssi',
19     description => 'Send twitter updates using /tweet.  '
20       . 'Can optionally set your bitlbee /away message to same',
21     license => 'GNU GPL v2',
22     url     => 'http://twirssi.com',
23     changed => '$Date: 2009-04-25 11:08:58 -0700 (Sat, 25 Apr 2009) $',
24 );
25
26 my $window;
27 my $twit;
28 my %twits;
29 my $user;
30 my $defservice;
31 my $poll;
32 my $last_poll;
33 my $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     }
805     print scalar localtime, " - get_updates ends" if &debug;
806 }
807
808 sub do_updates {
809     my ( $fh, $username, $obj, $cache ) = @_;
810
811     my $rate_limit = $obj->rate_limit_status();
812     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
813         &notice("Rate limit exceeded for $username");
814         return undef;
815     }
816
817     print scalar localtime, " - Polling for updates for $username" if &debug;
818     my $tweets;
819     my $new_poll_id = 0;
820     eval {
821         if ( $id_map{__last_id}{$username}{timeline} )
822         {
823             $tweets = $obj->friends_timeline( { count => 100 } );
824         } else {
825             $tweets = $obj->friends_timeline();
826         }
827     };
828
829     if ($@) {
830         print $fh "type:debug Error during friends_timeline call: Aborted.\n";
831         print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
832         return undef;
833     }
834
835     unless ( ref $tweets ) {
836         if ( $obj->can("get_error") ) {
837             my $error = "Unknown error";
838             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
839             unless ($@) { $error = $obj->get_error() }
840             print $fh
841               "type:debug API Error during friends_timeline call: Aborted\n";
842             print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
843
844         } else {
845             print $fh
846               "type:debug API Error during friends_timeline call. Aborted.\n";
847         }
848         return undef;
849     }
850
851     foreach my $t ( reverse @$tweets ) {
852         my $text = decode_entities( $t->{text} );
853         $text = &hilight($text);
854         my $reply = "tweet";
855         if (    Irssi::settings_get_bool("show_reply_context")
856             and $t->{in_reply_to_screen_name} ne $username
857             and $t->{in_reply_to_screen_name}
858             and not exists $friends{ $t->{in_reply_to_screen_name} } )
859         {
860             $nicks{ $t->{in_reply_to_screen_name} } = time;
861             my $context;
862             unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
863                 eval {
864                     $cache->{ $t->{in_reply_to_status_id} } =
865                       $obj->show_status( $t->{in_reply_to_status_id} );
866                 };
867
868             }
869             $context = $cache->{ $t->{in_reply_to_status_id} };
870
871             if ($context) {
872                 my $ctext = decode_entities( $context->{text} );
873                 $ctext = &hilight($ctext);
874                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
875                     $ctext .=
876                         " -- http://twitter.com/$context->{user}{screen_name}"
877                       . "/status/$context->{id}";
878                 }
879                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
880                   $context->{id}, $username,
881                   $context->{user}{screen_name}, $ctext;
882                 $reply = "reply";
883             }
884         }
885         next
886           if $t->{user}{screen_name} eq $username
887               and not Irssi::settings_get_bool("show_own_tweets");
888         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
889             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
890               . "/status/$t->{id}";
891         }
892         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
893           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
894         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
895     }
896     printf $fh "id:%d account:%s type:last_id timeline\n",
897       $new_poll_id, $username;
898
899     print scalar localtime, " - Polling for replies" if &debug;
900     $new_poll_id = 0;
901     eval {
902         if ( $id_map{__last_id}{$username}{reply} )
903         {
904             $tweets = $obj->replies(
905                 { since_id => $id_map{__last_id}{$username}{reply} } )
906               || [];
907         } else {
908             $tweets = $obj->replies() || [];
909         }
910     };
911
912     if ($@) {
913         print $fh "type:debug Error during replies call.  Aborted.\n";
914         return undef;
915     }
916
917     foreach my $t ( reverse @$tweets ) {
918         next
919           if exists $friends{ $t->{user}{screen_name} };
920
921         my $text = decode_entities( $t->{text} );
922         $text = &hilight($text);
923         if ( $t->{truncated} ) {
924             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
925               . "/status/$t->{id}";
926         }
927         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
928           $t->{id}, $username, $t->{user}{screen_name}, $text;
929         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
930     }
931     printf $fh "id:%d account:%s type:last_id reply\n", $new_poll_id, $username;
932
933     print scalar localtime, " - Polling for DMs" if &debug;
934     $new_poll_id = 0;
935     eval {
936         if ( $id_map{__last_id}{$username}{dm} )
937         {
938             $tweets = $obj->direct_messages(
939                 { since_id => $id_map{__last_id}{$username}{dm} } )
940               || [];
941         } else {
942             $tweets = $obj->direct_messages() || [];
943         }
944     };
945
946     if ($@) {
947         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
948         return undef;
949     }
950
951     foreach my $t ( reverse @$tweets ) {
952         my $text = decode_entities( $t->{text} );
953         $text = &hilight($text);
954         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
955           $t->{id}, $username, $t->{sender_screen_name}, $text;
956         $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
957     }
958     printf $fh "id:%d account:%s type:last_id dm\n", $new_poll_id, $username;
959
960     print scalar localtime, " - Polling for subscriptions" if &debug;
961     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
962         my $search;
963         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
964             print $fh "type:debug searching for $topic since ",
965               "$id_map{__searches}{$username}{$topic}\n";
966             eval {
967                 $search = $obj->search(
968                     {
969                         q        => $topic,
970                         since_id => $id_map{__searches}{$username}{$topic}
971                     }
972                 );
973             };
974
975             if ($@) {
976                 print $fh
977                   "type:debug Error during search($topic) call.  Aborted.\n";
978                 return undef;
979             }
980
981             unless ( $search->{max_id} ) {
982                 print $fh "type:debug Invalid search results when searching",
983                   " for $topic. Aborted.\n";
984                 return undef;
985             }
986
987             $id_map{__searches}{$username}{$topic} = $search->{max_id};
988             printf $fh "id:%d account:%s type:searchid topic:%s\n",
989               $search->{max_id}, $username, $topic;
990
991             foreach my $t ( reverse @{ $search->{results} } ) {
992                 my $text = decode_entities( $t->{text} );
993                 $text = &hilight($text);
994                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
995                   $t->{id}, $username, $t->{from_user}, $topic, $text;
996                 $new_poll_id = $t->{id}
997                   if not $new_poll_id
998                       or $t->{id} < $new_poll_id;
999             }
1000         }
1001     }
1002
1003     print scalar localtime, " - Done" if &debug;
1004
1005     return 1;
1006 }
1007
1008 sub monitor_child {
1009     my ($data)   = @_;
1010     my $filename = $data->[0];
1011     my $attempt  = $data->[1];
1012
1013     print scalar localtime, " - checking child log at $filename ($attempt)"
1014       if &debug;
1015     my ($new_last_poll);
1016
1017     # first time we run we don't want to print out *everything*, so we just
1018     # pretend
1019
1020     if ( open FILE, $filename ) {
1021         my @lines;
1022         my %new_cache;
1023         while (<FILE>) {
1024             last if /^__friends__/;
1025             unless (/\n$/) {    # skip partial lines
1026                                 # print "Skipping partial line: $_" if &debug;
1027                 next;
1028             }
1029             chomp;
1030             my $hilight = 0;
1031             my %meta;
1032
1033             foreach my $key (qw/id account nick type topic/) {
1034                 if (s/^$key:(\S+)\s*//) {
1035                     $meta{$key} = $1;
1036                 }
1037             }
1038
1039             if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1040                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1041                     next;
1042                 }
1043
1044                 $new_cache{ $meta{id} } = time;
1045
1046                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1047                     next;
1048                 }
1049             }
1050
1051             my $account = "";
1052             $meta{account} =~ s/\@(\w+)$//;
1053             $meta{service} = $1;
1054             if (
1055                 lc $meta{service} eq
1056                 lc Irssi::settings_get_str("twirssi_default_service") )
1057             {
1058                 $account = "$meta{account}: "
1059                   if lc "$meta{account}\@$meta{service}" ne lc
1060                       "$user\@$defservice";
1061             } else {
1062                 $account = "$meta{account}\@$meta{service}: ";
1063             }
1064
1065             my $marker = "";
1066             if (    $meta{type} ne 'dm'
1067                 and Irssi::settings_get_bool("twirssi_track_replies")
1068                 and $meta{nick}
1069                 and $meta{id} )
1070             {
1071                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1072                 $id_map{ lc $meta{nick} }[$marker]           = $meta{id};
1073                 $id_map{__indexes}{ $meta{nick} }            = $marker;
1074                 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1075                 $marker                                      = ":$marker";
1076             }
1077
1078             my $hilight_color =
1079               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1080             my $nick = "\@$meta{account}";
1081             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1082                 and Irssi::settings_get_bool("twirssi_hilights") )
1083             {
1084                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1085                 $hilight = MSGLEVEL_HILIGHT;
1086             }
1087
1088             if ( $meta{type} =~ /tweet|reply/ ) {
1089                 push @lines,
1090                   [
1091                     ( MSGLEVEL_PUBLIC | $hilight ),
1092                     $meta{type}, $account, $meta{nick}, $marker, $_
1093                   ];
1094             } elsif ( $meta{type} eq 'search' ) {
1095                 push @lines,
1096                   [
1097                     ( MSGLEVEL_PUBLIC | $hilight ),
1098                     $meta{type}, $account, $meta{topic},
1099                     $meta{nick}, $marker,  $_
1100                   ];
1101                 if (
1102                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1103                     and $meta{id} >
1104                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1105                 {
1106                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1107                       $meta{id};
1108                 }
1109             } elsif ( $meta{type} eq 'dm' ) {
1110                 push @lines,
1111                   [
1112                     ( MSGLEVEL_MSGS | $hilight ),
1113                     $meta{type}, $account, $meta{nick}, $_
1114                   ];
1115             } elsif ( $meta{type} eq 'searchid' ) {
1116                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1117                 if (
1118                     not
1119                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1120                     or $meta{id} >=
1121                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1122                 {
1123                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1124                       $meta{id};
1125                 } elsif (&debug) {
1126                     print "Search '$meta{topic}' returned invalid id $meta{id}";
1127                 }
1128             } elsif ( $meta{type} eq 'last_id' ) {
1129                 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1130                   $meta{id}
1131                   if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1132                       $meta{id};
1133             } elsif ( $meta{type} eq 'error' ) {
1134                 push @lines, [ MSGLEVEL_MSGS, $_ ];
1135             } elsif ( $meta{type} eq 'debug' ) {
1136                 print "$_" if &debug,;
1137             } else {
1138                 print "Unknown line type $meta{type}: $_" if &debug,;
1139             }
1140         }
1141
1142         %friends = ();
1143         while (<FILE>) {
1144             if (/^__updated (\d+)$/) {
1145                 $last_friends_poll = $1;
1146                 print "Friend list updated" if &debug;
1147                 next;
1148             }
1149
1150             if (/^-- (\d+)$/) {
1151                 ($new_last_poll) = ($1);
1152                 last;
1153             }
1154             my ( $f, $t ) = split ' ', $_;
1155             $nicks{$f} = $friends{$f} = $t;
1156         }
1157
1158         if ($new_last_poll) {
1159             print "new last_poll    = $new_last_poll" if &debug;
1160             print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1161             if ($first_call) {
1162                 print "First call, not printing updates" if &debug;
1163             } else {
1164                 foreach my $line (@lines) {
1165                     $window->printformat(
1166                         $line->[0],
1167                         "twirssi_" . $line->[1],
1168                         @$line[ 2 .. $#$line ]
1169                     );
1170                 }
1171             }
1172
1173             close FILE;
1174             unlink $filename
1175               or warn "Failed to remove $filename: $!"
1176               unless &debug;
1177
1178             # commit the pending cache lines to the actual cache, now that
1179             # we've printed our output
1180             %tweet_cache = ( %tweet_cache, %new_cache );
1181
1182             # keep enough cached tweets, to make sure we don't show duplicates.
1183             foreach ( keys %tweet_cache ) {
1184                 next if $tweet_cache{$_} >= $last_poll - 3600;
1185                 delete $tweet_cache{$_};
1186             }
1187             $last_poll = $new_last_poll;
1188
1189             # save id_map hash
1190             if ( keys %id_map
1191                 and my $file =
1192                 Irssi::settings_get_str("twirssi_replies_store") )
1193             {
1194                 if ( open JSON, ">$file" ) {
1195                     print JSON JSON::Any->objToJson( \%id_map );
1196                     close JSON;
1197                 } else {
1198                     &ccrap("Failed to write replies to $file: $!");
1199                 }
1200             }
1201             $failwhale  = 0;
1202             $first_call = 0;
1203             return;
1204         }
1205     }
1206
1207     close FILE;
1208
1209     if ( $attempt < 24 ) {
1210         Irssi::timeout_add_once( 5000, 'monitor_child',
1211             [ $filename, $attempt + 1 ] );
1212     } else {
1213         print "Giving up on polling $filename" if &debug;
1214         unlink $filename unless &debug;
1215
1216         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1217
1218         my $since;
1219         my @time = localtime($last_poll);
1220         if ( time - $last_poll < 24 * 60 * 60 ) {
1221             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1222         } else {
1223             $since = scalar localtime($last_poll);
1224         }
1225
1226         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1227             foreach my $whale (
1228                 q{     v  v        v},
1229                 q{     |  |  v     |  v},
1230                 q{     | .-, |     |  |},
1231                 q{  .--./ /  |  _.---.| },
1232                 q{   '-. (__..-"       \\},
1233                 q{      \\          a    |},
1234                 q{       ',.__.   ,__.-'/},
1235                 q{         '--/_.'----'`}
1236               )
1237             {
1238                 &ccrap($whale);
1239             }
1240             $failwhale = 1;
1241         }
1242         &ccrap("Haven't been able to get updated tweets since $since");
1243     }
1244 }
1245
1246 sub debug {
1247     return Irssi::settings_get_bool("twirssi_debug");
1248 }
1249
1250 sub notice {
1251     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1252 }
1253
1254 sub ccrap {
1255     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1256 }
1257
1258 sub update_away {
1259     my $data = shift;
1260
1261     if (    Irssi::settings_get_bool("tweet_to_away")
1262         and $data !~ /\@\w/
1263         and $data !~ /^[dD] / )
1264     {
1265         my $server =
1266           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1267         if ($server) {
1268             $server->send_raw("away :$data");
1269             return 1;
1270         } else {
1271             &ccrap( "Can't find bitlbee server.",
1272                 "Update bitlbee_server or disable tweet_to_away" );
1273             return 0;
1274         }
1275     }
1276
1277     return 0;
1278 }
1279
1280 sub too_long {
1281     my $data    = shift;
1282     my $noalert = shift;
1283
1284     if ( length $data > 140 ) {
1285         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1286           unless $noalert;
1287         return 1;
1288     }
1289
1290     return 0;
1291 }
1292
1293 sub valid_username {
1294     my $username = shift;
1295
1296     $username = &normalize_username($username);
1297
1298     unless ( exists $twits{$username} ) {
1299         &notice("Unknown username $username");
1300         return undef;
1301     }
1302
1303     return $username;
1304 }
1305
1306 sub logged_in {
1307     my $obj = shift;
1308     unless ($obj) {
1309         &notice("Not logged in!  Use /twitter_login username pass!");
1310         return 0;
1311     }
1312
1313     return 1;
1314 }
1315
1316 sub sig_complete {
1317     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1318
1319     if (
1320         $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1321         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1322             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1323       )
1324     {    # /twitter_reply gets a nick:num
1325         $word =~ s/^@//;
1326         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1327           sort { $nicks{$b} <=> $nicks{$a} }
1328           grep /^\Q$word/i,
1329           keys %{ $id_map{__indexes} };
1330     }
1331
1332     if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1333     {    # /twitter_unfriend gets a nick
1334         $word =~ s/^@//;
1335         push @$complist, grep /^\Q$word/i,
1336           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1337     }
1338
1339     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1340     # arg to dm)
1341     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1342         my $prefix = $word =~ s/^@//;
1343         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1344         push @$complist, grep /^\Q$word/i,
1345           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1346         @$complist = map { "\@$_" } @$complist if $prefix;
1347     }
1348 }
1349
1350 sub event_send_text {
1351     my ( $line, $server, $win ) = @_;
1352     my $awin = Irssi::active_win();
1353
1354     # if the window where we got our text was the twitter window, and the user
1355     # wants to be lazy, tweet away!
1356     if ( ( $awin->get_active_name() eq $window->{name} )
1357         and Irssi::settings_get_bool("tweet_window_input") )
1358     {
1359         &cmd_tweet( $line, $server, $win );
1360     }
1361 }
1362
1363 sub get_poll_time {
1364     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1365     return $poll if $poll >= 60;
1366     return 60;
1367 }
1368
1369 sub hilight {
1370     my $text = shift;
1371
1372     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1373         my $c = Irssi::settings_get_str("twirssi_nick_color");
1374         $c = $irssi_to_mirc_colors{$c};
1375         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1376     }
1377     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1378         my $c = Irssi::settings_get_str("twirssi_topic_color");
1379         $c = $irssi_to_mirc_colors{$c};
1380         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1381     }
1382     $text =~ s/[\n\r]/ /g;
1383
1384     return $text;
1385 }
1386
1387 sub shorten {
1388     my $data = shift;
1389
1390     my $provider = Irssi::settings_get_str("short_url_provider");
1391     if (
1392         (
1393             Irssi::settings_get_bool("twirssi_always_shorten")
1394             or &too_long( $data, 1 )
1395         )
1396         and $provider
1397       )
1398     {
1399         my @args;
1400         if ( $provider eq 'Bitly' ) {
1401             @args[ 1, 2 ] = split ',',
1402               Irssi::settings_get_str("short_url_args"), 2;
1403             unless ( @args == 3 ) {
1404                 &ccrap(
1405                     "WWW::Shorten::Bitly requires a username and API key.",
1406                     "Set short_url_args to username,API_key or change your",
1407                     "short_url_provider."
1408                 );
1409                 return $data;
1410             }
1411         }
1412
1413         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1414             eval {
1415                 $args[0] = $url;
1416                 my $short = makeashorterlink(@args);
1417                 if ($short) {
1418                     $data =~ s/\Q$url/$short/g;
1419                 } else {
1420                     &notice("Failed to shorten $url!");
1421                 }
1422             };
1423         }
1424     }
1425
1426     return $data;
1427 }
1428
1429 sub normalize_username {
1430     my $user = shift;
1431
1432     my ( $username, $service ) = split /\@/, $user, 2;
1433     if ($service) {
1434         $service = ucfirst lc $service;
1435     } else {
1436         $service =
1437           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1438         unless ( exists $twits{"$username\@$service"} ) {
1439             $service = undef;
1440             foreach my $t ( sort keys %twits ) {
1441                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1442                 $service = $1;
1443                 last;
1444             }
1445
1446             unless ($service) {
1447                 &notice("Can't find a logged in user '$user'");
1448             }
1449         }
1450     }
1451
1452     return "$username\@$service";
1453 }
1454
1455 Irssi::signal_add( "send text", "event_send_text" );
1456
1457 Irssi::theme_register(
1458     [
1459         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1460         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1461         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1462         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1463         'twirssi_error',  'ERROR: $0',
1464     ]
1465 );
1466
1467 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1468 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1469 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1470 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1471 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1472 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1473 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1474 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1475 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1476 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1477 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1478     'RT $n: "$t" ${-- $c$}' );
1479 Irssi::settings_add_str( "twirssi", "twirssi_location",
1480     ".irssi/scripts/twirssi.pl" );
1481 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1482     ".irssi/scripts/twirssi.json" );
1483
1484 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1485
1486 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1487 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1488 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1489 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1490 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1491 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1492 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1493 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1494 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1495 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1496 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1497 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1498 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1499
1500 $last_poll = time - &get_poll_time;
1501 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1502 if ( !$window ) {
1503     Irssi::active_win()
1504       ->print( "Couldn't find a window named '"
1505           . Irssi::settings_get_str('twitter_window')
1506           . "', trying to create it." );
1507     $window =
1508       Irssi::Windowitem::window_create(
1509         Irssi::settings_get_str('twitter_window'), 1 );
1510     $window->set_name( Irssi::settings_get_str('twitter_window') );
1511 }
1512
1513 if ($window) {
1514     Irssi::command_bind( "dm",                         "cmd_direct" );
1515     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1516     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1517     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1518     Irssi::command_bind( "retweet",                    "cmd_retweet" );
1519     Irssi::command_bind( "retweet_as",                 "cmd_retweet_as" );
1520     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1521     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1522     Irssi::command_bind( "twitter_login",              "cmd_login" );
1523     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1524     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1525     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1526     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1527     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1528     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1529     Irssi::command_bind( "twitter_updates",            "get_updates" );
1530     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1531         Irssi::command_bind( "reply",    "cmd_reply" );
1532         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1533     }
1534     Irssi::command_bind(
1535         "twirssi_dump",
1536         sub {
1537             print "twits: ", join ", ",
1538               map { "u: $_->{username}\@" . ref($_) } values %twits;
1539             print "selected: $user\@$defservice";
1540             print "friends: ", join ", ", sort keys %friends;
1541             print "nicks: ",   join ", ", sort keys %nicks;
1542             print "searches: ", Dumper \%{ $id_map{__searches} };
1543             print "last poll: $last_poll";
1544             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1545                 print DUMP Dumper \%tweet_cache;
1546                 close DUMP;
1547                 print "cache written out to /tmp/twirssi.cache.txt";
1548             }
1549         }
1550     );
1551     Irssi::command_bind(
1552         "twirssi_version",
1553         sub {
1554             &notice("Twirssi v$VERSION (r$REV); "
1555                   . "Net::Twitter v$Net::Twitter::VERSION. "
1556                   . "JSON in use: "
1557                   . JSON::Any::handler()
1558                   . ".  See details at http://twirssi.com/" );
1559         }
1560     );
1561     Irssi::command_bind(
1562         "twitter_friend",
1563         &gen_cmd(
1564             "/twitter_friend <username>",
1565             "create_friend",
1566             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1567         )
1568     );
1569     Irssi::command_bind(
1570         "twitter_unfriend",
1571         &gen_cmd(
1572             "/twitter_unfriend <username>",
1573             "destroy_friend",
1574             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1575         )
1576     );
1577     Irssi::command_bind(
1578         "twitter_device_updates",
1579         &gen_cmd(
1580             "/twitter_device_updates none|im|sms",
1581             "update_delivery_device",
1582             sub { &notice("Device updated to $_[0]"); }
1583         )
1584     );
1585     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1586
1587     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1588     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1589     &notice(
1590         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1591
1592     my $file = Irssi::settings_get_str("twirssi_replies_store");
1593     if ( $file and -r $file ) {
1594         if ( open( JSON, $file ) ) {
1595             local $/;
1596             my $json = <JSON>;
1597             close JSON;
1598             eval {
1599                 my $ref = JSON::Any->jsonToObj($json);
1600                 %id_map = %$ref;
1601                 my $num = keys %{ $id_map{__indexes} };
1602                 &notice( sprintf "Loaded old replies from %d contact%s.",
1603                     $num, ( $num == 1 ? "" : "s" ) );
1604                 &cmd_list_search;
1605             };
1606         } else {
1607             &notice("Failed to load old replies from $file: $!");
1608         }
1609     }
1610
1611     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1612         &notice("Loading WWW::Shorten::$provider...");
1613         eval "use WWW::Shorten::$provider;";
1614
1615         if ($@) {
1616             &notice(
1617                 "Failed to load WWW::Shorten::$provider - either clear",
1618                 "short_url_provider or install the CPAN module"
1619             );
1620         }
1621     }
1622
1623     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1624         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1625     {
1626         &cmd_login();
1627         &get_updates;
1628     }
1629
1630 } else {
1631     Irssi::active_win()
1632       ->print( "Create a window named "
1633           . Irssi::settings_get_str('twitter_window')
1634           . " or change the value of twitter_window.  Then, reload twirssi." );
1635 }
1636
1637 # vim: set sts=4 expandtab: