2 # Copyright Michael Orlitzky
4 # http://michael.orlitzky.com/
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # http://www.fsf.org/licensing/licenses/gpl.html
22 class Youtube
< Website
24 VALID_YOUTUBE_URL_REGEX
= /^(http:\/\
/)?([a-z0-9]+\.)?youtube\.com\/((watch
\?v
=)|(v\
/))[a-z0-9_\-]+(\&.*)?\#?$/i
26 def self.owns_url
?(url
)
27 return url
=~ VALID_YOUTUBE_URL_REGEX
32 video_id
= self.parse_video_id()
34 # The video's URL (the "page data" URL) may be different from the
35 # URL that was passed to the program. We support the /v/video_id
36 # URL format, but that is *not* the main video page where we can
37 # retrieve the "t" parameter. We can only get that from the
38 # /watch?v=video_id form.
39 page_data_url
= "http://www.youtube.com/watch?v=#{video_id}"
40 page_data
= self.get_page_data(page_data_url
)
43 t_parameter
= self.parse_t_parameter(page_data
)
45 video_url
= "http://www.youtube.com/get_video?video_id=#{video_id}&t=#{t_parameter}"
51 def get_video_filename()
52 return (self.parse_video_id() +
'.flv')
58 # Get the video id from the URL. Should be relatively easy,
59 # unless Youtube supports some URL formats of which I'm unaware.
61 # Return nil if we get no matches below.
64 # Both URLs are fairly easy to parse if you handle
65 # them one at a time. The only tricky situation is when
66 # parameters like "&hl=en" are tacked on to the end.
67 # We'll call /watch?v=video_id the "first form."
68 first_form_video_id_regex
= /v=([0-9a-z_\-]+)/i
69 first_form_matches
= first_form_video_id_regex
.match(@url)
70 return first_form_matches
[1] if not (first_form_matches
.nil? ||
71 first_form_matches
.length
< 2)
73 # First form didn't work? Try the second.
74 second_form_video_id_regex
= /\/v\
/([0-9a-z_\-]+)/i
75 second_form_matches
= second_form_video_id_regex
.match(@url)
76 video_id
= second_form_matches
[1] if not (second_form_matches
.nil? ||
77 second_form_matches
.length
< 2)
83 # Parse out the "t" parameter from the video's page. I'm not sure
84 # what "t" stands for, but it's located in some JSON, and is required
85 # for the final video URL to work.
86 def parse_t_parameter(page_data
)
89 t_parameter_regex
= /\"t\"\:[[:space:]]\"([^\"]+?)\"/
90 matches
= t_parameter_regex
.match(page_data
)
91 t_parameter
= matches
[1] if not (matches
.nil? || matches
.length
< 2)