youtube: not all urls have v= as first CGI param
[rbot] / data / rbot / plugins / youtube.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: YouTube plugin for rbot
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 #
8 # Copyright:: (C) 2008 Giuseppe Bilotta
9
10
11 class YouTubePlugin < Plugin
12   YOUTUBE_SEARCH = "http://gdata.youtube.com/feeds/api/videos?vq=%{words}&orderby=relevance"
13   YOUTUBE_VIDEO = "http://gdata.youtube.com/feeds/api/videos/%{id}"
14
15   YOUTUBE_VIDEO_URLS = %r{youtube.com/(?:watch\?(?:.*&)?v=|v/)(.*?)(&.*)?$}
16
17   Config.register Config::IntegerValue.new('youtube.hits',
18     :default => 3,
19     :desc => "Number of hits to return from YouTube searches")
20   Config.register Config::IntegerValue.new('youtube.descs',
21     :default => 3,
22     :desc => "When set to n > 0, the bot will return the description of the first n videos found")
23   Config.register Config::BooleanValue.new('youtube.formats',
24     :default => true,
25     :desc => "Should the bot display alternative URLs (swf, rstp) for YouTube videos?")
26
27   def youtube_filter(s)
28     loc = Utils.check_location(s, /youtube\.com/)
29     return nil unless loc
30     if s[:text].include? '<link rel="alternate" type="text/xml+oembed"'
31       vid = @bot.filter(:"youtube.video", s)
32       return nil unless vid
33       content = _("Category: %{cat}. Rating: %{rating}. Author: %{author}. Duration: %{duration}. %{views} views, faved %{faves} times. %{desc}") % vid
34       return vid.merge(:content => content)
35     elsif s[:text].include? '<!-- start search results -->'
36       vids = @bot.filter(:"youtube.search", s)[:videos]
37       if !vids.empty?
38         return nil # TODO
39       end
40     end
41     # otherwise, just grab the proper div
42     if defined? Hpricot
43       content = (Hpricot(s[:text])/".watch-video-desc").to_html.ircify_html
44     end
45     # suboptimal, but still better than the default HTML info extractor
46     dm = /<div\s+class="watch-video-desc"[^>]*>/.match(s[:text])
47     content ||= dm ? dm.post_match.ircify_html : '(no description found)'
48     return {:title => s[:text].ircify_html_title, :content => content}
49   end
50
51   def youtube_apivideo_filter(s)
52     # This filter can be used either
53     e = s[:rexml] || REXML::Document.new(s[:text]).elements["entry"]
54     # TODO precomputing mg doesn't work on my REXML, despite what the doc
55     # says?
56     #   mg = e.elements["media:group"]
57     #   :title => mg["media:title"].text
58     # fails because "media:title" is not an Integer. Bah
59     vid = {
60       :formats => [],
61       :author => (e.elements["author/name"].text rescue nil),
62       :title =>  (e.elements["media:group/media:title"].text rescue nil),
63       :desc =>   (e.elements["media:group/media:description"].text rescue nil),
64       :cat => (e.elements["media:group/media:category"].text rescue nil),
65       :seconds => (e.elements["media:group/yt:duration/"].attributes["seconds"].to_i rescue nil),
66       :url => (e.elements["media:group/media:player/"].attributes["url"] rescue nil),
67       :rating => (("%s/%s" % [e.elements["gd:rating"].attributes["average"], e.elements["gd:rating/@max"].value]) rescue nil),
68       :views => (e.elements["yt:statistics"].attributes["viewCount"] rescue nil),
69       :faves => (e.elements["yt:statistics"].attributes["favoriteCount"] rescue nil)
70     }
71     if vid[:desc]
72       vid[:desc].gsub!(/\s+/m, " ")
73     end
74     if secs = vid[:seconds]
75       vid[:duration] = Utils.secs_to_short(secs)
76     else
77       vid[:duration] = _("unknown duration")
78     end
79     e.elements.each("media:group/media:content") { |c|
80       if url = (c.attributes["url"] rescue nil)
81         type = c.attributes["type"] rescue nil
82         medium = c.attributes["medium"] rescue nil
83         expression = c.attributes["expression"] rescue nil
84         seconds = c.attributes["duration"].to_i rescue nil
85         fmt = case num_fmt = (c.attributes["yt:format"] rescue nil)
86               when "1"
87                 "h263+amr"
88               when "5"
89                 "swf"
90               when "6"
91                 "mp4+aac"
92               when nil
93                 nil
94               else
95                 num_fmt
96               end
97         vid[:formats] << {
98           :url => url, :type => type,
99           :medium => medium, :expression => expression,
100           :seconds => seconds,
101           :numeric_format => num_fmt,
102           :format => fmt
103         }.delete_if { |k, v| v.nil? }
104         if seconds
105           vid[:formats].last[:duration] = Utils.secs_to_short(seconds)
106         else
107           vid[:formats].last[:duration] = _("unknown duration")
108         end
109       end
110     }
111     debug vid
112     return vid
113   end
114
115   def youtube_apisearch_filter(s)
116     vids = []
117     title = nil
118     begin
119       doc = REXML::Document.new(s[:text])
120       title = doc.elements["feed/title"].text
121       doc.elements.each("*/entry") { |e|
122         vids << @bot.filter(:"youtube.apivideo", :rexml => e)
123       }
124       debug vids
125     rescue => e
126       debug e
127     end
128     return {:title => title, :vids => vids}
129   end
130
131   def youtube_search_filter(s)
132     # TODO
133     # hits = s[:hits] || @bot.config['youtube.hits']
134     # scrap the videos
135     return []
136   end
137
138   # Filter a YouTube video URL
139   def youtube_video_filter(s)
140     id = s[:youtube_video_id]
141     if not id
142       url = s.key?(:headers) ? s[:headers]['x-rbot-location'].first : s[:url]
143       debug url
144       id = YOUTUBE_VIDEO_URLS.match(url).captures.first rescue nil
145     end
146     return nil unless id
147
148     debug id
149
150     url = YOUTUBE_VIDEO % {:id => id}
151     resp, xml = @bot.httputil.get_response(url)
152     unless Net::HTTPSuccess === resp
153       debug("error looking for movie %{id} on youtube: %{e}" % {:id => id, :e => xml})
154       return nil
155     end
156     debug xml
157     begin
158       return @bot.filter(:"youtube.apivideo", DataStream.new(xml, s))
159     rescue => e
160       debug e
161       return nil
162     end
163   end
164
165   def initialize
166     super
167     @bot.register_filter(:youtube, :htmlinfo) { |s| youtube_filter(s) }
168     @bot.register_filter(:apisearch, :youtube) { |s| youtube_apisearch_filter(s) }
169     @bot.register_filter(:apivideo, :youtube) { |s| youtube_apivideo_filter(s) }
170     @bot.register_filter(:search, :youtube) { |s| youtube_search_filter(s) }
171     @bot.register_filter(:video, :youtube) { |s| youtube_video_filter(s) }
172   end
173
174   def info(m, params)
175     movie = params[:movie]
176     id = nil
177     if movie =~ /^[A-Za-z0-9]+$/
178       id = movie.dup
179     end
180
181     vid = @bot.filter(:"youtube.video", :url => movie, :youtube_video_id => id)
182     if vid
183       str = _("%{bold}%{title}%{bold} [%{cat}] %{rating} @ %{url} by %{author} (%{duration}). %{views} views, faved %{faves} times. %{desc}") %
184         {:bold => Bold}.merge(vid)
185       if @bot.config['youtube.formats'] and not vid[:formats].empty?
186         str << _("\n -- also available at: ")
187         str << vid[:formats].inject([]) { |list, fmt|
188           list << ("%{url} %{type} %{format} (%{duration} %{expression} %{medium})" % fmt)
189         }.join(', ')
190       end
191       m.reply str
192     else
193       m.reply(_("couldn't retrieve video info") % {:id => id})
194     end
195   end
196
197   def search(m, params)
198     what = params[:words].to_s
199     searchfor = CGI.escape what
200     url = YOUTUBE_SEARCH % {:words => searchfor}
201     resp, xml = @bot.httputil.get_response(url)
202     unless Net::HTTPSuccess === resp
203       m.reply(_("error looking for %{what} on youtube: %{e}") % {:what => what, :e => xml})
204       return
205     end
206     debug "filtering XML"
207     vids = @bot.filter(:"youtube.apisearch", DataStream.new(xml, params))[:vids][0, @bot.config['youtube.hits']]
208     debug vids
209     case vids.length
210     when 0
211       m.reply _("no videos found for %{what}") % {:what => what}
212       return
213     when 1
214       show = "%{title} (%{duration}) [%{desc}] @ %{url}" % vids.first
215       m.reply _("One video found for %{what}: %{show}") % {:what => what, :show => show}
216     else
217       idx = 0
218       shorts = vids.inject([]) { |list, el|
219         idx += 1
220         list << ("#{idx}. %{bold}%{title}%{bold} (%{duration}) @ %{url}" % {:bold => Bold}.merge(el))
221       }.join(" | ")
222       m.reply(_("Videos for %{what}: %{shorts}") % {:what =>what, :shorts => shorts},
223               :split_at => /\s+\|\s+/)
224       if (descs = @bot.config['youtube.descs']) > 0
225         vids[0, descs].each_with_index { |v, i|
226           m.reply("[#{i+1}] %{title} (%{duration}): %{desc}" % v, :overlong => :truncate)
227         }
228       end
229     end
230   end
231
232 end
233
234 plugin = YouTubePlugin.new
235
236 plugin.map "youtube info :movie", :action => 'info', :threaded => true
237 plugin.map "youtube [search] *words", :action => 'search', :threaded => true