4 # :title: IMDB plugin for rbot
6 # Author:: Arnaud Cornet <arnaud.cornet@gmail.com>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
9 # Copyright:: (C) 2005 Arnaud Cornet
10 # Copyright:: (C) 2007 Giuseppe Bilotta
12 # License:: MIT license
15 IMDB = "http://www.imdb.com"
16 TITLE_OR_NAME_MATCH = /<a\s+href="(\/(?:title|name)\/(?:tt|nm)[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
17 TITLE_MATCH = /<a\s+href="(\/title\/tt[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
18 NAME_MATCH = /<a\s+onclick="[^"]+"\s+href="(\/name\/nm[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
19 CHAR_MATCH = /<a\s+href="(\/character\/ch[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
20 CREDIT_NAME_MATCH = /#{NAME_MATCH}\s*<\/td>\s*<td[^>]+>\s*\.\.\.\s*<\/td>\s*<td[^>]+>\s*(.+?)\s*<\/td>/m
21 FINAL_ARTICLE_MATCH = /, ([A-Z]\S{0,2})$/
22 DESC_MATCH = /<meta name="description" content="(.*?)\. (.*?)\. (.*?)\."\s*\/>/
25 :character => CHAR_MATCH,
26 :title => TITLE_MATCH,
28 :both => TITLE_OR_NAME_MATCH
35 def search(rawstr, rawopts={})
36 # allow the user to search directly for (movie) IDs
37 if rawstr.match /$tt\d+^/ then
38 return ["/movie/#{rawstr}/"]
40 str = CGI.escape(rawstr)
41 str << "&site=aka" if @bot.config['imdb.aka']
43 opts[:type] = :both unless opts[:type]
44 return do_search(str, opts)
47 def do_search(str, opts={})
50 resp = @bot.httputil.get_response(IMDB + "/find?q=#{str}",
54 warning e.backtrace.join("\n")
59 matcher = MATCHER[opts[:type]]
63 return resp.body.scan(matcher).map { |m| m.first }.compact.uniq
66 m << matcher.match(resp.body) if @bot.config['imdb.popular']
67 if resp.body.match(/\(Exact Matches\)<\/b>/) and @bot.config['imdb.exact']
68 m << matcher.match($')
76 elsif resp.code == "302"
77 debug "automatic redirection"
78 new_loc = resp['location'].gsub(IMDB, "")
79 if new_loc.match(/\/find\?q=(.*)/)
80 return do_search($1, opts)
82 return [new_loc.gsub(/\?.*/, "")]
88 def info(rawstr, opts={})
90 urls = search(rawstr, opts)
93 debug "IMDB: search returned NIL"
98 type = sr.match(/^\/([^\/]+)\//)[1].downcase.intern rescue nil
101 results << info_title(sr, opts)
103 results << info_name(sr, opts)
111 def grab_info(info, body)
112 /<div (?:id="\S+-info" )?class="(?:txt-block|see-more inline canwrap)">\s*<h[45](?: class="inline")?>\s*#{info}:\s*<\/h[45]>\s*(.*?)<\/div>/mi.match(body)[1] rescue nil
115 def fix_article(org_tit)
118 if title.match(/^"(.*)"$/)
119 return "\"#{fix_article($1)}\""
121 if @bot.config['imdb.fix_article'] and title.gsub!(FINAL_ARTICLE_MATCH, '')
124 if art[-1,1].match(/[A-Za-z]/)
132 def info_title(sr, opts={})
135 # movie urls without tailing / trigger a redirect
136 sr += '/' if sr[-1,1] != '/'
137 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
138 rescue Exception => e
140 warning e.backtrace.join("\n")
146 if resp.code == "200"
147 m = /<title>([^<]*)<\/title>/.match(resp.body)
149 title_date = m[1].ircify_html
151 # note that the date dash for series is a - (ndash), not a - (minus sign)
152 # also, the second date, if missing, is an no-break space
153 pre_title, extra, date, junk = title_date.scan(/^(.*)\((.+?\s+)?(\d\d\d\d(?:–(?:\d\d\d\d| )?)?(?:\/[IV]+)?)\)\s*(.+)?$/).first
154 extra.strip! if extra
156 title = fix_article(pre_title)
159 data = grab_info(/(?:Director|Creator)s?/, resp.body)
161 dir = data.scan(NAME_MATCH).map { |url, name|
167 data = grab_info(/Country/, resp.body)
169 country = data.ircify_html.gsub(' / ','/')
172 info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, opts[:nourl] ? nil : ": http://www.imdb.com#{sr}"].compact.join(" ")
174 return info if opts[:title_only]
177 info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
178 "%s: %s" % [name, role.ircify_html]
184 # parse imdb rating value:
185 if resp.body.match(/itemprop="ratingValue">([^<]+)</)
188 # parse imdb rating count:
189 if resp.body.match(/itemprop="ratingCount">([^<]+)</)
190 ratings += " (#{$1} voters)"
194 resp.body.scan(/<a\s+href="\/genre\/[^\?]+\?[^"]+"\s+>([^<]+)<\/a>/) do |gnr|
195 genre << gnr.first.strip
198 plot = resp.body.match(DESC_MATCH)[3] rescue nil
199 # TODO option to extract the long storyline
200 # data = resp.body.match(/<h2>Storyline<\/h2>\s+/m).post_match.match(/<\/p>/).pre_match rescue nil
202 # data.sub!(/<em class="nobr">Written by.*$/m, '')
203 # plot = data.ircify_html.gsub(/\s+more\s*$/,'').gsub(/\s+Full summary » \| Full synopsis »\s*$/,'')
205 plot = "Plot: #{plot}" if plot
207 info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
214 def info_name(sr, opts={})
217 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
218 rescue Exception => e
220 warning e.backtrace.join("\n")
226 if resp.code == "200"
227 m = /<title>([^<]*)<\/title>/.match(resp.body)
229 name = m[1].sub(/ - IMDb/, '')
232 info.last << " : http://www.imdb.com#{sr}" unless opts[:nourl]
234 return info if opts[:name_only]
236 if opts[:movies_by_year]
237 filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
239 info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
245 data = grab_info("Date of Birth", resp.body)
247 birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
251 data = grab_info("Date of Death", resp.body)
253 death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
256 info << [birth, death].compact.join('. ') if birth or death
262 filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
267 filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
268 what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
270 movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
271 fix_article(tit.ircify_html)
276 preferred = ['Actor', 'Director']
277 if resp.body.match(/Jump to filmography as: (.*?)<\/div>/)
279 preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
285 all_keys = movies.keys.sort
286 debug all_keys.inspect
288 preferred.each { |key|
289 keys << key if all_keys.include? key
291 keys = all_keys if keys.empty?
295 ar.last << ": " + movies[key].join('; ')
297 info << ar.join('. ')
305 def year_movies(urls, years_txt_org, role_req)
306 years_txt = years_txt_org.dup
307 years_txt.sub!(/^'/,'')
308 years_txt = "9#{years_txt}" if years_txt.match(/^\d\ds?$/)
309 years_txt = "1#{years_txt}" if years_txt.match(/^\d\d\ds?$/)
317 base.upto(base+9) { |year|
323 info = info_name(u, :movies_by_year => true)
327 name_url = info.first
331 # Sort by pre-title putting movies before TV series
336 (aclip == quot ? 1 : -1) <=> (bclip == quot ? 1 : -1)
337 }.each { |url, pre_title, year, pre_roles|
338 next unless years.include?(year)
339 title = fix_article(pre_title.ircify_html)
340 if title[0] == ?" and not @bot.config['imdb.tv_series_in_movies']
343 title << " (#{year})" unless years.length == 1
345 pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
348 if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
350 extra = "(#{$2.ircify_html})"
354 next if role_req and not role.match(/^#{role_req}/i)
357 extra += comm.ircify_html if comm
359 role_array << [role, extra]
361 next if role_req and role_array.empty?
363 roles = role_array.map { |ar|
365 ar[1] # works for us both if it's nil and if it's something
370 roles = nil if roles.empty?
371 movies << [roles, title].compact.join(": ")
377 [name_url, movies.join(" | ")]
382 def name_in_movie(name_urls, movie_urls)
385 movie_urls.each { |movie|
386 title_info = info_title(movie, :title_only => true)
389 data = @bot.httputil.get(IMDB + movie + "fullcredits")
390 data.scan(CREDIT_NAME_MATCH).each { |url, name, role_data|
391 ch_url, role = role_data.scan(CHAR_MATCH).first
393 wanted = name_urls.include?(url) || name_urls.include?(ch_url)
394 valid << [url, name.ircify_html, role.ircify_html] if wanted
396 valid.each { |url, name, role|
397 info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
406 class ImdbPlugin < Plugin
407 Config.register Config::BooleanValue.new('imdb.aka',
409 :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
410 Config.register Config::BooleanValue.new('imdb.popular',
412 :desc => "Display info on popular IMDB entries matching the request closely")
413 Config.register Config::BooleanValue.new('imdb.exact',
415 :desc => "Display info on IMDB entries matching the request exactly")
416 Config.register Config::BooleanValue.new('imdb.fix_article',
418 :desc => "Try to detect an article placed at the end and move it in front of the title")
419 Config.register Config::BooleanValue.new('imdb.tv_series_in_movies',
421 :desc => "Whether searching movies by person/year should also return TV series")
423 def help(plugin, topic="")
426 "movies by <who> in <years> [as <role>] => display the movies in the <years> where which <who> was <role>; <role> can be one of actor, actress, director or anything: if it's omitted, the role is defined by the prefix: \"movies by ...\" implies director, \"movies with ...\" implies actor or actress; the years can be specified as \"in the 60s\" or as \"in 1953\""
428 "character played by <who> in <movie> => show the character played by <who> in movie <movie>. characters in <movie> => show the actors and characters in movie <movie>"
430 "imdb <string> => search http://www.imdb.org for <string>: prefix <string> with 'name' or 'title' if you only want to search for people or films respectively, e.g.: imdb name ed wood. see also movies and characters"
436 TITLE_URL = %r{^http://(?:[^.]+\.)?imdb.com(/title/tt\d+/)}
437 NAME_URL = %r{^http://(?:[^.]+\.)?imdb.com(/name/nm\d+/)}
439 loc = Utils.check_location(s, TITLE_URL)
441 sr = loc.first.match(TITLE_URL)[1]
442 extra = $2 # nothign for the time being, could be fullcredits or whatever
443 res = i.info_title(sr, :nourl => true, :characters => (extra == 'fullcredits'))
446 return {:title => res.first, :content => res.last}
451 loc = Utils.check_location(s, NAME_URL)
453 sr = loc.first.match(NAME_URL)[1]
454 extra = $2 # nothing for the time being, could be filmoyear or whatever
455 res = i.info_name(sr, :nourl => true, :movies_by_year => (extra == 'filmoyear'))
459 return {:title => name, :content => res.join(". ")}
470 @bot.register_filter(:imdb, :htmlinfo) { |s| imdb_filter(s) }
473 # Find a person or movie on IMDB. A :type (name/title, default both) can be
474 # specified to limit the search to either.
478 movie = params[:movie].to_s
479 info = i.info(movie, :type => :title, :characters => true)
481 what = params[:what].to_s
482 type = params[:type].intern
483 info = i.info(what, :type => type)
485 m.reply "nothing found for #{what}"
490 m.reply Utils.decode_html_entities(info.first.join("\n"))
492 m.reply info.map { |si|
493 Utils.decode_html_entities si.join(" | ")
498 # Find the movies with a participation of :who in the year :year
499 # TODO: allow year to be either a year or a decade ('[in the] 1960s')
501 def movies(m, params)
502 who = params[:who].to_s
503 years = params[:years]
505 if role and role.downcase == 'anything'
508 case params[:prefix].intern
510 role = /actor|actress/i
516 name_urls = i.search(who, :type => :name)
518 m.reply "nothing found about #{who}, sorry"
522 movie_urls = i.year_movies(name_urls, years, role)
523 debug movie_urls.inspect
524 debug movie_urls[0][1]
526 if movie_urls.length == 1 and movie_urls[0][1]
527 m.reply movie_urls.join("\n")
529 m.reply movie_urls.map { |si|
530 si[1] = "no movies in #{years}" unless si[1]
531 Utils.decode_html_entities si.join(" | ")
536 # Find the character played by :who in :movie
538 def character(m, params)
539 movie = params[:movie].to_s
540 movie_urls = i.search(movie, :type => :title)
542 m.reply "movie #{who} not found, sorry"
547 who = params[:actor].to_s
550 who = params[:character].to_s
554 name_urls = i.search(who, :type => type, :all => true)
556 m.reply "nothing found about #{who}, sorry"
560 info = i.name_in_movie(name_urls, movie_urls)
562 m.reply "nothing found about #{who} in #{movie}, sorry"
564 m.reply info.join("\n")
568 # Report the characters in movie :movie
570 def characters(m, params)
571 movie = params[:movie].to_s
573 urls = i.search(movie, :type => :title)
575 m.reply "nothing found about #{movie}"
582 plugin = ImdbPlugin.new
584 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
585 plugin.map "movies :prefix *who in [the] :years [as :role]", :requirements => { :prefix => /with|by|from/, :years => /'?\d+s?/ }
586 plugin.map "character [played] by *actor in *movie"
587 plugin.map "character of *character in *movie"
588 plugin.map "characters in *movie", :action => :imdb