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