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