]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
fix for imdb, changed patterns for ratings&genre
[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       # 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
149       pre_title.strip!
150       title = fix_article(pre_title)
151
152       dir = nil
153       data = grab_info(/(?:Director|Creator)s?/, resp.body)
154       if data
155         dir = data.scan(NAME_MATCH).map { |url, name|
156           name.ircify_html
157         }.join(', ')
158       end
159
160       country = nil
161       data = grab_info(/Country/, resp.body)
162       if data
163         country = data.ircify_html.gsub(' / ','/')
164       end
165
166       info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, opts[:nourl] ? nil : ": http://www.imdb.com#{sr}"].compact.join(" ")
167
168       return info if opts[:title_only]
169
170       if opts[:characters]
171         info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
172           "%s: %s" % [name, role.ircify_html]
173         }.join('; ')
174         return info
175       end
176
177       ratings = "no votes"
178       m = resp.body.match(/Users rated this ([0-9.]+)\/10 \(([0-9,]+) votes\)/m)
179       if m
180         ratings = "#{m[1]}/10 (#{m[2]} voters)"
181       end
182
183       genre = Array.new
184       resp.body.scan(/<a href="\/genre\/[^"]+"[^>]+>([^<]+)<\/a>/) do |gnr|
185         genre << gnr
186       end
187
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
191       # if data
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*$/,'')
194       # end
195       plot = "Plot: #{plot}" if plot
196
197       info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
198
199       return info
200     end
201     return nil
202   end
203
204   def info_name(sr, opts={})
205     resp = nil
206     begin
207       resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
208     rescue Exception => e
209       error e.message
210       warning e.backtrace.join("\n")
211       return nil
212     end
213
214     info = []
215
216     if resp.code == "200"
217       m = /<title>([^<]*)<\/title>/.match(resp.body)
218       return nil if !m
219       name = m[1].sub(/ - IMDb/, '')
220
221       info << name
222       info.last << " : http://www.imdb.com#{sr}" unless opts[:nourl]
223
224       return info if opts[:name_only]
225
226       if opts[:movies_by_year]
227         filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
228         if filmoyear
229           info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
230         end
231         return info
232       end
233
234       birth = nil
235       data = grab_info("Date of Birth", resp.body)
236       if data
237         birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
238       end
239
240       death = nil
241       data = grab_info("Date of Death", resp.body)
242       if data
243         death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
244       end
245
246       info << [birth, death].compact.join('. ') if birth or death
247
248       movies = {}
249
250       filmorate = nil
251       begin
252         filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
253       rescue Exception
254       end
255
256       if filmorate
257         filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
258           what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
259           next unless what
260           movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
261             fix_article(tit.ircify_html)
262           }
263         }
264       end
265
266       preferred = ['Actor', 'Director']
267       if resp.body.match(/Jump to filmography as:&nbsp;(.*?)<\/div>/)
268         txt = $1
269         preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
270           pref.first
271         }
272       end
273
274       unless movies.empty?
275         all_keys = movies.keys.sort
276         debug all_keys.inspect
277         keys = []
278         preferred.each { |key|
279           keys << key if all_keys.include? key
280         }
281         keys = all_keys if keys.empty?
282         ar = []
283         keys.each { |key|
284           ar << key.dup
285           ar.last << ": " + movies[key].join('; ')
286         }
287         info << ar.join('. ')
288       end
289       return info
290
291     end
292     return nil
293   end
294
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?$/)
300
301     years = []
302     case years_txt
303     when /^\d\d\d\d$/
304       years << years_txt
305     when /^(\d\d\d\d)s$/
306       base = $1.to_i
307       base.upto(base+9) { |year|
308         years << year.to_s
309       }
310     end
311
312     urls.map { |u|
313       info = info_name(u, :movies_by_year => true)
314
315       debug info.inspect
316
317       name_url = info.first
318       data = info[1]
319
320       movies = []
321       # Sort by pre-title putting movies before TV series
322       data.sort { |a, b|
323         aclip = a[1][0,5]
324         bclip = b[1][0,5]
325         quot = '&#34;'
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']
331           next
332         end
333         title << " (#{year})" unless years.length == 1
334         role_array = []
335         pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
336           role = nil
337           extra = nil
338           if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
339             role = $1
340             extra = "(#{$2.ircify_html})"
341           else
342             role = txt
343           end
344           next if role_req and not role.match(/^#{role_req}/i)
345           if comm
346             extra ||= ""
347             extra += comm.ircify_html if comm
348           end
349           role_array << [role, extra]
350         }
351         next if role_req and role_array.empty?
352
353         roles = role_array.map { |ar|
354           if role_req
355             ar[1] # works for us both if it's nil and if it's something
356           else
357             ar.compact.join(" ")
358           end
359         }.compact.join(', ')
360         roles = nil if roles.empty?
361         movies << [roles, title].compact.join(": ")
362       }
363
364       if movies.empty?
365         [name_url, nil]
366       else
367         [name_url, movies.join(" | ")]
368       end
369     }
370   end
371
372   def name_in_movie(name_urls, movie_urls)
373     debug name_urls
374     info = []
375     movie_urls.each { |movie|
376       title_info = info_title(movie, :title_only => true)
377       valid = []
378
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
382         debug [ch_url, role]
383         wanted = name_urls.include?(url) || name_urls.include?(ch_url)
384         valid << [url, name.ircify_html, role.ircify_html] if wanted
385       }
386       valid.each { |url, name, role|
387         info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
388       }
389     }
390     return info
391   end
392
393
394 end
395
396 class ImdbPlugin < Plugin
397   Config.register Config::BooleanValue.new('imdb.aka',
398     :default => true,
399     :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
400   Config.register Config::BooleanValue.new('imdb.popular',
401     :default => true,
402     :desc => "Display info on popular IMDB entries matching the request closely")
403   Config.register Config::BooleanValue.new('imdb.exact',
404     :default => true,
405     :desc => "Display info on IMDB entries matching the request exactly")
406   Config.register Config::BooleanValue.new('imdb.fix_article',
407     :default => false,
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',
410     :default => false,
411     :desc => "Whether searching movies by person/year should also return TV series")
412
413   def help(plugin, topic="")
414     case plugin
415     when "movies"
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\""
417     when /characters?/
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>"
419     else
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"
421     end
422   end
423
424   attr_reader :i
425
426   TITLE_URL = %r{^http://(?:[^.]+\.)?imdb.com(/title/tt\d+/)}
427   NAME_URL = %r{^http://(?:[^.]+\.)?imdb.com(/name/nm\d+/)}
428   def imdb_filter(s)
429     loc = Utils.check_location(s, TITLE_URL)
430     if loc
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'))
434       debug res
435       if res
436         return {:title => res.first, :content => res.last}
437       else
438         return nil
439       end
440     end
441     loc = Utils.check_location(s, NAME_URL)
442     if loc
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'))
446       debug res
447       if res
448         name = res.shift
449         return {:title => name, :content => res.join(". ")}
450       else
451         return nil
452       end
453     end
454     return nil
455   end
456
457   def initialize
458     super
459     @i = Imdb.new(@bot)
460     @bot.register_filter(:imdb, :htmlinfo) { |s| imdb_filter(s) }
461   end
462
463   # Find a person or movie on IMDB. A :type (name/title, default both) can be
464   # specified to limit the search to either.
465   #
466   def imdb(m, params)
467     if params[:movie]
468       movie = params[:movie].to_s
469       info = i.info(movie, :type => :title, :characters => true)
470     else
471       what = params[:what].to_s
472       type = params[:type].intern
473       info = i.info(what, :type => type)
474       if !info
475         m.reply "nothing found for #{what}"
476         return nil
477       end
478     end
479     if info.length == 1
480       m.reply Utils.decode_html_entities(info.first.join("\n"))
481     else
482       m.reply info.map { |si|
483         Utils.decode_html_entities si.join(" | ")
484       }.join("\n")
485     end
486   end
487
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')
490   #
491   def movies(m, params)
492     who = params[:who].to_s
493     years = params[:years]
494     role = params[:role]
495     if role and role.downcase == 'anything'
496       role = nil
497     elsif not role
498       case params[:prefix].intern
499       when :with
500         role = /actor|actress/i
501       when :by
502         role = 'director'
503       end
504     end
505
506     name_urls = i.search(who, :type => :name)
507     unless name_urls
508       m.reply "nothing found about #{who}, sorry"
509       return
510     end
511
512     movie_urls = i.year_movies(name_urls, years, role)
513     debug movie_urls.inspect
514     debug movie_urls[0][1]
515
516     if movie_urls.length == 1 and movie_urls[0][1]
517       m.reply movie_urls.join("\n")
518     else
519       m.reply movie_urls.map { |si|
520         si[1] = "no movies in #{years}" unless si[1]
521         Utils.decode_html_entities si.join(" | ")
522       }.join("\n")
523     end
524   end
525
526   # Find the character played by :who in :movie
527   #
528   def character(m, params)
529     movie = params[:movie].to_s
530     movie_urls = i.search(movie, :type => :title)
531     unless movie_urls
532       m.reply "movie #{who} not found, sorry"
533       return
534     end
535
536     if params[:actor]
537       who = params[:actor].to_s
538       type = :name
539     else
540       who = params[:character].to_s
541       type = :character
542     end
543
544     name_urls = i.search(who, :type => type, :all => true)
545     unless name_urls
546       m.reply "nothing found about #{who}, sorry"
547       return
548     end
549
550     info = i.name_in_movie(name_urls, movie_urls)
551     if info.empty?
552       m.reply "nothing found about #{who} in #{movie}, sorry"
553     else
554       m.reply info.join("\n")
555     end
556   end
557
558   # Report the characters in movie :movie
559   #
560   def characters(m, params)
561     movie = params[:movie].to_s
562
563     urls = i.search(movie, :type => :title)
564     unless urls
565       m.reply "nothing found about #{movie}"
566     end
567
568   end
569
570 end
571
572 plugin = ImdbPlugin.new
573
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
579