]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
imdb: restore 'character of' functionality
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / imdb.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: IMDB plugin for rbot
5 #
6 # Author:: Arnaud Cornet <arnaud.cornet@gmail.com>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 #
9 # Copyright:: (C) 2005 Arnaud Cornet
10 # Copyright:: (C) 2007 Giuseppe Bilotta
11 #
12 # License:: MIT license
13
14 class Imdb
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*\/>/
23
24   MATCHER = {
25     :character => CHAR_MATCH,
26     :title => TITLE_MATCH,
27     :name => NAME_MATCH,
28     :both => TITLE_OR_NAME_MATCH
29   }
30
31   def initialize(bot)
32     @bot = bot
33   end
34
35   def search(rawstr, rawopts={})
36     str = CGI.escape(rawstr)
37     str << ";site=aka" if @bot.config['imdb.aka']
38     opts = rawopts.dup
39     opts[:type] = :both unless opts[:type]
40     return do_search(str, opts)
41   end
42
43   def do_search(str, opts={})
44     resp = nil
45     begin
46       resp = @bot.httputil.get_response(IMDB + "/find?q=#{str}",
47                                         :max_redir => -1)
48     rescue Exception => e
49       error e.message
50       warning e.backtrace.join("\n")
51       return nil
52     end
53
54
55     matcher = MATCHER[opts[:type]]
56
57     if resp.code == "200"
58       if opts[:all]
59         return resp.body.scan(matcher).map { |m| m.first }.compact.uniq
60       end
61       m = []
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($')
65       end
66       m.compact!
67       unless m.empty?
68         return m.map { |mm|
69           mm[1]
70         }.uniq
71       end
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)
77       else
78         return [new_loc.gsub(/\?.*/, "")]
79       end
80     end
81     return nil
82   end
83
84   def info(rawstr, opts={})
85     debug opts.inspect
86     urls = search(rawstr, opts)
87     debug urls
88     if urls.nil_or_empty?
89       debug "IMDB: search returned NIL"
90       return nil
91     end
92     results = []
93     urls.each { |sr|
94       type = sr.match(/^\/([^\/]+)\//)[1].downcase.intern rescue nil
95       case type
96       when :title
97         results << info_title(sr, opts)
98       when :name
99         results << info_name(sr, opts)
100       else
101         results << "#{sr}"
102       end
103     }
104     return results
105   end
106
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
109   end
110
111   def fix_article(org_tit)
112     title = org_tit.dup
113     debug title.inspect
114     if title.match(/^"(.*)"$/)
115       return "\"#{fix_article($1)}\""
116     end
117     if @bot.config['imdb.fix_article'] and title.gsub!(FINAL_ARTICLE_MATCH, '')
118       art = $1.dup
119       debug art.inspect
120       if art[-1,1].match(/[A-Za-z]/)
121         art << " "
122       end
123       return art + title
124     end
125     return title
126   end
127
128   def info_title(sr, opts={})
129     resp = nil
130     begin
131       resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
132     rescue Exception => e
133       error e.message
134       warning e.backtrace.join("\n")
135       return nil
136     end
137
138     info = []
139
140     if resp.code == "200"
141       m = /<title>([^<]*)<\/title>/.match(resp.body)
142       return nil if !m
143       title_date = m[1].ircify_html
144       debug title_date
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
148       pre_title.strip!
149       title = fix_article(pre_title)
150
151       dir = nil
152       data = grab_info(/(?:Director|Creator)s?/, resp.body)
153       if data
154         dir = data.scan(NAME_MATCH).map { |url, name|
155           name.ircify_html
156         }.join(', ')
157       end
158
159       country = nil
160       data = grab_info(/Country/, resp.body)
161       if data
162         country = data.ircify_html.gsub(' / ','/')
163       end
164
165       info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, opts[:nourl] ? nil : ": http://www.imdb.com#{sr}"].compact.join(" ")
166
167       return info if opts[:title_only]
168
169       if opts[:characters]
170         info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
171           "%s: %s" % [name, role.ircify_html]
172         }.join('; ')
173         return info
174       end
175
176       ratings = "no votes"
177       m = resp.body.match(/<b>([0-9.]+)<\/b><span [^>]+>\/10<\/span><\/span>\s*[^<]+<a\s+[^>]*href="ratings"[^>]+>([0-9,]+) votes?<\/a>/m)
178       if m
179         ratings = "#{m[1]}/10 (#{m[2]} voters)"
180       end
181
182       genre = Array.new
183       resp.body.scan(/<a href="\/genre\/[^"]+">([^<]+)<\/a>/) do |gnr|
184         genre << gnr
185       end
186
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
190       # if data
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*$/,'')
193       # end
194       plot = "Plot: #{plot}" if plot
195
196       info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
197
198       return info
199     end
200     return nil
201   end
202
203   def info_name(sr, opts={})
204     resp = nil
205     begin
206       resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
207     rescue Exception => e
208       error e.message
209       warning e.backtrace.join("\n")
210       return nil
211     end
212
213     info = []
214
215     if resp.code == "200"
216       m = /<title>([^<]*)<\/title>/.match(resp.body)
217       return nil if !m
218       name = m[1].sub(/ - IMDb/, '')
219
220       info << name
221       info.last << " : http://www.imdb.com#{sr}" unless opts[:nourl]
222
223       return info if opts[:name_only]
224
225       if opts[:movies_by_year]
226         filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
227         if filmoyear
228           info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
229         end
230         return info
231       end
232
233       birth = nil
234       data = grab_info("Date of Birth", resp.body)
235       if data
236         birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
237       end
238
239       death = nil
240       data = grab_info("Date of Death", resp.body)
241       if data
242         death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
243       end
244
245       info << [birth, death].compact.join('. ') if birth or death
246
247       movies = {}
248
249       filmorate = nil
250       begin
251         filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
252       rescue Exception
253       end
254
255       if filmorate
256         filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
257           what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
258           next unless what
259           movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
260             fix_article(tit.ircify_html)
261           }
262         }
263       end
264
265       preferred = ['Actor', 'Director']
266       if resp.body.match(/Jump to filmography as:&nbsp;(.*?)<\/div>/)
267         txt = $1
268         preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
269           pref.first
270         }
271       end
272
273       unless movies.empty?
274         all_keys = movies.keys.sort
275         debug all_keys.inspect
276         keys = []
277         preferred.each { |key|
278           keys << key if all_keys.include? key
279         }
280         keys = all_keys if keys.empty?
281         ar = []
282         keys.each { |key|
283           ar << key.dup
284           ar.last << ": " + movies[key].join('; ')
285         }
286         info << ar.join('. ')
287       end
288       return info
289
290     end
291     return nil
292   end
293
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?$/)
299
300     years = []
301     case years_txt
302     when /^\d\d\d\d$/
303       years << years_txt
304     when /^(\d\d\d\d)s$/
305       base = $1.to_i
306       base.upto(base+9) { |year|
307         years << year.to_s
308       }
309     end
310
311     urls.map { |url|
312       info = info_name(url, :movies_by_year => true)
313
314       debug info.inspect
315
316       name_url = info.first
317       data = info[1]
318
319       movies = []
320       # Sort by pre-title putting movies before TV series
321       data.sort { |a, b|
322         aclip = a[1][0,5]
323         bclip = b[1][0,5]
324         quot = '&#34;'
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']
330           next
331         end
332         title << " (#{year})" unless years.length == 1
333         role_array = []
334         pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
335           role = nil
336           extra = nil
337           if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
338             role = $1
339             extra = "(#{$2.ircify_html})"
340           else
341             role = txt
342           end
343           next if role_req and not role.match(/^#{role_req}/i)
344           if comm
345             extra ||= ""
346             extra += comm.ircify_html if comm
347           end
348           role_array << [role, extra]
349         }
350         next if role_req and role_array.empty?
351
352         roles = role_array.map { |ar|
353           if role_req
354             ar[1] # works for us both if it's nil and if it's something
355           else
356             ar.compact.join(" ")
357           end
358         }.compact.join(', ')
359         roles = nil if roles.empty?
360         movies << [roles, title].compact.join(": ")
361       }
362
363       if movies.empty?
364         [name_url, nil]
365       else
366         [name_url, movies.join(" | ")]
367       end
368     }
369   end
370
371   def name_in_movie(name_urls, movie_urls)
372     debug name_urls
373     info = []
374     movie_urls.each { |movie|
375       title_info = info_title(movie, :title_only => true)
376       valid = []
377
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
381         debug [ch_url, role]
382         wanted = name_urls.include?(url) || name_urls.include?(ch_url)
383         valid << [url, name.ircify_html, role.ircify_html] if wanted
384       }
385       valid.each { |url, name, role|
386         info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
387       }
388     }
389     return info
390   end
391
392
393 end
394
395 class ImdbPlugin < Plugin
396   Config.register Config::BooleanValue.new('imdb.aka',
397     :default => true,
398     :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
399   Config.register Config::BooleanValue.new('imdb.popular',
400     :default => true,
401     :desc => "Display info on popular IMDB entries matching the request closely")
402   Config.register Config::BooleanValue.new('imdb.exact',
403     :default => true,
404     :desc => "Display info on IMDB entries matching the request exactly")
405   Config.register Config::BooleanValue.new('imdb.fix_article',
406     :default => false,
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',
409     :default => false,
410     :desc => "Whether searching movies by person/year should also return TV series")
411
412   def help(plugin, topic="")
413     case plugin
414     when "movies"
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\""
416     when /characters?/
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>"
418     else
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"
420     end
421   end
422
423   attr_reader :i
424
425   TITLE_URL = %r{^http://(?:[^.]+\.)?imdb.com(/title/tt\d+/)}
426   NAME_URL = %r{^http://(?:[^.]+\.)?imdb.com(/name/nm\d+/)}
427   def imdb_filter(s)
428     loc = Utils.check_location(s, TITLE_URL)
429     if loc
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'))
433       debug res
434       if res
435         return {:title => res.first, :content => res.last}
436       else
437         return nil
438       end
439     end
440     loc = Utils.check_location(s, NAME_URL)
441     if loc
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'))
445       debug res
446       if res
447         name = res.shift
448         return {:title => name, :content => res.join(". ")}
449       else
450         return nil
451       end
452     end
453     return nil
454   end
455
456   def initialize
457     super
458     @i = Imdb.new(@bot)
459     @bot.register_filter(:imdb, :htmlinfo) { |s| imdb_filter(s) }
460   end
461
462   # Find a person or movie on IMDB. A :type (name/title, default both) can be
463   # specified to limit the search to either.
464   #
465   def imdb(m, params)
466     if params[:movie]
467       movie = params[:movie].to_s
468       info = i.info(movie, :type => :title, :characters => true)
469     else
470       what = params[:what].to_s
471       type = params[:type].intern
472       info = i.info(what, :type => type)
473       if !info
474         m.reply "nothing found for #{what}"
475         return nil
476       end
477     end
478     if info.length == 1
479       m.reply Utils.decode_html_entities(info.first.join("\n"))
480     else
481       m.reply info.map { |si|
482         Utils.decode_html_entities si.join(" | ")
483       }.join("\n")
484     end
485   end
486
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')
489   #
490   def movies(m, params)
491     who = params[:who].to_s
492     years = params[:years]
493     role = params[:role]
494     if role and role.downcase == 'anything'
495       role = nil
496     elsif not role
497       case params[:prefix].intern
498       when :with
499         role = /actor|actress/i
500       when :by
501         role = 'director'
502       end
503     end
504
505     name_urls = i.search(who, :type => :name)
506     unless name_urls
507       m.reply "nothing found about #{who}, sorry"
508       return
509     end
510
511     movie_urls = i.year_movies(name_urls, years, role)
512     debug movie_urls.inspect
513     debug movie_urls[0][1]
514
515     if movie_urls.length == 1 and movie_urls[0][1]
516       m.reply movie_urls.join("\n")
517     else
518       m.reply movie_urls.map { |si|
519         si[1] = "no movies in #{years}" unless si[1]
520         Utils.decode_html_entities si.join(" | ")
521       }.join("\n")
522     end
523   end
524
525   # Find the character played by :who in :movie
526   #
527   def character(m, params)
528     movie = params[:movie].to_s
529     movie_urls = i.search(movie, :type => :title)
530     unless movie_urls
531       m.reply "movie #{who} not found, sorry"
532       return
533     end
534
535     if params[:actor]
536       who = params[:actor].to_s
537       type = :name
538     else
539       who = params[:character].to_s
540       type = :character
541     end
542
543     name_urls = i.search(who, :type => type, :all => true)
544     unless name_urls
545       m.reply "nothing found about #{who}, sorry"
546       return
547     end
548
549     info = i.name_in_movie(name_urls, movie_urls)
550     if info.empty?
551       m.reply "nothing found about #{who} in #{movie}, sorry"
552     else
553       m.reply info.join("\n")
554     end
555   end
556
557   # Report the characters in movie :movie
558   #
559   def characters(m, params)
560     movie = params[:movie].to_s
561
562     urls = i.search(movie, :type => :title)
563     unless urls
564       m.reply "nothing found about #{movie}"
565     end
566
567   end
568
569 end
570
571 plugin = ImdbPlugin.new
572
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
578