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