]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
imdb plugin: improve title fixing
[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   FINAL_ARTICLE_MATCH = /, ([A-Z]\S{0,2})$/
22
23   MATCHER = {
24     :title => TITLE_MATCH,
25     :name => NAME_MATCH,
26     :both => TITLE_OR_NAME_MATCH
27   }
28
29   def initialize(bot)
30     @bot = bot
31   end
32
33   def search(rawstr, rawopts={})
34     str = URI.escape(rawstr)
35     str << ";site=aka" if @bot.config['imdb.aka']
36     opts = rawopts.dup
37     opts[:type] = :both unless opts[:type]
38     return do_search(str, opts)
39   end
40
41   def do_search(str, opts={})
42     resp = nil
43     begin
44       resp = @bot.httputil.get_response(IMDB + "/find?q=#{str}",
45                                         :max_redir => -1)
46     rescue Exception => e
47       error e.message
48       warning e.backtrace.join("\n")
49       return nil
50     end
51
52
53     matcher = MATCHER[opts[:type]]
54     debug matcher.inspect
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)
94       when :name
95         results << info_name(sr)
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)
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
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       ratings = "no votes"
161       m = /<b>([0-9.]+)\/10<\/b>\n?\r?\s+<small>\(<a href="ratings">([0-9,]+) votes?<\/a>\)<\/small>/.match(resp.body)
162       if m
163         ratings = "#{m[1]}/10 (#{m[2]} voters)"
164       end
165
166       genre = Array.new
167       resp.body.scan(/<a href="\/Sections\/Genres\/[^\/]+\/">([^<]+)<\/a>/) do |gnr|
168         genre << gnr
169       end
170
171       plot = nil
172       data = grab_info(/Plot (?:Outline|Summary)/, resp.body)
173       if data
174         plot = "Plot: " + data.ircify_html.gsub(/\s+more$/,'')
175       end
176
177       info << ["Ratings: " << ratings, "Genre: " << genre.join('/') , plot].compact.join(". ")
178
179       return info
180     end
181     return nil
182   end
183
184   def info_name(sr)
185     resp = nil
186     begin
187       resp = @bot.httputil.get_response(IMDB + sr, :max_redir => -1)
188     rescue Exception => e
189       error e.message
190       warning e.backtrace.join("\n")
191       return nil
192     end
193
194     info = []
195
196     if resp.code == "200"
197       m = /<title>([^<]*)<\/title>/.match(resp.body)
198       return nil if !m
199       name = m[1]
200
201       info << "#{name} : http://us.imdb.com#{sr}"
202
203       birth = nil
204       data = grab_info("Date of Birth", resp.body)
205       if data
206         birth = "Birth: #{data.ircify_html.gsub(/\s+more$/,'')}"
207       end
208
209       death = nil
210       data = grab_info("Date of Death", resp.body)
211       if data
212         death = "Death: #{data.ircify_html.gsub(/\s+more$/,'')}"
213       end
214
215       info << [birth, death].compact.join('. ') if birth or death
216
217       movies = {}
218
219       filmorate = nil
220       begin
221         filmorate = @bot.httputil.get(IMDB + sr + "filmorate")
222       rescue Exception
223       end
224
225       if filmorate
226         filmorate.scan(/<div class="filmo">.*?<a href="\/title.*?<\/div>/m) { |str|
227           what = str.match(/<a name="[^"]+">([^<]+)<\/a>/)[1] rescue nil
228           next unless what
229           movies[what] = str.scan(TITLE_MATCH)[0..2].map { |url, tit|
230             fix_article(tit.ircify_html)
231           }
232         }
233       end
234
235       preferred = ['Actor', 'Director']
236       if resp.body.match(/Jump to filmography as:&nbsp;(.*?)<\/div>/)
237         txt = $1
238         preferred = txt.scan(/<a[^>]+>([^<]+)<\/a>/)[0..2].map { |pref|
239           pref.first
240         }
241       end
242
243       unless movies.empty?
244         all_keys = movies.keys.sort
245         debug all_keys.inspect
246         keys = []
247         preferred.each { |key|
248           keys << key if all_keys.include? key
249         }
250         keys = all_keys if keys.empty?
251         ar = []
252         keys.each { |key|
253           ar << key.dup
254           ar.last << ": " + movies[key].join('; ')
255         }
256         info << ar.join('. ')
257       end
258       return info
259
260     end
261     return nil
262   end
263 end
264
265 class ImdbPlugin < Plugin
266   BotConfig.register BotConfigBooleanValue.new('imdb.aka',
267     :default => true,
268     :desc => "Look for IMDB matches also in translated titles and other 'also known as' information")
269   BotConfig.register BotConfigBooleanValue.new('imdb.popular',
270     :default => true,
271     :desc => "Display info on popular IMDB entries matching the request closely")
272   BotConfig.register BotConfigBooleanValue.new('imdb.exact',
273     :default => true,
274     :desc => "Display info on IMDB entries matching the request exactly")
275   BotConfig.register BotConfigBooleanValue.new('imdb.fix_article',
276     :default => false,
277     :desc => "Try to detect an article placed at the end and move it in front of the title")
278
279   def help(plugin, topic="")
280     "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"
281   end
282
283   def imdb(m, params)
284     what = params[:what].to_s
285     type = params[:type].intern
286     i = Imdb.new(@bot)
287     info = i.info(what, :type => type)
288     if !info
289       m.reply "Nothing found for #{what}"
290       return nil
291     end
292     if info.length == 1
293       m.reply Utils.decode_html_entities info.first.join("\n")
294     else
295       m.reply info.map { |i|
296         Utils.decode_html_entities i.join(" | ")
297       }.join("\n")
298     end
299   end
300 end
301
302 plugin = ImdbPlugin.new
303 plugin.map "imdb [:type] *what", :requirements => { :type => /name|title/ }, :defaults => { :type => 'both' }
304