]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
imdb plugin: movies by person/year can now be shown in decades, and by shortening...
[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 require 'uri/common'
15
16 class Imdb
17   IMDB = "http://us.imdb.com"
18   TITLE_OR_NAME_MATCH = /<a href="(\/(?:title|name)\/(?:tt|nm)[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
19   TITLE_MATCH = /<a href="(\/title\/tt[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
20   NAME_MATCH = /<a href="(\/name\/nm[0-9]+\/?)[^"]*"(?:[^>]*)>([^<]*)<\/a>/
21   CREDIT_NAME_MATCH = /#{NAME_MATCH}<\/td><td[^>]+> \.\.\. <\/td><td[^>]+>(.+?)<\/td>/
22   FINAL_ARTICLE_MATCH = /, ([A-Z]\S{0,2})$/
23
24   MATCHER = {
25     :title => TITLE_MATCH,
26     :name => NAME_MATCH,
27     :both => TITLE_OR_NAME_MATCH
28   }
29
30   def initialize(bot)
31     @bot = bot
32   end
33
34   def search(rawstr, rawopts={})
35     str = CGI.escape(rawstr)
36     str << ";site=aka" if @bot.config['imdb.aka']
37     opts = rawopts.dup
38     opts[:type] = :both unless opts[:type]
39     return do_search(str, opts)
40   end
41
42   def do_search(str, opts={})
43     resp = nil
44     begin
45       resp = @bot.httputil.get_response(IMDB + "/find?q=#{str}",
46                                         :max_redir => -1)
47     rescue Exception => e
48       error e.message
49       warning e.backtrace.join("\n")
50       return nil
51     end
52
53
54     matcher = MATCHER[opts[:type]]
55
56     if resp.code == "200"
57       m = []
58       m << matcher.match(resp.body) if @bot.config['imdb.popular']
59       if resp.body.match(/\(Exact Matches\)<\/b>/) and @bot.config['imdb.exact']
60         m << matcher.match($')
61       end
62       m.compact!
63       unless m.empty?
64         return m.map { |mm|
65           mm[1]
66         }.uniq
67       end
68     elsif resp.code == "302"
69       debug "automatic redirection"
70       new_loc = resp['location'].gsub(IMDB, "")
71       if new_loc.match(/\/find\?q=(.*)/)
72         return do_search($1, opts)
73       else
74         return [new_loc.gsub(/\?.*/, "")]
75       end
76     end
77     return nil
78   end
79
80   def info(rawstr, opts={})
81     debug opts.inspect
82     urls = search(rawstr, opts)
83     debug urls
84     if urls.nil_or_empty?
85       debug "IMDB: search returned NIL"
86       return nil
87     end
88     results = []
89     urls.each { |sr|
90       type = sr.match(/^\/([^\/]+)\//)[1].downcase.intern rescue nil
91       case type
92       when :title
93         results << info_title(sr, opts)
94       when :name
95         results << info_name(sr, opts)
96       else
97         results << "#{sr}"
98       end
99     }
100     return results
101   end
102
103   def grab_info(info, body)
104     /<div class="info">\s+<h5>#{info}:<\/h5>\s+(.*?)<\/div>/mi.match(body)[1] rescue nil
105   end
106
107   def fix_article(org_tit)
108     title = org_tit.dup
109     debug title.inspect
110     if title.match(/^"(.*)"$/)
111       return "\"#{fix_article($1)}\""
112     end
113     if @bot.config['imdb.fix_article'] and title.gsub!(FINAL_ARTICLE_MATCH, '')
114       art = $1.dup
115       debug art.inspect
116       if art[-1,1].match(/[A-Za-z]/)
117         art << " "
118       end
119       return art + title
120     end
121     return title
122   end
123
124   def info_title(sr, opts={})
125     resp = nil
126     begin
127       resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
128     rescue Exception => e
129       error e.message
130       warning e.backtrace.join("\n")
131       return nil
132     end
133
134     info = []
135
136     if resp.code == "200"
137       m = /<title>([^<]*)<\/title>/.match(resp.body)
138       return nil if !m
139       title_date = m[1]
140       pre_title, date, extra = title_date.scan(/^(.*)\((\d\d\d\d(?:\/[IV]+)?)\)\s*(.+)?$/).first
141       pre_title.strip!
142       title = fix_article(pre_title.ircify_html)
143
144       dir = nil
145       data = grab_info(/Directors?/, resp.body)
146       if data
147         dir = data.scan(NAME_MATCH).map { |url, name|
148           name.ircify_html
149         }.join(', ')
150       end
151
152       country = nil
153       data = grab_info(/Country/, resp.body)
154       if data
155         country = data.ircify_html.gsub(' / ','/')
156       end
157
158       info << [title, "(#{country}, #{date})", extra, dir ? "[#{dir}]" : nil, ": http://us.imdb.com#{sr}"].compact.join(" ")
159
160       return info if opts[:title_only]
161
162       if opts[:characters]
163         info << resp.body.scan(CREDIT_NAME_MATCH).map { |url, name, role|
164           "%s: %s" % [name, role]
165         }.join('; ')
166         return info
167       end
168
169       ratings = "no votes"
170       m = /<b>([0-9.]+)\/10<\/b>\n?\r?\s+<small>\(<a href="ratings">([0-9,]+) votes?<\/a>\)<\/small>/.match(resp.body)
171       if m
172         ratings = "#{m[1]}/10 (#{m[2]} voters)"
173       end
174
175       genre = Array.new
176       resp.body.scan(/<a href="\/Sections\/Genres\/[^\/]+\/">([^<]+)<\/a>/) do |gnr|
177         genre << gnr
178       end
179
180       plot = nil
181       data = grab_info(/Plot (?:Outline|Summary)/, resp.body)
182       if data
183         plot = "Plot: " + data.ircify_html.gsub(/\s+more$/,'')
184       end
185
186       info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
187
188       return info
189     end
190     return nil
191   end
192
193   def info_name(sr, opts={})
194     resp = nil
195     begin
196       resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
197     rescue Exception => e
198       error e.message
199       warning e.backtrace.join("\n")
200       return nil
201     end
202
203     info = []
204
205     if resp.code == "200"
206       m = /<title>([^<]*)<\/title>/.match(resp.body)
207       return nil if !m
208       name = m[1]
209
210       info << "#{name} : http://us.imdb.com#{sr}"
211
212       return info if opts[:name_only]
213
214       if opts[:movies_by_year]
215         filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
216         if filmoyear
217           info << filmoyear.scan(/#{TITLE_MATCH} \((\d\d\d\d)\)[^\[\n]*((?:\s+\[[^\]]+\](?:\s+\([^\[<]+\))*)+)\s+</)
218         end
219         return info
220       end
221
222       birth = nil
223       data = grab_info("Date of Birth", resp.body)
224       if data
225         birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
226       end
227
228       death = nil
229       data = grab_info("Date of Death", resp.body)
230       if data
231         death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
232       end
233
234       info << [birth, death].compact.join('. ') if birth or death
235
236       movies = {}
237
238       filmorate = nil
239       begin
240         filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
241       rescue Exception
242       end
243
244       if filmorate
245         filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
246           what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
247           next unless what
248           movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
249             fix_article(tit.ircify_html)
250           }
251         }
252       end
253
254       preferred = ['Actor', 'Director']
255       if resp.body.match(/Jump to filmography as:&nbsp;(.*?)<\/div>/)
256         txt = $1
257         preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
258           pref.first
259         }
260       end
261
262       unless movies.empty?
263         all_keys = movies.keys.sort
264         debug all_keys.inspect
265         keys = []
266         preferred.each { |key|
267           keys << key if all_keys.include? key
268         }
269         keys = all_keys if keys.empty?
270         ar = []
271         keys.each { |key|
272           ar << key.dup
273           ar.last << ": " + movies[key].join('; ')
274         }
275         info << ar.join('. ')
276       end
277       return info
278
279     end
280     return nil
281   end
282
283   def year_movies(urls, years_txt_org)
284     years_txt = years_txt_org.dup
285     years_txt.sub!(/^'/,'')
286     years_txt = "9#{years_txt}" if years_txt.match(/^\d\ds?$/)
287     years_txt = "1#{years_txt}" if years_txt.match(/^\d\d\ds?$/)
288
289     years = []
290     case years_txt
291     when /^\d\d\d\d$/
292       years << years_txt
293     when /^(\d\d\d\d)s$/
294       base = $1.to_i
295       base.upto(base+9) { |year|
296         years << year.to_s
297       }
298     end
299
300     urls.map { |url|
301       info = info_name(url, :movies_by_year => true)
302
303       debug info.inspect
304
305       name_url = info.first
306       data = info[1]
307
308       movies = []
309       # Sort by pre-title putting movies before TV series
310       data.sort { |a, b|
311         aclip = a[1][0,5]
312         bclip = b[1][0,5]
313         quot = '&#34;'
314         (aclip == quot ? 1 : -1) <=> (bclip == quot ? 1 : -1)
315       }.each { |url, pre_title, year, pre_roles|
316         next unless years.include?(year)
317         title = fix_article(pre_title.ircify_html)
318         if title[0] == ?" and not @bot.config['imdb.tv_series_in_movies']
319           next
320         end
321         title << " (#{year})" unless years.length == 1
322         role_array = []
323         pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
324           if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
325             role_array << "#{$1} (#{$2})"
326           else
327             role_array << txt
328           end
329           role_array.last << " " + comm.ircify_html if comm
330         }
331
332         roles = role_array.join(', ')
333         movies << [roles, title].join(": ")
334       }
335
336       if movies.empty?
337         [name_url, nil]
338       else
339         [name_url, movies.join(" | ")]
340       end
341     }
342   end
343
344   def name_in_movie(name_urls, movie_urls)
345     info = []
346     movie_urls.each { |movie|
347       title_info = info_title(movie, :title_only => true)
348       valid = []
349
350       data = @bot.httputil.get(IMDB + movie + "fullcredits")
351       data.scan(CREDIT_NAME_MATCH).each { |url, name, role|
352         valid << [url, name.ircify_html, role.ircify_html] if name_urls.include?(url)
353       }
354       valid.each { |url, name, role|
355         info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
356       }
357     }
358     return info
359   end
360
361
362 end
363
364 class ImdbPlugin < Plugin
365   BotConfig.register BotConfigBooleanValue.new('imdb.aka',
366     :default => true,
367     :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
368   BotConfig.register BotConfigBooleanValue.new('imdb.popular',
369     :default => true,
370     :desc => "Display info on popular IMDB entries matching the request closely")
371   BotConfig.register BotConfigBooleanValue.new('imdb.exact',
372     :default => true,
373     :desc => "Display info on IMDB entries matching the request exactly")
374   BotConfig.register BotConfigBooleanValue.new('imdb.fix_article',
375     :default => false,
376     :desc => "Try to detect an article placed at the end and move it in front of the title")
377   BotConfig.register BotConfigBooleanValue.new('imdb.tv_series_in_movies',
378     :default => false,
379     :desc => "Whether searching movies by person/year should also return TV series")
380
381   def help(plugin, topic="")
382     "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"
383   end
384
385   attr_reader :i
386
387   def initialize
388     super
389     @i = Imdb.new(@bot)
390   end
391
392   # Find a person or movie on IMDB. A :type (name/title, default both) can be
393   # specified to limit the search to either.
394   #
395   def imdb(m, params)
396     if params[:movie]
397       movie = params[:movie].to_s
398       info = i.info(movie, :type => :title, :characters => true)
399     else
400       what = params[:what].to_s
401       type = params[:type].intern
402       info = i.info(what, :type => type)
403       if !info
404         m.reply "nothing found for #{what}"
405         return nil
406       end
407     end
408     if info.length == 1
409       m.reply Utils.decode_html_entities info.first.join("\n")
410     else
411       m.reply info.map { |si|
412         Utils.decode_html_entities si.join(" | ")
413       }.join("\n")
414     end
415   end
416
417   # Find the movies with a participation of :who in the year :year
418   # TODO: allow year to be either a year or a decade ('[in the] 1960s') 
419   #
420   def movies(m, params)
421     who = params[:who].to_s
422     years = params[:years]
423
424     name_urls = i.search(who, :type => :name)
425     unless name_urls
426       m.reply "nothing found about #{who}, sorry"
427       return
428     end
429
430     movie_urls = i.year_movies(name_urls, years)
431     debug movie_urls.inspect
432     debug movie_urls[0][1]
433
434     if movie_urls.length == 1 and movie_urls[0][1]
435       m.reply movie_urls.join("\n")
436     else
437       m.reply movie_urls.map { |si|
438         si[1] = "no movies in #{years}" unless si[1]
439         Utils.decode_html_entities si.join(" | ")
440       }.join("\n")
441     end
442   end
443
444   # Find the character played by :who in :movie
445   #
446   def character(m, params)
447     who = params[:who].to_s
448     movie = params[:movie].to_s
449
450     name_urls = i.search(who, :type => :name)
451     unless name_urls
452       m.reply "nothing found about #{who}, sorry"
453       return
454     end
455
456     movie_urls = i.search(movie, :type => :title)
457     unless movie_urls
458       m.reply "nothing found about #{who}, sorry"
459       return
460     end
461
462     info = i.name_in_movie(name_urls, movie_urls)
463     if info.empty?
464       m.reply "nothing found about #{who} in #{movie}, sorry"
465     else
466       m.reply info.join("\n")
467     end
468   end
469
470   # Report the characters in movie :movie
471   #
472   def characters(m, params)
473     movie = params[:movie].to_s
474
475     urls = i.search(movie, :type => :title)
476     unless urls
477       m.reply "nothing found about #{movie}"
478     end
479
480   end
481
482 end
483
484 plugin = ImdbPlugin.new
485
486 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
487 plugin.map "movies :prefix *who in [the] :years", :requirements => { :prefix => /with|by|from/, :years => /'?\d+s?/ }
488 plugin.map "character [played] by *who in *movie"
489 plugin.map "character of *who in *movie"
490 plugin.map "characters in *movie", :action => :imdb
491