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