+ def choose_best_fmt_stream_url(fmt_stream_urls)
+ # Take a list, generated by get_fmt_stream_list(), and choose the
+ # best URL out of the bunch based on the video format.
+ fmt_stream_urls.each do |fs|
+ if fs =~ /video\/mp4/ and fs =~ /quality=large/
+ return fs
+ elsif fs =~ /quality=large/
+ return fs
+ elsif fs =~ /video\/mp4/
+ return fs
+ else
+ return fs
+ end
+ end
+ end
+
+
+ def unicode_unescape(string)
+ # Unescape sequences like '\u0026'.
+ # Ok, only '\u0026' for now.
+ return string.gsub('\u0026', '&')
+ end
+
+
+ def get_fmt_stream_list(page_data)
+ # This is another (new?) method of embedding the video URLs.
+ # The url_encoded_fmt_stream_map variable contains a list of URLs
+ # in the form url=foo1,url=foo2...
+ #
+ # It looks like the first one in the list is the highest
+ # quality? Let's just take that one for now.
+ fmt_stream_regex = /\"url_encoded_fmt_stream_map\": \"(.+?)\"/
+
+ matches = fmt_stream_regex.match(page_data)
+
+ if (matches.nil? || matches.length < 2)
+ raise StandardError.new("Could not parse the url_encoded_fmt_stream_map Flash variable.")
+ end
+
+ urlstring = matches[1]
+ urlstring.gsub!('url=', '')
+ urls = urlstring.split(',')
+
+ urls.each_index do |idx|
+ urls[idx] = self.unicode_unescape(urls[idx])
+ urls[idx] = CGI::unescape(urls[idx])
+ # Strip off everything after the first space in the URL.
+ # I don't know why this works, but if we leave the space
+ # in (encoded, even), Youtube throws us 403 errors.
+ urls[idx].gsub!(/ .+$/, '')
+ end
+
+ return urls
+ end
+
+