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+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 str = CGI.escape(rawstr)
37 str << ";site=aka" if @bot.config['imdb.aka']
39 opts[:type] = :both unless opts[:type]
40 return do_search(str, opts)
43 def do_search(str, opts={})
46 resp = @bot.httputil.get_response(IMDB + "/find?q=#{str}",
50 warning e.backtrace.join("\n")
55 matcher = MATCHER[opts[:type]]
59 return resp.body.scan(matcher).map { |m| m.first }.compact.uniq
62 m << matcher.match(resp.body) if @bot.config['imdb.popular']
63 if resp.body.match(/\(Exact Matches\)<\/b>/) and @bot.config['imdb.exact']
64 m << matcher.match($')
72 elsif resp.code == "302"
73 debug "automatic redirection"
74 new_loc = resp['location'].gsub(IMDB, "")
75 if new_loc.match(/\/find\?q=(.*)/)
76 return do_search($1, opts)
78 return [new_loc.gsub(/\?.*/, "")]
84 def info(rawstr, opts={})
86 urls = search(rawstr, opts)
89 debug "IMDB: search returned NIL"
94 type = sr.match(/^\/([^\/]+)\//)[1].downcase.intern rescue nil
97 results << info_title(sr, opts)
99 results << info_name(sr, opts)
107 def grab_info(info, body)
108 /<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
111 def fix_article(org_tit)
114 if title.match(/^"(.*)"$/)
115 return "\"#{fix_article($1)}\""
117 if @bot.config['imdb.fix_article'] and title.gsub!(FINAL_ARTICLE_MATCH, '')
120 if art[-1,1].match(/[A-Za-z]/)
128 def info_title(sr, opts={})
131 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
132 rescue Exception => e
134 warning e.backtrace.join("\n")
140 if resp.code == "200"
141 m = /<title>([^<]*)<\/title>/.match(resp.body)
143 title_date = m[1].ircify_html
145 # note that the date dash for series is a - (ndash), not a - (minus sign)
146 pre_title, extra, date, junk = title_date.scan(/^(.*)\((.+?\s+)?(\d\d\d\d(?:–(?:\d\d\d\d)?)?(?:\/[IV]+)?)\)\s*(.+)?$/).first
147 extra.strip! if extra
149 title = fix_article(pre_title)
152 data = grab_info(/(?:Director|Creator)s?/, resp.body)
154 dir = data.scan(NAME_MATCH).map { |url, name|
160 data = grab_info(/Country/, resp.body)
162 country = data.ircify_html.gsub(' / ','/')
165 info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, opts[:nourl] ? nil : ": http://www.imdb.com#{sr}"].compact.join(" ")
167 return info if opts[:title_only]
170 info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
171 "%s: %s" % [name, role.ircify_html]
177 m = resp.body.match(/<b>([0-9.]+)<\/b><span [^>]+>\/10<\/span><\/span>\s*[^<]+<a\s+[^>]*href="ratings"[^>]+>([0-9,]+) votes?<\/a>/m)
179 ratings = "#{m[1]}/10 (#{m[2]} voters)"
183 resp.body.scan(/<a href="\/genre\/[^"]+">([^<]+)<\/a>/) do |gnr|
187 plot = resp.body.match(DESC_MATCH)[3] rescue nil
188 # TODO option to extract the long storyline
189 # data = resp.body.match(/<h2>Storyline<\/h2>\s+/m).post_match.match(/<\/p>/).pre_match rescue nil
191 # data.sub!(/<em class="nobr">Written by.*$/m, '')
192 # plot = data.ircify_html.gsub(/\s+more\s*$/,'').gsub(/\s+Full summary » \| Full synopsis »\s*$/,'')
194 plot = "Plot: #{plot}" if plot
196 info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
203 def info_name(sr, opts={})
206 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
207 rescue Exception => e
209 warning e.backtrace.join("\n")
215 if resp.code == "200"
216 m = /<title>([^<]*)<\/title>/.match(resp.body)
218 name = m[1].sub(/ - IMDb/, '')
221 info.last << " : http://www.imdb.com#{sr}" unless opts[:nourl]
223 return info if opts[:name_only]
225 if opts[:movies_by_year]
226 filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
228 info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
234 data = grab_info("Date of Birth", resp.body)
236 birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
240 data = grab_info("Date of Death", resp.body)
242 death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
245 info << [birth, death].compact.join('. ') if birth or death
251 filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
256 filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
257 what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
259 movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
260 fix_article(tit.ircify_html)
265 preferred = ['Actor', 'Director']
266 if resp.body.match(/Jump to filmography as: (.*?)<\/div>/)
268 preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
274 all_keys = movies.keys.sort
275 debug all_keys.inspect
277 preferred.each { |key|
278 keys << key if all_keys.include? key
280 keys = all_keys if keys.empty?
284 ar.last << ": " + movies[key].join('; ')
286 info << ar.join('. ')
294 def year_movies(urls, years_txt_org, role_req)
295 years_txt = years_txt_org.dup
296 years_txt.sub!(/^'/,'')
297 years_txt = "9#{years_txt}" if years_txt.match(/^\d\ds?$/)
298 years_txt = "1#{years_txt}" if years_txt.match(/^\d\d\ds?$/)
306 base.upto(base+9) { |year|
312 info = info_name(url, :movies_by_year => true)
316 name_url = info.first
320 # Sort by pre-title putting movies before TV series
325 (aclip == quot ? 1 : -1) <=> (bclip == quot ? 1 : -1)
326 }.each { |url, pre_title, year, pre_roles|
327 next unless years.include?(year)
328 title = fix_article(pre_title.ircify_html)
329 if title[0] == ?" and not @bot.config['imdb.tv_series_in_movies']
332 title << " (#{year})" unless years.length == 1
334 pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
337 if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
339 extra = "(#{$2.ircify_html})"
343 next if role_req and not role.match(/^#{role_req}/i)
346 extra += comm.ircify_html if comm
348 role_array << [role, extra]
350 next if role_req and role_array.empty?
352 roles = role_array.map { |ar|
354 ar[1] # works for us both if it's nil and if it's something
359 roles = nil if roles.empty?
360 movies << [roles, title].compact.join(": ")
366 [name_url, movies.join(" | ")]
371 def name_in_movie(name_urls, movie_urls)
374 movie_urls.each { |movie|
375 title_info = info_title(movie, :title_only => true)
378 data = @bot.httputil.get(IMDB + movie + "fullcredits")
379 data.scan(CREDIT_NAME_MATCH).each { |url, name, role_data|
380 ch_url, role = role_data.scan(CHAR_MATCH).first
382 wanted = name_urls.include?(url) || name_urls.include?(ch_url)
383 valid << [url, name.ircify_html, role.ircify_html] if wanted
385 valid.each { |url, name, role|
386 info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
395 class ImdbPlugin < Plugin
396 Config.register Config::BooleanValue.new('imdb.aka',
398 :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
399 Config.register Config::BooleanValue.new('imdb.popular',
401 :desc => "Display info on popular IMDB entries matching the request closely")
402 Config.register Config::BooleanValue.new('imdb.exact',
404 :desc => "Display info on IMDB entries matching the request exactly")
405 Config.register Config::BooleanValue.new('imdb.fix_article',
407 :desc => "Try to detect an article placed at the end and move it in front of the title")
408 Config.register Config::BooleanValue.new('imdb.tv_series_in_movies',
410 :desc => "Whether searching movies by person/year should also return TV series")
412 def help(plugin, topic="")
415 "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\""
417 "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>"
419 "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"
425 TITLE_URL = %r{^http://(?:[^.]+\.)?imdb.com(/title/tt\d+/)}
426 NAME_URL = %r{^http://(?:[^.]+\.)?imdb.com(/name/nm\d+/)}
428 loc = Utils.check_location(s, TITLE_URL)
430 sr = loc.first.match(TITLE_URL)[1]
431 extra = $2 # nothign for the time being, could be fullcredits or whatever
432 res = i.info_title(sr, :nourl => true, :characters => (extra == 'fullcredits'))
435 return {:title => res.first, :content => res.last}
440 loc = Utils.check_location(s, NAME_URL)
442 sr = loc.first.match(NAME_URL)[1]
443 extra = $2 # nothing for the time being, could be filmoyear or whatever
444 res = i.info_name(sr, :nourl => true, :movies_by_year => (extra == 'filmoyear'))
448 return {:title => name, :content => res.join(". ")}
459 @bot.register_filter(:imdb, :htmlinfo) { |s| imdb_filter(s) }
462 # Find a person or movie on IMDB. A :type (name/title, default both) can be
463 # specified to limit the search to either.
467 movie = params[:movie].to_s
468 info = i.info(movie, :type => :title, :characters => true)
470 what = params[:what].to_s
471 type = params[:type].intern
472 info = i.info(what, :type => type)
474 m.reply "nothing found for #{what}"
479 m.reply Utils.decode_html_entities(info.first.join("\n"))
481 m.reply info.map { |si|
482 Utils.decode_html_entities si.join(" | ")
487 # Find the movies with a participation of :who in the year :year
488 # TODO: allow year to be either a year or a decade ('[in the] 1960s')
490 def movies(m, params)
491 who = params[:who].to_s
492 years = params[:years]
494 if role and role.downcase == 'anything'
497 case params[:prefix].intern
499 role = /actor|actress/i
505 name_urls = i.search(who, :type => :name)
507 m.reply "nothing found about #{who}, sorry"
511 movie_urls = i.year_movies(name_urls, years, role)
512 debug movie_urls.inspect
513 debug movie_urls[0][1]
515 if movie_urls.length == 1 and movie_urls[0][1]
516 m.reply movie_urls.join("\n")
518 m.reply movie_urls.map { |si|
519 si[1] = "no movies in #{years}" unless si[1]
520 Utils.decode_html_entities si.join(" | ")
525 # Find the character played by :who in :movie
527 def character(m, params)
528 movie = params[:movie].to_s
529 movie_urls = i.search(movie, :type => :title)
531 m.reply "movie #{who} not found, sorry"
536 who = params[:actor].to_s
539 who = params[:character].to_s
543 name_urls = i.search(who, :type => type, :all => true)
545 m.reply "nothing found about #{who}, sorry"
549 info = i.name_in_movie(name_urls, movie_urls)
551 m.reply "nothing found about #{who} in #{movie}, sorry"
553 m.reply info.join("\n")
557 # Report the characters in movie :movie
559 def characters(m, params)
560 movie = params[:movie].to_s
562 urls = i.search(movie, :type => :title)
564 m.reply "nothing found about #{movie}"
571 plugin = ImdbPlugin.new
573 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
574 plugin.map "movies :prefix *who in [the] :years [as :role]", :requirements => { :prefix => /with|by|from/, :years => /'?\d+s?/ }
575 plugin.map "character [played] by *actor in *movie"
576 plugin.map "character of *character in *movie"
577 plugin.map "characters in *movie", :action => :imdb