]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
imdb plugin: fix for the previous commit
[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, role_req)
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           role = nil
325           extra = nil
326           if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
327             role = $1
328             extra = "(#{$2.ircify_html})"
329           else
330             role = txt
331           end
332           next if role_req and not role.match(/^#{role_req}/i)
333           if comm
334             extra ||= ""
335             extra += comm.ircify_html if comm
336           end
337           role_array << [role, extra]
338         }
339         next if role_req and role_array.empty?
340
341         roles = role_array.map { |ar|
342           if role_req
343             ar[1] # works for us both if it's nil and if it's something
344           else
345             ar.compact.join(" ")
346           end
347         }.compact.join(', ')
348         roles = nil if roles.empty?
349         movies << [roles, title].compact.join(": ")
350       }
351
352       if movies.empty?
353         [name_url, nil]
354       else
355         [name_url, movies.join(" | ")]
356       end
357     }
358   end
359
360   def name_in_movie(name_urls, movie_urls)
361     info = []
362     movie_urls.each { |movie|
363       title_info = info_title(movie, :title_only => true)
364       valid = []
365
366       data = @bot.httputil.get(IMDB + movie + "fullcredits")
367       data.scan(CREDIT_NAME_MATCH).each { |url, name, role|
368         valid << [url, name.ircify_html, role.ircify_html] if name_urls.include?(url)
369       }
370       valid.each { |url, name, role|
371         info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
372       }
373     }
374     return info
375   end
376
377
378 end
379
380 class ImdbPlugin < Plugin
381   BotConfig.register BotConfigBooleanValue.new('imdb.aka',
382     :default => true,
383     :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
384   BotConfig.register BotConfigBooleanValue.new('imdb.popular',
385     :default => true,
386     :desc => "Display info on popular IMDB entries matching the request closely")
387   BotConfig.register BotConfigBooleanValue.new('imdb.exact',
388     :default => true,
389     :desc => "Display info on IMDB entries matching the request exactly")
390   BotConfig.register BotConfigBooleanValue.new('imdb.fix_article',
391     :default => false,
392     :desc => "Try to detect an article placed at the end and move it in front of the title")
393   BotConfig.register BotConfigBooleanValue.new('imdb.tv_series_in_movies',
394     :default => false,
395     :desc => "Whether searching movies by person/year should also return TV series")
396
397   def help(plugin, topic="")
398     "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"
399   end
400
401   attr_reader :i
402
403   def initialize
404     super
405     @i = Imdb.new(@bot)
406   end
407
408   # Find a person or movie on IMDB. A :type (name/title, default both) can be
409   # specified to limit the search to either.
410   #
411   def imdb(m, params)
412     if params[:movie]
413       movie = params[:movie].to_s
414       info = i.info(movie, :type => :title, :characters => true)
415     else
416       what = params[:what].to_s
417       type = params[:type].intern
418       info = i.info(what, :type => type)
419       if !info
420         m.reply "nothing found for #{what}"
421         return nil
422       end
423     end
424     if info.length == 1
425       m.reply Utils.decode_html_entities info.first.join("\n")
426     else
427       m.reply info.map { |si|
428         Utils.decode_html_entities si.join(" | ")
429       }.join("\n")
430     end
431   end
432
433   # Find the movies with a participation of :who in the year :year
434   # TODO: allow year to be either a year or a decade ('[in the] 1960s') 
435   #
436   def movies(m, params)
437     who = params[:who].to_s
438     years = params[:years]
439     role = params[:role]
440     if role and role.downcase == 'anything'
441       role = nil
442     elsif not role
443       case params[:prefix].intern
444       when :with
445         role = /actor|actress/i
446       when :by
447         role = 'director'
448       end
449     end
450
451     name_urls = i.search(who, :type => :name)
452     unless name_urls
453       m.reply "nothing found about #{who}, sorry"
454       return
455     end
456
457     movie_urls = i.year_movies(name_urls, years, role)
458     debug movie_urls.inspect
459     debug movie_urls[0][1]
460
461     if movie_urls.length == 1 and movie_urls[0][1]
462       m.reply movie_urls.join("\n")
463     else
464       m.reply movie_urls.map { |si|
465         si[1] = "no movies in #{years}" unless si[1]
466         Utils.decode_html_entities si.join(" | ")
467       }.join("\n")
468     end
469   end
470
471   # Find the character played by :who in :movie
472   #
473   def character(m, params)
474     who = params[:who].to_s
475     movie = params[:movie].to_s
476
477     name_urls = i.search(who, :type => :name)
478     unless name_urls
479       m.reply "nothing found about #{who}, sorry"
480       return
481     end
482
483     movie_urls = i.search(movie, :type => :title)
484     unless movie_urls
485       m.reply "nothing found about #{who}, sorry"
486       return
487     end
488
489     info = i.name_in_movie(name_urls, movie_urls)
490     if info.empty?
491       m.reply "nothing found about #{who} in #{movie}, sorry"
492     else
493       m.reply info.join("\n")
494     end
495   end
496
497   # Report the characters in movie :movie
498   #
499   def characters(m, params)
500     movie = params[:movie].to_s
501
502     urls = i.search(movie, :type => :title)
503     unless urls
504       m.reply "nothing found about #{movie}"
505     end
506
507   end
508
509 end
510
511 plugin = ImdbPlugin.new
512
513 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
514 plugin.map "movies :prefix *who in [the] :years [as :role]", :requirements => { :prefix => /with|by|from/, :years => /'?\d+s?/ }
515 plugin.map "character [played] by *who in *movie"
516 plugin.map "character of *who in *movie"
517 plugin.map "characters in *movie", :action => :imdb
518