1use strict;
2use Irssi;
3use LWP::UserAgent;
4use HTML::Entities;
5use vars qw($VERSION %IRSSI $cache);
6
7$VERSION = '1.02';
8%IRSSI = (
9    authors 	=> 'Eric Jansen',
10    contact 	=> 'chaos@sorcery.net',
11    name 	=> 'imdb',
12    description => 'Automatically lookup IMDB-numbers in nicknames',
13    license 	=> 'GPL',
14    modules	=> 'LWP::UserAgent HTML::Entities',
15    url		=> 'http://xyrion.org/irssi/',
16    changed 	=> '2018-06-14'
17);
18
19my $ua = new LWP::UserAgent;
20$ua->agent('Irssi; ' . $ua->agent);
21
22# Set the timeout to five second, so it won't freeze the client too long on laggy connections
23$ua->timeout(5);
24
25sub event_nickchange {
26
27    my ($channel, $nick, $old_nick) = @_;
28
29    # Lookup any 7-digit number in someone elses nick
30    if($nick->{'nick'} ne $channel->{'ownnick'}->{'nick'} && $nick->{'nick'} =~ /\D(\d{7})(?:\D|$)/) {
31
32	my $id = $1;
33
34	# See if we know the title already
35	if(defined $cache->{$id}) {
36
37	    # Print it
38	    $channel->printformat(MSGLEVEL_CRAP, 'imdb_lookup', $old_nick, $cache->{$id}->{'title'}, $cache->{$id}->{'year'});
39	}
40
41	# Otherwise, contact IMDB
42	else {
43
44	    # Fetch the movie detail page
45	    my $req = new HTTP::Request(GET => "http://us.imdb.com/title/tt$id");
46	    my $res = $ua->request($req);
47
48	    # Get the title and year from the fetched page
49	    if($res->is_success
50		&& $res->content  =~ /<title>(.+?) \((.+)\).*<\/title>/) {
51
52	# https://www.imdb.com/title/tt1234567/
53	# <title>&quot;So You Think You Can Dance&quot; The Top 14 Perform (TV Episode 2008) - IMDb</title>
54	# https://www.imdb.com/title/tt0234567/
55	# <title>The Ranchman's Nerve (1911) - IMDb</title>
56
57		my ($title, $year) = ($1, $2);
58
59		# Decode special characters in the title
60		$title= decode_entities($title);
61
62		# Print it
63		$channel->printformat(MSGLEVEL_CRAP, 'imdb_lookup', $old_nick, $title, $year);
64
65		# And cache it
66		$cache->{$id} = {
67		    'title'	=> $title,
68		    'year'	=> $year
69		};
70	    }
71	}
72    }
73}
74
75Irssi::theme_register([
76    'imdb_lookup', '{nick $0} is watching {hilight $1} ($2)'
77]);
78Irssi::signal_add('nicklist changed', 'event_nickchange');
79