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