]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/imdb.rb
Plugin header boilerplating.
[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 # Copyright:: (C) 2005 Arnaud Cornet
8 # License:: MIT license
9
10 require 'net/http'
11 require 'cgi'
12 require 'uri/common'
13
14 class Imdb
15   def initialize(bot)
16     @bot = bot
17   end
18
19   def search(rawstr)
20     str = URI.escape(rawstr)
21     @http = @bot.httputil.get_proxy(URI.parse("http://us.imdb.com/find?q=#{str}"))
22     @http.start
23     begin
24     resp, data = @http.get("/find?q=#{str}", "User-Agent" => "Mozilla/5.0")
25     rescue Net::ProtoRetriableError => detail
26       head = detail.data
27       if head.code == "301" or head.code == "302"
28             return head['location'].gsub(/http:\/\/us.imdb.com/, "").gsub(/\?.*/, "")
29         end
30     end
31     if resp.code == "200"
32       m = /<a href="(\/title\/tt[0-9]+\/?)[^"]*"(:?[^>]*)>([^<]*)<\/a>/.match(resp.body)
33       if m
34         url = m[1]
35         title = m[2]
36         return url
37       end
38     elsif resp.code == "302"
39       return resp['location'].gsub(/http:\/\/us.imdb.com/, "").gsub(/\?.*/, "")
40     end
41     return nil
42   end
43
44   def info(rawstr)
45     sr = search(rawstr)
46     if !sr
47       debug "IMDB: search returned NIL"
48       return nil
49     end
50     resp, data = @http.get(sr, "User-Agent" =>
51       "Mozilla/5.0 (compatible; Konqueror/3.1; Linux)")
52     if resp.code == "200"
53       m = /<title>([^<]*)<\/title>/.match(resp.body)
54       return nil if !m
55       title = CGI.unescapeHTML(m[1])
56
57       m = /<b>([0-9.]+)\/10<\/b> \(([0-9,]+) votes?\)/.match(resp.body)
58       return nil if !m
59       score = m[1]
60       votes = m[2]
61
62       genre = Array.new
63       resp.body.scan(/<a href="\/Sections\/Genres\/[^\/]+\/">([^<]+)<\/a>/) do |gnr|
64         genre << gnr
65       end
66       return ["http://us.imdb.com" + sr, title, score, votes,
67         genre]
68     end
69     return nil
70   end
71 end
72
73 class ImdbPlugin < Plugin
74   def help(plugin, topic="")
75     "imdb <string> => search http://www.imdb.org for <string>"
76   end
77
78   def imdb(m, params)
79     what = params[:what].to_s
80     i = Imdb.new(@bot)
81     info = i.info(what)
82     if !info
83       m.reply "Nothing found for #{what}"
84       return nil
85     end
86     m.reply "#{info[1]} : #{info[0]}"
87     m.reply "Ratings: #{info[2]}/10 (#{info[3]} voters). Genre: #{info[4].join('/')}"
88   end
89 end
90
91 plugin = ImdbPlugin.new
92 plugin.map "imdb *what"
93