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 CREDIT_NAME_MATCH = /#{NAME_MATCH}\s*<\/td>\s*<td[^>]+>\s*\.\.\.\s*<\/td>\s*<td[^>]+>\s*(.+?)\s*<\/td>/m
20 FINAL_ARTICLE_MATCH = /, ([A-Z]\S{0,2})$/
21 DESC_MATCH = /<meta name="description" content="(.*?)\. (.*?)\. (.*?)\."\s*\/>/
24 :title => TITLE_MATCH,
26 :both => TITLE_OR_NAME_MATCH
33 def search(rawstr, rawopts={})
34 str = CGI.escape(rawstr)
35 str << ";site=aka" if @bot.config['imdb.aka']
37 opts[:type] = :both unless opts[:type]
38 return do_search(str, opts)
41 def do_search(str, opts={})
44 resp = @bot.httputil.get_response(IMDB + "/find?q=#{str}",
48 warning e.backtrace.join("\n")
53 matcher = MATCHER[opts[:type]]
57 m << matcher.match(resp.body) if @bot.config['imdb.popular']
58 if resp.body.match(/\(Exact Matches\)<\/b>/) and @bot.config['imdb.exact']
59 m << matcher.match($')
67 elsif resp.code == "302"
68 debug "automatic redirection"
69 new_loc = resp['location'].gsub(IMDB, "")
70 if new_loc.match(/\/find\?q=(.*)/)
71 return do_search($1, opts)
73 return [new_loc.gsub(/\?.*/, "")]
79 def info(rawstr, opts={})
81 urls = search(rawstr, opts)
84 debug "IMDB: search returned NIL"
89 type = sr.match(/^\/([^\/]+)\//)[1].downcase.intern rescue nil
92 results << info_title(sr, opts)
94 results << info_name(sr, opts)
102 def grab_info(info, body)
103 /<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
106 def fix_article(org_tit)
109 if title.match(/^"(.*)"$/)
110 return "\"#{fix_article($1)}\""
112 if @bot.config['imdb.fix_article'] and title.gsub!(FINAL_ARTICLE_MATCH, '')
115 if art[-1,1].match(/[A-Za-z]/)
123 def info_title(sr, opts={})
126 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
127 rescue Exception => e
129 warning e.backtrace.join("\n")
135 if resp.code == "200"
136 m = /<title>([^<]*)<\/title>/.match(resp.body)
138 title_date = m[1].ircify_html
140 # note that the date dash for series is a - (ndash), not a - (minus sign)
141 pre_title, extra, date, junk = title_date.scan(/^(.*)\((.+?\s+)?(\d\d\d\d(?:–(?:\d\d\d\d)?)?(?:\/[IV]+)?)\)\s*(.+)?$/).first
142 extra.strip! if extra
144 title = fix_article(pre_title)
147 data = grab_info(/(?:Director|Creator)s?/, resp.body)
149 dir = data.scan(NAME_MATCH).map { |url, name|
155 data = grab_info(/Country/, resp.body)
157 country = data.ircify_html.gsub(' / ','/')
160 info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, opts[:nourl] ? nil : ": http://www.imdb.com#{sr}"].compact.join(" ")
162 return info if opts[:title_only]
165 info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
166 "%s: %s" % [name, role.ircify_html]
172 m = resp.body.match(/<b>([0-9.]+)<\/b><span [^>]+>\/10<\/span><\/span>\s*[^<]+<a\s+[^>]*href="ratings"[^>]+>([0-9,]+) votes?<\/a>/m)
174 ratings = "#{m[1]}/10 (#{m[2]} voters)"
178 resp.body.scan(/<a href="\/genre\/[^"]+">([^<]+)<\/a>/) do |gnr|
182 plot = resp.body.match(DESC_MATCH)[3] rescue nil
183 # TODO option to extract the long storyline
184 # data = resp.body.match(/<h2>Storyline<\/h2>\s+/m).post_match.match(/<\/p>/).pre_match rescue nil
186 # data.sub!(/<em class="nobr">Written by.*$/m, '')
187 # plot = data.ircify_html.gsub(/\s+more\s*$/,'').gsub(/\s+Full summary » \| Full synopsis »\s*$/,'')
189 plot = "Plot: #{plot}" if plot
191 info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
198 def info_name(sr, opts={})
201 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
202 rescue Exception => e
204 warning e.backtrace.join("\n")
210 if resp.code == "200"
211 m = /<title>([^<]*)<\/title>/.match(resp.body)
213 name = m[1].sub(/ - IMDb/, '')
216 info.last << " : http://www.imdb.com#{sr}" unless opts[:nourl]
218 return info if opts[:name_only]
220 if opts[:movies_by_year]
221 filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
223 info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
229 data = grab_info("Date of Birth", resp.body)
231 birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
235 data = grab_info("Date of Death", resp.body)
237 death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
240 info << [birth, death].compact.join('. ') if birth or death
246 filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
251 filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
252 what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
254 movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
255 fix_article(tit.ircify_html)
260 preferred = ['Actor', 'Director']
261 if resp.body.match(/Jump to filmography as: (.*?)<\/div>/)
263 preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
269 all_keys = movies.keys.sort
270 debug all_keys.inspect
272 preferred.each { |key|
273 keys << key if all_keys.include? key
275 keys = all_keys if keys.empty?
279 ar.last << ": " + movies[key].join('; ')
281 info << ar.join('. ')
289 def year_movies(urls, years_txt_org, role_req)
290 years_txt = years_txt_org.dup
291 years_txt.sub!(/^'/,'')
292 years_txt = "9#{years_txt}" if years_txt.match(/^\d\ds?$/)
293 years_txt = "1#{years_txt}" if years_txt.match(/^\d\d\ds?$/)
301 base.upto(base+9) { |year|
307 info = info_name(url, :movies_by_year => true)
311 name_url = info.first
315 # Sort by pre-title putting movies before TV series
320 (aclip == quot ? 1 : -1) <=> (bclip == quot ? 1 : -1)
321 }.each { |url, pre_title, year, pre_roles|
322 next unless years.include?(year)
323 title = fix_article(pre_title.ircify_html)
324 if title[0] == ?" and not @bot.config['imdb.tv_series_in_movies']
327 title << " (#{year})" unless years.length == 1
329 pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
332 if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
334 extra = "(#{$2.ircify_html})"
338 next if role_req and not role.match(/^#{role_req}/i)
341 extra += comm.ircify_html if comm
343 role_array << [role, extra]
345 next if role_req and role_array.empty?
347 roles = role_array.map { |ar|
349 ar[1] # works for us both if it's nil and if it's something
354 roles = nil if roles.empty?
355 movies << [roles, title].compact.join(": ")
361 [name_url, movies.join(" | ")]
366 def name_in_movie(name_urls, movie_urls)
368 movie_urls.each { |movie|
369 title_info = info_title(movie, :title_only => true)
372 data = @bot.httputil.get(IMDB + movie + "fullcredits")
373 data.scan(CREDIT_NAME_MATCH).each { |url, name, role|
374 valid << [url, name.ircify_html, role.ircify_html] if name_urls.include?(url)
376 valid.each { |url, name, role|
377 info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
386 class ImdbPlugin < Plugin
387 Config.register Config::BooleanValue.new('imdb.aka',
389 :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
390 Config.register Config::BooleanValue.new('imdb.popular',
392 :desc => "Display info on popular IMDB entries matching the request closely")
393 Config.register Config::BooleanValue.new('imdb.exact',
395 :desc => "Display info on IMDB entries matching the request exactly")
396 Config.register Config::BooleanValue.new('imdb.fix_article',
398 :desc => "Try to detect an article placed at the end and move it in front of the title")
399 Config.register Config::BooleanValue.new('imdb.tv_series_in_movies',
401 :desc => "Whether searching movies by person/year should also return TV series")
403 def help(plugin, topic="")
406 "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\""
408 "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>"
410 "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"
416 TITLE_URL = %r{^http://(?:[^.]+\.)?imdb.com(/title/tt\d+/)}
417 NAME_URL = %r{^http://(?:[^.]+\.)?imdb.com(/name/nm\d+/)}
419 loc = Utils.check_location(s, TITLE_URL)
421 sr = loc.first.match(TITLE_URL)[1]
422 extra = $2 # nothign for the time being, could be fullcredits or whatever
423 res = i.info_title(sr, :nourl => true, :characters => (extra == 'fullcredits'))
426 return {:title => res.first, :content => res.last}
431 loc = Utils.check_location(s, NAME_URL)
433 sr = loc.first.match(NAME_URL)[1]
434 extra = $2 # nothing for the time being, could be filmoyear or whatever
435 res = i.info_name(sr, :nourl => true, :movies_by_year => (extra == 'filmoyear'))
439 return {:title => name, :content => res.join(". ")}
450 @bot.register_filter(:imdb, :htmlinfo) { |s| imdb_filter(s) }
453 # Find a person or movie on IMDB. A :type (name/title, default both) can be
454 # specified to limit the search to either.
458 movie = params[:movie].to_s
459 info = i.info(movie, :type => :title, :characters => true)
461 what = params[:what].to_s
462 type = params[:type].intern
463 info = i.info(what, :type => type)
465 m.reply "nothing found for #{what}"
470 m.reply Utils.decode_html_entities(info.first.join("\n"))
472 m.reply info.map { |si|
473 Utils.decode_html_entities si.join(" | ")
478 # Find the movies with a participation of :who in the year :year
479 # TODO: allow year to be either a year or a decade ('[in the] 1960s')
481 def movies(m, params)
482 who = params[:who].to_s
483 years = params[:years]
485 if role and role.downcase == 'anything'
488 case params[:prefix].intern
490 role = /actor|actress/i
496 name_urls = i.search(who, :type => :name)
498 m.reply "nothing found about #{who}, sorry"
502 movie_urls = i.year_movies(name_urls, years, role)
503 debug movie_urls.inspect
504 debug movie_urls[0][1]
506 if movie_urls.length == 1 and movie_urls[0][1]
507 m.reply movie_urls.join("\n")
509 m.reply movie_urls.map { |si|
510 si[1] = "no movies in #{years}" unless si[1]
511 Utils.decode_html_entities si.join(" | ")
516 # Find the character played by :who in :movie
518 def character(m, params)
519 who = params[:who].to_s
520 movie = params[:movie].to_s
522 name_urls = i.search(who, :type => :name)
524 m.reply "nothing found about #{who}, sorry"
528 movie_urls = i.search(movie, :type => :title)
530 m.reply "nothing found about #{who}, sorry"
534 info = i.name_in_movie(name_urls, movie_urls)
536 m.reply "nothing found about #{who} in #{movie}, sorry"
538 m.reply info.join("\n")
542 # Report the characters in movie :movie
544 def characters(m, params)
545 movie = params[:movie].to_s
547 urls = i.search(movie, :type => :title)
549 m.reply "nothing found about #{movie}"
556 plugin = ImdbPlugin.new
558 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
559 plugin.map "movies :prefix *who in [the] :years [as :role]", :requirements => { :prefix => /with|by|from/, :years => /'?\d+s?/ }
560 plugin.map "character [played] by *who in *movie"
561 plugin.map "character of *who in *movie"
562 plugin.map "characters in *movie", :action => :imdb