]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
imdb plugin: command to display the characters (and actors) in a given movie
[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 = URI.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 year = opts[:movies_in_year]
215         filmoyear = @bot.httputil.get(IMDB + sr + "filmoyear")
216         if filmoyear
217           info << filmoyear.scan(/#{TITLE_MATCH} \(#{year}\)[^\[\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, year)
284     urls.map { |url|
285       info = info_name(url, :movies_in_year => year)
286
287       debug info.inspect
288
289       name_url = info.first
290       data = info[1]
291
292       movies = []
293       # Sort by pre-title putting movies before TV series
294       data.sort { |a, b|
295         aclip = a[1][0,5]
296         bclip = b[1][0,5]
297         quot = '&#34;'
298         (aclip == quot ? 1 : -1) <=> (bclip == quot ? 1 : -1)
299       }.each { |url, pre_title, pre_roles|
300         title = fix_article(pre_title.ircify_html)
301         if title[0] == ?" and not @bot.config['imdb.tv_series_in_movies']
302           next
303         end
304         role_array = []
305         pre_roles.strip.scan(/\[([^\]]+)\]((?:\s+\([^\[]+\))+)?/) { |txt, comm|
306           if txt.match(/^(.*)\s+\.\.\.\.\s+(.*)$/)
307             role_array << "#{$1} (#{$2})"
308           else
309             role_array << txt
310           end
311           role_array.last << " " + comm.ircify_html if comm
312         }
313
314         roles = role_array.join(', ')
315         movies << [roles, title].join(": ")
316       }
317
318       if movies.empty?
319         [name_url, nil]
320       else
321         [name_url, movies.join(" | ")]
322       end
323     }
324   end
325
326   def name_in_movie(name_urls, movie_urls)
327     info = []
328     movie_urls.each { |movie|
329       title_info = info_title(movie, :title_only => true)
330       valid = []
331
332       data = @bot.httputil.get(IMDB + movie + "fullcredits")
333       data.scan(CREDIT_NAME_MATCH).each { |url, name, role|
334         valid << [url, name.ircify_html, role.ircify_html] if name_urls.include?(url)
335       }
336       valid.each { |url, name, role|
337         info << "%s : %s was %s in %s" % [name, IMDB + url, role, title_info]
338       }
339     }
340     return info
341   end
342
343
344 end
345
346 class ImdbPlugin < Plugin
347   BotConfig.register BotConfigBooleanValue.new('imdb.aka',
348     :default => true,
349     :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
350   BotConfig.register BotConfigBooleanValue.new('imdb.popular',
351     :default => true,
352     :desc => "Display info on popular IMDB entries matching the request closely")
353   BotConfig.register BotConfigBooleanValue.new('imdb.exact',
354     :default => true,
355     :desc => "Display info on IMDB entries matching the request exactly")
356   BotConfig.register BotConfigBooleanValue.new('imdb.fix_article',
357     :default => false,
358     :desc => "Try to detect an article placed at the end and move it in front of the title")
359   BotConfig.register BotConfigBooleanValue.new('imdb.tv_series_in_movies',
360     :default => false,
361     :desc => "Whether searching movies by person/year should also return TV series")
362
363   def help(plugin, topic="")
364     "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"
365   end
366
367   attr_reader :i
368
369   def initialize
370     super
371     @i = Imdb.new(@bot)
372   end
373
374   # Find a person or movie on IMDB. A :type (name/title, default both) can be
375   # specified to limit the search to either.
376   #
377   def imdb(m, params)
378     if params[:movie]
379       movie = params[:movie].to_s
380       info = i.info(movie, :type => :title, :characters => true)
381     else
382       what = params[:what].to_s
383       type = params[:type].intern
384       info = i.info(what, :type => type)
385       if !info
386         m.reply "nothing found for #{what}"
387         return nil
388       end
389     end
390     if info.length == 1
391       m.reply Utils.decode_html_entities info.first.join("\n")
392     else
393       m.reply info.map { |si|
394         Utils.decode_html_entities si.join(" | ")
395       }.join("\n")
396     end
397   end
398
399   # Find the movies with a participation of :who in the year :year
400   # TODO: allow year to be either a year or a decade ('[in the] 1960s') 
401   #
402   def movies(m, params)
403     who = params[:who].to_s
404     year = params[:year]
405
406     name_urls = i.search(who, :type => :name)
407     unless name_urls
408       m.reply "nothing found about #{who}, sorry"
409       return
410     end
411
412     movie_urls = i.year_movies(name_urls, year)
413     debug movie_urls.inspect
414     debug movie_urls[0][1]
415
416     if movie_urls.length == 1 and movie_urls[0][1]
417       m.reply movie_urls.join("\n")
418     else
419       m.reply movie_urls.map { |si|
420         si[1] = "no movies in #{year}" unless si[1]
421         Utils.decode_html_entities si.join(" | ")
422       }.join("\n")
423     end
424   end
425
426   # Find the character played by :who in :movie
427   #
428   def character(m, params)
429     who = params[:who].to_s
430     movie = params[:movie].to_s
431
432     name_urls = i.search(who, :type => :name)
433     unless name_urls
434       m.reply "nothing found about #{who}, sorry"
435       return
436     end
437
438     movie_urls = i.search(movie, :type => :title)
439     unless movie_urls
440       m.reply "nothing found about #{who}, sorry"
441       return
442     end
443
444     info = i.name_in_movie(name_urls, movie_urls)
445     if info.empty?
446       m.reply "nothing found about #{who} in #{movie}, sorry"
447     else
448       m.reply info.join("\n")
449     end
450   end
451
452   # Report the characters in movie :movie
453   #
454   def characters(m, params)
455     movie = params[:movie].to_s
456
457     urls = i.search(movie, :type => :title)
458     unless urls
459       m.reply "nothing found about #{movie}"
460     end
461
462   end
463
464 end
465
466 plugin = ImdbPlugin.new
467
468 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
469 plugin.map "movies :prefix *who in :year", :requirements => { :prefix => /with|by|from/, :year => /\d+/ }
470 plugin.map "character [played] by *who in *movie"
471 plugin.map "character of *who in *movie"
472 plugin.map "characters in *movie", :action => :imdb
473