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 # also, the second date, if missing, is an no-break space
147 pre_title, extra, date, junk = title_date.scan(/^(.*)\((.+?\s+)?(\d\d\d\d(?:–(?:\d\d\d\d| )?)?(?:\/[IV]+)?)\)\s*(.+)?$/).first
148 extra.strip! if extra
150 title = fix_article(pre_title)
153 data = grab_info(/(?:Director|Creator)s?/, resp.body)
155 dir = data.scan(NAME_MATCH).map { |url, name|
161 data = grab_info(/Country/, resp.body)
163 country = data.ircify_html.gsub(' / ','/')
166 info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, opts[:nourl] ? nil : ": http://www.imdb.com#{sr}"].compact.join(" ")
168 return info if opts[:title_only]
171 info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
172 "%s: %s" % [name, role.ircify_html]
178 m = resp.body.match(/Users rated this ([0-9.]+)\/10 \(([0-9,]+) votes\)/m)
180 ratings = "#{m[1]}/10 (#{m[2]} voters)"
184 resp.body.scan(/<a href="\/genre\/[^"]+"[^>]+>([^<]+)<\/a>/) do |gnr|
188 plot = resp.body.match(DESC_MATCH)[3] rescue nil
189 # TODO option to extract the long storyline
190 # data = resp.body.match(/<h2>Storyline<\/h2>\s+/m).post_match.match(/<\/p>/).pre_match rescue nil
192 # data.sub!(/<em class="nobr">Written by.*$/m, '')
193 # plot = data.ircify_html.gsub(/\s+more\s*$/,'').gsub(/\s+Full summary » \| Full synopsis »\s*$/,'')
195 plot = "Plot: #{plot}" if plot
197 info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
204 def info_name(sr, opts={})
207 resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
208 rescue Exception => e
210 warning e.backtrace.join("\n")
216 if resp.code == "200"
217 m = /<title>([^<]*)<\/title>/.match(resp.body)
219 name = m[1].sub(/ - IMDb/, '')
222 info.last << " : http://www.imdb.com#{sr}" unless opts[:nourl]
224 return info if opts[:name_only]
226 if opts[:movies_by_year]
227 filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
229 info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
235 data = grab_info("Date of Birth", resp.body)
237 birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
241 data = grab_info("Date of Death", resp.body)
243 death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
246 info << [birth, death].compact.join('. ') if birth or death
252 filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
257 filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
258 what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
260 movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
261 fix_article(tit.ircify_html)
266 preferred = ['Actor', 'Director']
267 if resp.body.match(/Jump to filmography as: (.*?)<\/div>/)
269 preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
275 all_keys = movies.keys.sort
276 debug all_keys.inspect
278 preferred.each { |key|
279 keys << key if all_keys.include? key
281 keys = all_keys if keys.empty?
285 ar.last << ": " + movies[key].join('; ')
287 info << ar.join('. ')
295 def year_movies(urls, years_txt_org, role_req)
296 years_txt = years_txt_org.dup
297 years_txt.sub!(/^'/,'')
298 years_txt = "9#{years_txt}" if years_txt.match(/^\d\ds?$/)
299 years_txt = "1#{years_txt}" if years_txt.match(/^\d\d\ds?$/)
307 base.upto(base+9) { |year|
313 info = info_name(u, :movies_by_year => true)
317 name_url = info.first
321 # Sort by pre-title putting movies before TV series
326 (aclip == quot ? 1 : -1) <=> (bclip == quot ? 1 : -1)
327 }.each { |url, pre_title, year, pre_roles|
328 next unless years.include?(year)
329 title = fix_article(pre_title.ircify_html)
330 if title[0] == ?" and not @bot.config['imdb.tv_series_in_movies']
333 title << " (#{year})" unless years.length == 1
335 pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
338 if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
340 extra = "(#{$2.ircify_html})"
344 next if role_req and not role.match(/^#{role_req}/i)
347 extra += comm.ircify_html if comm
349 role_array << [role, extra]
351 next if role_req and role_array.empty?
353 roles = role_array.map { |ar|
355 ar[1] # works for us both if it's nil and if it's something
360 roles = nil if roles.empty?
361 movies << [roles, title].compact.join(": ")
367 [name_url, movies.join(" | ")]
372 def name_in_movie(name_urls, movie_urls)
375 movie_urls.each { |movie|
376 title_info = info_title(movie, :title_only => true)
379 data = @bot.httputil.get(IMDB + movie + "fullcredits")
380 data.scan(CREDIT_NAME_MATCH).each { |url, name, role_data|
381 ch_url, role = role_data.scan(CHAR_MATCH).first
383 wanted = name_urls.include?(url) || name_urls.include?(ch_url)
384 valid << [url, name.ircify_html, role.ircify_html] if wanted
386 valid.each { |url, name, role|
387 info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
396 class ImdbPlugin < Plugin
397 Config.register Config::BooleanValue.new('imdb.aka',
399 :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
400 Config.register Config::BooleanValue.new('imdb.popular',
402 :desc => "Display info on popular IMDB entries matching the request closely")
403 Config.register Config::BooleanValue.new('imdb.exact',
405 :desc => "Display info on IMDB entries matching the request exactly")
406 Config.register Config::BooleanValue.new('imdb.fix_article',
408 :desc => "Try to detect an article placed at the end and move it in front of the title")
409 Config.register Config::BooleanValue.new('imdb.tv_series_in_movies',
411 :desc => "Whether searching movies by person/year should also return TV series")
413 def help(plugin, topic="")
416 "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\""
418 "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>"
420 "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"
426 TITLE_URL = %r{^http://(?:[^.]+\.)?imdb.com(/title/tt\d+/)}
427 NAME_URL = %r{^http://(?:[^.]+\.)?imdb.com(/name/nm\d+/)}
429 loc = Utils.check_location(s, TITLE_URL)
431 sr = loc.first.match(TITLE_URL)[1]
432 extra = $2 # nothign for the time being, could be fullcredits or whatever
433 res = i.info_title(sr, :nourl => true, :characters => (extra == 'fullcredits'))
436 return {:title => res.first, :content => res.last}
441 loc = Utils.check_location(s, NAME_URL)
443 sr = loc.first.match(NAME_URL)[1]
444 extra = $2 # nothing for the time being, could be filmoyear or whatever
445 res = i.info_name(sr, :nourl => true, :movies_by_year => (extra == 'filmoyear'))
449 return {:title => name, :content => res.join(". ")}
460 @bot.register_filter(:imdb, :htmlinfo) { |s| imdb_filter(s) }
463 # Find a person or movie on IMDB. A :type (name/title, default both) can be
464 # specified to limit the search to either.
468 movie = params[:movie].to_s
469 info = i.info(movie, :type => :title, :characters => true)
471 what = params[:what].to_s
472 type = params[:type].intern
473 info = i.info(what, :type => type)
475 m.reply "nothing found for #{what}"
480 m.reply Utils.decode_html_entities(info.first.join("\n"))
482 m.reply info.map { |si|
483 Utils.decode_html_entities si.join(" | ")
488 # Find the movies with a participation of :who in the year :year
489 # TODO: allow year to be either a year or a decade ('[in the] 1960s')
491 def movies(m, params)
492 who = params[:who].to_s
493 years = params[:years]
495 if role and role.downcase == 'anything'
498 case params[:prefix].intern
500 role = /actor|actress/i
506 name_urls = i.search(who, :type => :name)
508 m.reply "nothing found about #{who}, sorry"
512 movie_urls = i.year_movies(name_urls, years, role)
513 debug movie_urls.inspect
514 debug movie_urls[0][1]
516 if movie_urls.length == 1 and movie_urls[0][1]
517 m.reply movie_urls.join("\n")
519 m.reply movie_urls.map { |si|
520 si[1] = "no movies in #{years}" unless si[1]
521 Utils.decode_html_entities si.join(" | ")
526 # Find the character played by :who in :movie
528 def character(m, params)
529 movie = params[:movie].to_s
530 movie_urls = i.search(movie, :type => :title)
532 m.reply "movie #{who} not found, sorry"
537 who = params[:actor].to_s
540 who = params[:character].to_s
544 name_urls = i.search(who, :type => type, :all => true)
546 m.reply "nothing found about #{who}, sorry"
550 info = i.name_in_movie(name_urls, movie_urls)
552 m.reply "nothing found about #{who} in #{movie}, sorry"
554 m.reply info.join("\n")
558 # Report the characters in movie :movie
560 def characters(m, params)
561 movie = params[:movie].to_s
563 urls = i.search(movie, :type => :title)
565 m.reply "nothing found about #{movie}"
572 plugin = ImdbPlugin.new
574 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
575 plugin.map "movies :prefix *who in [the] :years [as :role]", :requirements => { :prefix => /with|by|from/, :years => /'?\d+s?/ }
576 plugin.map "character [played] by *actor in *movie"
577 plugin.map "character of *character in *movie"
578 plugin.map "characters in *movie", :action => :imdb