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