InfoExtractors.py 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import HTMLParser
  5. import httplib
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import time
  11. import urllib
  12. import urllib2
  13. import email.utils
  14. import xml.etree.ElementTree
  15. import random
  16. import math
  17. from urlparse import parse_qs
  18. try:
  19. import cStringIO as StringIO
  20. except ImportError:
  21. import StringIO
  22. from utils import *
  23. class InfoExtractor(object):
  24. """Information Extractor class.
  25. Information extractors are the classes that, given a URL, extract
  26. information about the video (or videos) the URL refers to. This
  27. information includes the real video URL, the video title, author and
  28. others. The information is stored in a dictionary which is then
  29. passed to the FileDownloader. The FileDownloader processes this
  30. information possibly downloading the video to the file system, among
  31. other possible outcomes.
  32. The dictionaries must include the following fields:
  33. id: Video identifier.
  34. url: Final video URL.
  35. uploader: Nickname of the video uploader.
  36. upload_date: Video upload date (YYYYMMDD).
  37. title: Video title, unescaped.
  38. ext: Video filename extension.
  39. The following fields are optional:
  40. format: The video format, defaults to ext (used for --get-format)
  41. thumbnail: Full URL to a video thumbnail image.
  42. description: One-line video description.
  43. player_url: SWF Player URL (used for rtmpdump).
  44. Subclasses of this one should re-define the _real_initialize() and
  45. _real_extract() methods and define a _VALID_URL regexp.
  46. Probably, they should also be added to the list of extractors.
  47. _real_extract() must return a *list* of information dictionaries as
  48. described above.
  49. """
  50. _ready = False
  51. _downloader = None
  52. def __init__(self, downloader=None):
  53. """Constructor. Receives an optional downloader."""
  54. self._ready = False
  55. self.set_downloader(downloader)
  56. def suitable(self, url):
  57. """Receives a URL and returns True if suitable for this IE."""
  58. return re.match(self._VALID_URL, url) is not None
  59. def initialize(self):
  60. """Initializes an instance (authentication, etc)."""
  61. if not self._ready:
  62. self._real_initialize()
  63. self._ready = True
  64. def extract(self, url):
  65. """Extracts URL information and returns it in list of dicts."""
  66. self.initialize()
  67. return self._real_extract(url)
  68. def set_downloader(self, downloader):
  69. """Sets the downloader for this IE."""
  70. self._downloader = downloader
  71. def _real_initialize(self):
  72. """Real initialization process. Redefine in subclasses."""
  73. pass
  74. def _real_extract(self, url):
  75. """Real extraction process. Redefine in subclasses."""
  76. pass
  77. class YoutubeIE(InfoExtractor):
  78. """Information extractor for youtube.com."""
  79. _VALID_URL = r"""^
  80. (
  81. (?:https?://)? # http(s):// (optional)
  82. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  83. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  84. (?:.*?\#/)? # handle anchor (#/) redirect urls
  85. (?!view_play_list|my_playlists|artist|playlist) # ignore playlist URLs
  86. (?: # the various things that can precede the ID:
  87. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  88. |(?: # or the v= param in all its forms
  89. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  90. (?:\?|\#!?) # the params delimiter ? or # or #!
  91. (?:.+&)? # any other preceding param (like /?s=tuff&v=xxxx)
  92. v=
  93. )
  94. )? # optional -> youtube.com/xxxx is OK
  95. )? # all until now is optional -> you can pass the naked ID
  96. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  97. (?(1).+)? # if we found the ID, everything can follow
  98. $"""
  99. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  100. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  101. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  102. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  103. _NETRC_MACHINE = 'youtube'
  104. # Listed in order of quality
  105. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  106. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  107. _video_extensions = {
  108. '13': '3gp',
  109. '17': 'mp4',
  110. '18': 'mp4',
  111. '22': 'mp4',
  112. '37': 'mp4',
  113. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  114. '43': 'webm',
  115. '44': 'webm',
  116. '45': 'webm',
  117. '46': 'webm',
  118. }
  119. _video_dimensions = {
  120. '5': '240x400',
  121. '6': '???',
  122. '13': '???',
  123. '17': '144x176',
  124. '18': '360x640',
  125. '22': '720x1280',
  126. '34': '360x640',
  127. '35': '480x854',
  128. '37': '1080x1920',
  129. '38': '3072x4096',
  130. '43': '360x640',
  131. '44': '480x854',
  132. '45': '720x1280',
  133. '46': '1080x1920',
  134. }
  135. IE_NAME = u'youtube'
  136. def suitable(self, url):
  137. """Receives a URL and returns True if suitable for this IE."""
  138. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  139. def report_lang(self):
  140. """Report attempt to set language."""
  141. self._downloader.to_screen(u'[youtube] Setting language')
  142. def report_login(self):
  143. """Report attempt to log in."""
  144. self._downloader.to_screen(u'[youtube] Logging in')
  145. def report_age_confirmation(self):
  146. """Report attempt to confirm age."""
  147. self._downloader.to_screen(u'[youtube] Confirming age')
  148. def report_video_webpage_download(self, video_id):
  149. """Report attempt to download video webpage."""
  150. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  151. def report_video_info_webpage_download(self, video_id):
  152. """Report attempt to download video info webpage."""
  153. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  154. def report_video_subtitles_download(self, video_id):
  155. """Report attempt to download video info webpage."""
  156. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  157. def report_information_extraction(self, video_id):
  158. """Report attempt to extract video information."""
  159. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  160. def report_unavailable_format(self, video_id, format):
  161. """Report extracted video URL."""
  162. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  163. def report_rtmp_download(self):
  164. """Indicate the download will use the RTMP protocol."""
  165. self._downloader.to_screen(u'[youtube] RTMP download detected')
  166. def _closed_captions_xml_to_srt(self, xml_string):
  167. srt = ''
  168. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  169. # TODO parse xml instead of regex
  170. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  171. if not dur: dur = '4'
  172. start = float(start)
  173. end = start + float(dur)
  174. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  175. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  176. caption = unescapeHTML(caption)
  177. caption = unescapeHTML(caption) # double cycle, intentional
  178. srt += str(n+1) + '\n'
  179. srt += start + ' --> ' + end + '\n'
  180. srt += caption + '\n\n'
  181. return srt
  182. def _print_formats(self, formats):
  183. print('Available formats:')
  184. for x in formats:
  185. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  186. def _real_initialize(self):
  187. if self._downloader is None:
  188. return
  189. username = None
  190. password = None
  191. downloader_params = self._downloader.params
  192. # Attempt to use provided username and password or .netrc data
  193. if downloader_params.get('username', None) is not None:
  194. username = downloader_params['username']
  195. password = downloader_params['password']
  196. elif downloader_params.get('usenetrc', False):
  197. try:
  198. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  199. if info is not None:
  200. username = info[0]
  201. password = info[2]
  202. else:
  203. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  204. except (IOError, netrc.NetrcParseError), err:
  205. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  206. return
  207. # Set language
  208. request = urllib2.Request(self._LANG_URL)
  209. try:
  210. self.report_lang()
  211. urllib2.urlopen(request).read()
  212. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  213. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % compat_str(err))
  214. return
  215. # No authentication to be performed
  216. if username is None:
  217. return
  218. # Log in
  219. login_form = {
  220. 'current_form': 'loginForm',
  221. 'next': '/',
  222. 'action_login': 'Log In',
  223. 'username': username,
  224. 'password': password,
  225. }
  226. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  227. try:
  228. self.report_login()
  229. login_results = urllib2.urlopen(request).read()
  230. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  231. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  232. return
  233. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  234. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  235. return
  236. # Confirm age
  237. age_form = {
  238. 'next_url': '/',
  239. 'action_confirm': 'Confirm',
  240. }
  241. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  242. try:
  243. self.report_age_confirmation()
  244. age_results = urllib2.urlopen(request).read()
  245. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  246. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  247. return
  248. def _real_extract(self, url):
  249. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  250. mobj = re.search(self._NEXT_URL_RE, url)
  251. if mobj:
  252. url = 'http://www.youtube.com/' + urllib.unquote(mobj.group(1)).lstrip('/')
  253. # Extract video id from URL
  254. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  255. if mobj is None:
  256. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  257. return
  258. video_id = mobj.group(2)
  259. # Get video webpage
  260. self.report_video_webpage_download(video_id)
  261. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id)
  262. try:
  263. video_webpage = urllib2.urlopen(request).read()
  264. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  265. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  266. return
  267. # Attempt to extract SWF player URL
  268. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  269. if mobj is not None:
  270. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  271. else:
  272. player_url = None
  273. # Get video info
  274. self.report_video_info_webpage_download(video_id)
  275. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  276. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  277. % (video_id, el_type))
  278. request = urllib2.Request(video_info_url)
  279. try:
  280. video_info_webpage = urllib2.urlopen(request).read()
  281. video_info = parse_qs(video_info_webpage)
  282. if 'token' in video_info:
  283. break
  284. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  285. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  286. return
  287. if 'token' not in video_info:
  288. if 'reason' in video_info:
  289. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  290. else:
  291. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  292. return
  293. # Check for "rental" videos
  294. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  295. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  296. return
  297. # Start extracting information
  298. self.report_information_extraction(video_id)
  299. # uploader
  300. if 'author' not in video_info:
  301. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  302. return
  303. video_uploader = urllib.unquote_plus(video_info['author'][0])
  304. # title
  305. if 'title' not in video_info:
  306. self._downloader.trouble(u'ERROR: unable to extract video title')
  307. return
  308. video_title = urllib.unquote_plus(video_info['title'][0])
  309. video_title = video_title.decode('utf-8')
  310. # thumbnail image
  311. if 'thumbnail_url' not in video_info:
  312. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  313. video_thumbnail = ''
  314. else: # don't panic if we can't find it
  315. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  316. # upload date
  317. upload_date = u'NA'
  318. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  319. if mobj is not None:
  320. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  321. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  322. for expression in format_expressions:
  323. try:
  324. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  325. except:
  326. pass
  327. # description
  328. video_description = get_element_by_id("eow-description", video_webpage.decode('utf8'))
  329. if video_description: video_description = clean_html(video_description)
  330. else: video_description = ''
  331. # closed captions
  332. video_subtitles = None
  333. if self._downloader.params.get('writesubtitles', False):
  334. try:
  335. self.report_video_subtitles_download(video_id)
  336. request = urllib2.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  337. try:
  338. srt_list = urllib2.urlopen(request).read()
  339. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  340. raise Trouble(u'WARNING: unable to download video subtitles: %s' % compat_str(err))
  341. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  342. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  343. if not srt_lang_list:
  344. raise Trouble(u'WARNING: video has no closed captions')
  345. if self._downloader.params.get('subtitleslang', False):
  346. srt_lang = self._downloader.params.get('subtitleslang')
  347. elif 'en' in srt_lang_list:
  348. srt_lang = 'en'
  349. else:
  350. srt_lang = srt_lang_list.keys()[0]
  351. if not srt_lang in srt_lang_list:
  352. raise Trouble(u'WARNING: no closed captions found in the specified language')
  353. request = urllib2.Request('http://www.youtube.com/api/timedtext?lang=%s&name=%s&v=%s' % (srt_lang, srt_lang_list[srt_lang], video_id))
  354. try:
  355. srt_xml = urllib2.urlopen(request).read()
  356. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  357. raise Trouble(u'WARNING: unable to download video subtitles: %s' % compat_str(err))
  358. if not srt_xml:
  359. raise Trouble(u'WARNING: unable to download video subtitles')
  360. video_subtitles = self._closed_captions_xml_to_srt(srt_xml.decode('utf-8'))
  361. except Trouble as trouble:
  362. self._downloader.trouble(trouble[0])
  363. if 'length_seconds' not in video_info:
  364. self._downloader.trouble(u'WARNING: unable to extract video duration')
  365. video_duration = ''
  366. else:
  367. video_duration = urllib.unquote_plus(video_info['length_seconds'][0])
  368. # token
  369. video_token = urllib.unquote_plus(video_info['token'][0])
  370. # Decide which formats to download
  371. req_format = self._downloader.params.get('format', None)
  372. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  373. self.report_rtmp_download()
  374. video_url_list = [(None, video_info['conn'][0])]
  375. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  376. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  377. url_data = [parse_qs(uds) for uds in url_data_strs]
  378. url_data = filter(lambda ud: 'itag' in ud and 'url' in ud, url_data)
  379. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  380. format_limit = self._downloader.params.get('format_limit', None)
  381. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  382. if format_limit is not None and format_limit in available_formats:
  383. format_list = available_formats[available_formats.index(format_limit):]
  384. else:
  385. format_list = available_formats
  386. existing_formats = [x for x in format_list if x in url_map]
  387. if len(existing_formats) == 0:
  388. self._downloader.trouble(u'ERROR: no known formats available for video')
  389. return
  390. if self._downloader.params.get('listformats', None):
  391. self._print_formats(existing_formats)
  392. return
  393. if req_format is None or req_format == 'best':
  394. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  395. elif req_format == 'worst':
  396. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  397. elif req_format in ('-1', 'all'):
  398. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  399. else:
  400. # Specific formats. We pick the first in a slash-delimeted sequence.
  401. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  402. req_formats = req_format.split('/')
  403. video_url_list = None
  404. for rf in req_formats:
  405. if rf in url_map:
  406. video_url_list = [(rf, url_map[rf])]
  407. break
  408. if video_url_list is None:
  409. self._downloader.trouble(u'ERROR: requested format not available')
  410. return
  411. else:
  412. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  413. return
  414. results = []
  415. for format_param, video_real_url in video_url_list:
  416. # Extension
  417. video_extension = self._video_extensions.get(format_param, 'flv')
  418. video_format = '{} - {}'.format(format_param.decode('utf-8') if format_param else video_extension.decode('utf-8'),
  419. self._video_dimensions.get(format_param, '???'))
  420. results.append({
  421. 'id': video_id.decode('utf-8'),
  422. 'url': video_real_url.decode('utf-8'),
  423. 'uploader': video_uploader.decode('utf-8'),
  424. 'upload_date': upload_date,
  425. 'title': video_title,
  426. 'ext': video_extension.decode('utf-8'),
  427. 'format': video_format,
  428. 'thumbnail': video_thumbnail.decode('utf-8'),
  429. 'description': video_description,
  430. 'player_url': player_url,
  431. 'subtitles': video_subtitles,
  432. 'duration': video_duration
  433. })
  434. return results
  435. class MetacafeIE(InfoExtractor):
  436. """Information Extractor for metacafe.com."""
  437. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  438. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  439. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  440. IE_NAME = u'metacafe'
  441. def __init__(self, downloader=None):
  442. InfoExtractor.__init__(self, downloader)
  443. def report_disclaimer(self):
  444. """Report disclaimer retrieval."""
  445. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  446. def report_age_confirmation(self):
  447. """Report attempt to confirm age."""
  448. self._downloader.to_screen(u'[metacafe] Confirming age')
  449. def report_download_webpage(self, video_id):
  450. """Report webpage download."""
  451. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  452. def report_extraction(self, video_id):
  453. """Report information extraction."""
  454. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  455. def _real_initialize(self):
  456. # Retrieve disclaimer
  457. request = urllib2.Request(self._DISCLAIMER)
  458. try:
  459. self.report_disclaimer()
  460. disclaimer = urllib2.urlopen(request).read()
  461. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  462. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % compat_str(err))
  463. return
  464. # Confirm age
  465. disclaimer_form = {
  466. 'filters': '0',
  467. 'submit': "Continue - I'm over 18",
  468. }
  469. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  470. try:
  471. self.report_age_confirmation()
  472. disclaimer = urllib2.urlopen(request).read()
  473. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  474. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  475. return
  476. def _real_extract(self, url):
  477. # Extract id and simplified title from URL
  478. mobj = re.match(self._VALID_URL, url)
  479. if mobj is None:
  480. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  481. return
  482. video_id = mobj.group(1)
  483. # Check if video comes from YouTube
  484. mobj2 = re.match(r'^yt-(.*)$', video_id)
  485. if mobj2 is not None:
  486. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  487. return
  488. # Retrieve video webpage to extract further information
  489. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  490. try:
  491. self.report_download_webpage(video_id)
  492. webpage = urllib2.urlopen(request).read()
  493. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  494. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  495. return
  496. # Extract URL, uploader and title from webpage
  497. self.report_extraction(video_id)
  498. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  499. if mobj is not None:
  500. mediaURL = urllib.unquote(mobj.group(1))
  501. video_extension = mediaURL[-3:]
  502. # Extract gdaKey if available
  503. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  504. if mobj is None:
  505. video_url = mediaURL
  506. else:
  507. gdaKey = mobj.group(1)
  508. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  509. else:
  510. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  511. if mobj is None:
  512. self._downloader.trouble(u'ERROR: unable to extract media URL')
  513. return
  514. vardict = parse_qs(mobj.group(1))
  515. if 'mediaData' not in vardict:
  516. self._downloader.trouble(u'ERROR: unable to extract media URL')
  517. return
  518. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  519. if mobj is None:
  520. self._downloader.trouble(u'ERROR: unable to extract media URL')
  521. return
  522. mediaURL = mobj.group(1).replace('\\/', '/')
  523. video_extension = mediaURL[-3:]
  524. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  525. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  526. if mobj is None:
  527. self._downloader.trouble(u'ERROR: unable to extract title')
  528. return
  529. video_title = mobj.group(1).decode('utf-8')
  530. mobj = re.search(r'submitter=(.*?);', webpage)
  531. if mobj is None:
  532. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  533. return
  534. video_uploader = mobj.group(1)
  535. return [{
  536. 'id': video_id.decode('utf-8'),
  537. 'url': video_url.decode('utf-8'),
  538. 'uploader': video_uploader.decode('utf-8'),
  539. 'upload_date': u'NA',
  540. 'title': video_title,
  541. 'ext': video_extension.decode('utf-8'),
  542. }]
  543. class DailymotionIE(InfoExtractor):
  544. """Information Extractor for Dailymotion"""
  545. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  546. IE_NAME = u'dailymotion'
  547. def __init__(self, downloader=None):
  548. InfoExtractor.__init__(self, downloader)
  549. def report_download_webpage(self, video_id):
  550. """Report webpage download."""
  551. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  552. def report_extraction(self, video_id):
  553. """Report information extraction."""
  554. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  555. def _real_extract(self, url):
  556. # Extract id and simplified title from URL
  557. mobj = re.match(self._VALID_URL, url)
  558. if mobj is None:
  559. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  560. return
  561. video_id = mobj.group(1).split('_')[0].split('?')[0]
  562. video_extension = 'mp4'
  563. # Retrieve video webpage to extract further information
  564. request = urllib2.Request(url)
  565. request.add_header('Cookie', 'family_filter=off')
  566. try:
  567. self.report_download_webpage(video_id)
  568. webpage = urllib2.urlopen(request).read()
  569. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  570. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  571. return
  572. # Extract URL, uploader and title from webpage
  573. self.report_extraction(video_id)
  574. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  575. if mobj is None:
  576. self._downloader.trouble(u'ERROR: unable to extract media URL')
  577. return
  578. flashvars = urllib.unquote(mobj.group(1))
  579. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  580. if key in flashvars:
  581. max_quality = key
  582. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  583. break
  584. else:
  585. self._downloader.trouble(u'ERROR: unable to extract video URL')
  586. return
  587. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  588. if mobj is None:
  589. self._downloader.trouble(u'ERROR: unable to extract video URL')
  590. return
  591. video_url = urllib.unquote(mobj.group(1)).replace('\\/', '/')
  592. # TODO: support choosing qualities
  593. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  594. if mobj is None:
  595. self._downloader.trouble(u'ERROR: unable to extract title')
  596. return
  597. video_title = unescapeHTML(mobj.group('title').decode('utf-8'))
  598. video_uploader = u'NA'
  599. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  600. if mobj is None:
  601. # lookin for official user
  602. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  603. if mobj_official is None:
  604. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  605. else:
  606. video_uploader = mobj_official.group(1)
  607. else:
  608. video_uploader = mobj.group(1)
  609. video_upload_date = u'NA'
  610. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  611. if mobj is not None:
  612. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  613. return [{
  614. 'id': video_id.decode('utf-8'),
  615. 'url': video_url.decode('utf-8'),
  616. 'uploader': video_uploader.decode('utf-8'),
  617. 'upload_date': video_upload_date,
  618. 'title': video_title,
  619. 'ext': video_extension.decode('utf-8'),
  620. }]
  621. class GoogleIE(InfoExtractor):
  622. """Information extractor for video.google.com."""
  623. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  624. IE_NAME = u'video.google'
  625. def __init__(self, downloader=None):
  626. InfoExtractor.__init__(self, downloader)
  627. def report_download_webpage(self, video_id):
  628. """Report webpage download."""
  629. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  630. def report_extraction(self, video_id):
  631. """Report information extraction."""
  632. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  633. def _real_extract(self, url):
  634. # Extract id from URL
  635. mobj = re.match(self._VALID_URL, url)
  636. if mobj is None:
  637. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  638. return
  639. video_id = mobj.group(1)
  640. video_extension = 'mp4'
  641. # Retrieve video webpage to extract further information
  642. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  643. try:
  644. self.report_download_webpage(video_id)
  645. webpage = urllib2.urlopen(request).read()
  646. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  647. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  648. return
  649. # Extract URL, uploader, and title from webpage
  650. self.report_extraction(video_id)
  651. mobj = re.search(r"download_url:'([^']+)'", webpage)
  652. if mobj is None:
  653. video_extension = 'flv'
  654. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  655. if mobj is None:
  656. self._downloader.trouble(u'ERROR: unable to extract media URL')
  657. return
  658. mediaURL = urllib.unquote(mobj.group(1))
  659. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  660. mediaURL = mediaURL.replace('\\x26', '\x26')
  661. video_url = mediaURL
  662. mobj = re.search(r'<title>(.*)</title>', webpage)
  663. if mobj is None:
  664. self._downloader.trouble(u'ERROR: unable to extract title')
  665. return
  666. video_title = mobj.group(1).decode('utf-8')
  667. # Extract video description
  668. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  669. if mobj is None:
  670. self._downloader.trouble(u'ERROR: unable to extract video description')
  671. return
  672. video_description = mobj.group(1).decode('utf-8')
  673. if not video_description:
  674. video_description = 'No description available.'
  675. # Extract video thumbnail
  676. if self._downloader.params.get('forcethumbnail', False):
  677. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  678. try:
  679. webpage = urllib2.urlopen(request).read()
  680. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  681. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  682. return
  683. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  684. if mobj is None:
  685. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  686. return
  687. video_thumbnail = mobj.group(1)
  688. else: # we need something to pass to process_info
  689. video_thumbnail = ''
  690. return [{
  691. 'id': video_id.decode('utf-8'),
  692. 'url': video_url.decode('utf-8'),
  693. 'uploader': u'NA',
  694. 'upload_date': u'NA',
  695. 'title': video_title,
  696. 'ext': video_extension.decode('utf-8'),
  697. }]
  698. class PhotobucketIE(InfoExtractor):
  699. """Information extractor for photobucket.com."""
  700. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  701. IE_NAME = u'photobucket'
  702. def __init__(self, downloader=None):
  703. InfoExtractor.__init__(self, downloader)
  704. def report_download_webpage(self, video_id):
  705. """Report webpage download."""
  706. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  707. def report_extraction(self, video_id):
  708. """Report information extraction."""
  709. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  710. def _real_extract(self, url):
  711. # Extract id from URL
  712. mobj = re.match(self._VALID_URL, url)
  713. if mobj is None:
  714. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  715. return
  716. video_id = mobj.group(1)
  717. video_extension = 'flv'
  718. # Retrieve video webpage to extract further information
  719. request = urllib2.Request(url)
  720. try:
  721. self.report_download_webpage(video_id)
  722. webpage = urllib2.urlopen(request).read()
  723. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  724. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  725. return
  726. # Extract URL, uploader, and title from webpage
  727. self.report_extraction(video_id)
  728. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  729. if mobj is None:
  730. self._downloader.trouble(u'ERROR: unable to extract media URL')
  731. return
  732. mediaURL = urllib.unquote(mobj.group(1))
  733. video_url = mediaURL
  734. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  735. if mobj is None:
  736. self._downloader.trouble(u'ERROR: unable to extract title')
  737. return
  738. video_title = mobj.group(1).decode('utf-8')
  739. video_uploader = mobj.group(2).decode('utf-8')
  740. return [{
  741. 'id': video_id.decode('utf-8'),
  742. 'url': video_url.decode('utf-8'),
  743. 'uploader': video_uploader,
  744. 'upload_date': u'NA',
  745. 'title': video_title,
  746. 'ext': video_extension.decode('utf-8'),
  747. }]
  748. class YahooIE(InfoExtractor):
  749. """Information extractor for video.yahoo.com."""
  750. # _VALID_URL matches all Yahoo! Video URLs
  751. # _VPAGE_URL matches only the extractable '/watch/' URLs
  752. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  753. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  754. IE_NAME = u'video.yahoo'
  755. def __init__(self, downloader=None):
  756. InfoExtractor.__init__(self, downloader)
  757. def report_download_webpage(self, video_id):
  758. """Report webpage download."""
  759. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  760. def report_extraction(self, video_id):
  761. """Report information extraction."""
  762. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  763. def _real_extract(self, url, new_video=True):
  764. # Extract ID from URL
  765. mobj = re.match(self._VALID_URL, url)
  766. if mobj is None:
  767. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  768. return
  769. video_id = mobj.group(2)
  770. video_extension = 'flv'
  771. # Rewrite valid but non-extractable URLs as
  772. # extractable English language /watch/ URLs
  773. if re.match(self._VPAGE_URL, url) is None:
  774. request = urllib2.Request(url)
  775. try:
  776. webpage = urllib2.urlopen(request).read()
  777. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  778. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  779. return
  780. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  781. if mobj is None:
  782. self._downloader.trouble(u'ERROR: Unable to extract id field')
  783. return
  784. yahoo_id = mobj.group(1)
  785. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  786. if mobj is None:
  787. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  788. return
  789. yahoo_vid = mobj.group(1)
  790. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  791. return self._real_extract(url, new_video=False)
  792. # Retrieve video webpage to extract further information
  793. request = urllib2.Request(url)
  794. try:
  795. self.report_download_webpage(video_id)
  796. webpage = urllib2.urlopen(request).read()
  797. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  798. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  799. return
  800. # Extract uploader and title from webpage
  801. self.report_extraction(video_id)
  802. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  803. if mobj is None:
  804. self._downloader.trouble(u'ERROR: unable to extract video title')
  805. return
  806. video_title = mobj.group(1).decode('utf-8')
  807. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  808. if mobj is None:
  809. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  810. return
  811. video_uploader = mobj.group(1).decode('utf-8')
  812. # Extract video thumbnail
  813. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  814. if mobj is None:
  815. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  816. return
  817. video_thumbnail = mobj.group(1).decode('utf-8')
  818. # Extract video description
  819. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  820. if mobj is None:
  821. self._downloader.trouble(u'ERROR: unable to extract video description')
  822. return
  823. video_description = mobj.group(1).decode('utf-8')
  824. if not video_description:
  825. video_description = 'No description available.'
  826. # Extract video height and width
  827. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  828. if mobj is None:
  829. self._downloader.trouble(u'ERROR: unable to extract video height')
  830. return
  831. yv_video_height = mobj.group(1)
  832. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  833. if mobj is None:
  834. self._downloader.trouble(u'ERROR: unable to extract video width')
  835. return
  836. yv_video_width = mobj.group(1)
  837. # Retrieve video playlist to extract media URL
  838. # I'm not completely sure what all these options are, but we
  839. # seem to need most of them, otherwise the server sends a 401.
  840. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  841. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  842. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  843. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  844. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  845. try:
  846. self.report_download_webpage(video_id)
  847. webpage = urllib2.urlopen(request).read()
  848. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  849. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  850. return
  851. # Extract media URL from playlist XML
  852. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  853. if mobj is None:
  854. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  855. return
  856. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  857. video_url = unescapeHTML(video_url)
  858. return [{
  859. 'id': video_id.decode('utf-8'),
  860. 'url': video_url,
  861. 'uploader': video_uploader,
  862. 'upload_date': u'NA',
  863. 'title': video_title,
  864. 'ext': video_extension.decode('utf-8'),
  865. 'thumbnail': video_thumbnail.decode('utf-8'),
  866. 'description': video_description,
  867. 'thumbnail': video_thumbnail,
  868. }]
  869. class VimeoIE(InfoExtractor):
  870. """Information extractor for vimeo.com."""
  871. # _VALID_URL matches Vimeo URLs
  872. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?:videos?/)?([0-9]+)'
  873. IE_NAME = u'vimeo'
  874. def __init__(self, downloader=None):
  875. InfoExtractor.__init__(self, downloader)
  876. def report_download_webpage(self, video_id):
  877. """Report webpage download."""
  878. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  879. def report_extraction(self, video_id):
  880. """Report information extraction."""
  881. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  882. def _real_extract(self, url, new_video=True):
  883. # Extract ID from URL
  884. mobj = re.match(self._VALID_URL, url)
  885. if mobj is None:
  886. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  887. return
  888. video_id = mobj.group(1)
  889. # Retrieve video webpage to extract further information
  890. request = urllib2.Request(url, None, std_headers)
  891. try:
  892. self.report_download_webpage(video_id)
  893. webpage = urllib2.urlopen(request).read()
  894. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  895. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  896. return
  897. # Now we begin extracting as much information as we can from what we
  898. # retrieved. First we extract the information common to all extractors,
  899. # and latter we extract those that are Vimeo specific.
  900. self.report_extraction(video_id)
  901. # Extract the config JSON
  902. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  903. try:
  904. config = json.loads(config)
  905. except:
  906. self._downloader.trouble(u'ERROR: unable to extract info section')
  907. return
  908. # Extract title
  909. video_title = config["video"]["title"]
  910. # Extract uploader
  911. video_uploader = config["video"]["owner"]["name"]
  912. # Extract video thumbnail
  913. video_thumbnail = config["video"]["thumbnail"]
  914. # Extract video description
  915. video_description = get_element_by_id("description", webpage.decode('utf8'))
  916. if video_description: video_description = clean_html(video_description)
  917. else: video_description = ''
  918. # Extract upload date
  919. video_upload_date = u'NA'
  920. mobj = re.search(r'<span id="clip-date" style="display:none">[^:]*: (.*?)( \([^\(]*\))?</span>', webpage)
  921. if mobj is not None:
  922. video_upload_date = mobj.group(1)
  923. # Vimeo specific: extract request signature and timestamp
  924. sig = config['request']['signature']
  925. timestamp = config['request']['timestamp']
  926. # Vimeo specific: extract video codec and quality information
  927. # First consider quality, then codecs, then take everything
  928. # TODO bind to format param
  929. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  930. files = { 'hd': [], 'sd': [], 'other': []}
  931. for codec_name, codec_extension in codecs:
  932. if codec_name in config["video"]["files"]:
  933. if 'hd' in config["video"]["files"][codec_name]:
  934. files['hd'].append((codec_name, codec_extension, 'hd'))
  935. elif 'sd' in config["video"]["files"][codec_name]:
  936. files['sd'].append((codec_name, codec_extension, 'sd'))
  937. else:
  938. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  939. for quality in ('hd', 'sd', 'other'):
  940. if len(files[quality]) > 0:
  941. video_quality = files[quality][0][2]
  942. video_codec = files[quality][0][0]
  943. video_extension = files[quality][0][1]
  944. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  945. break
  946. else:
  947. self._downloader.trouble(u'ERROR: no known codec found')
  948. return
  949. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  950. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  951. return [{
  952. 'id': video_id,
  953. 'url': video_url,
  954. 'uploader': video_uploader,
  955. 'upload_date': video_upload_date,
  956. 'title': video_title,
  957. 'ext': video_extension,
  958. 'thumbnail': video_thumbnail,
  959. 'description': video_description,
  960. }]
  961. class GenericIE(InfoExtractor):
  962. """Generic last-resort information extractor."""
  963. _VALID_URL = r'.*'
  964. IE_NAME = u'generic'
  965. def __init__(self, downloader=None):
  966. InfoExtractor.__init__(self, downloader)
  967. def report_download_webpage(self, video_id):
  968. """Report webpage download."""
  969. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  970. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  971. def report_extraction(self, video_id):
  972. """Report information extraction."""
  973. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  974. def report_following_redirect(self, new_url):
  975. """Report information extraction."""
  976. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  977. def _test_redirect(self, url):
  978. """Check if it is a redirect, like url shorteners, in case restart chain."""
  979. class HeadRequest(urllib2.Request):
  980. def get_method(self):
  981. return "HEAD"
  982. class HEADRedirectHandler(urllib2.HTTPRedirectHandler):
  983. """
  984. Subclass the HTTPRedirectHandler to make it use our
  985. HeadRequest also on the redirected URL
  986. """
  987. def redirect_request(self, req, fp, code, msg, headers, newurl):
  988. if code in (301, 302, 303, 307):
  989. newurl = newurl.replace(' ', '%20')
  990. newheaders = dict((k,v) for k,v in req.headers.items()
  991. if k.lower() not in ("content-length", "content-type"))
  992. return HeadRequest(newurl,
  993. headers=newheaders,
  994. origin_req_host=req.get_origin_req_host(),
  995. unverifiable=True)
  996. else:
  997. raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
  998. class HTTPMethodFallback(urllib2.BaseHandler):
  999. """
  1000. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1001. """
  1002. def http_error_405(self, req, fp, code, msg, headers):
  1003. fp.read()
  1004. fp.close()
  1005. newheaders = dict((k,v) for k,v in req.headers.items()
  1006. if k.lower() not in ("content-length", "content-type"))
  1007. return self.parent.open(urllib2.Request(req.get_full_url(),
  1008. headers=newheaders,
  1009. origin_req_host=req.get_origin_req_host(),
  1010. unverifiable=True))
  1011. # Build our opener
  1012. opener = urllib2.OpenerDirector()
  1013. for handler in [urllib2.HTTPHandler, urllib2.HTTPDefaultErrorHandler,
  1014. HTTPMethodFallback, HEADRedirectHandler,
  1015. urllib2.HTTPErrorProcessor, urllib2.HTTPSHandler]:
  1016. opener.add_handler(handler())
  1017. response = opener.open(HeadRequest(url))
  1018. new_url = response.geturl()
  1019. if url == new_url: return False
  1020. self.report_following_redirect(new_url)
  1021. self._downloader.download([new_url])
  1022. return True
  1023. def _real_extract(self, url):
  1024. if self._test_redirect(url): return
  1025. video_id = url.split('/')[-1]
  1026. request = urllib2.Request(url)
  1027. try:
  1028. self.report_download_webpage(video_id)
  1029. webpage = urllib2.urlopen(request).read()
  1030. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1031. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1032. return
  1033. except ValueError, err:
  1034. # since this is the last-resort InfoExtractor, if
  1035. # this error is thrown, it'll be thrown here
  1036. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1037. return
  1038. self.report_extraction(video_id)
  1039. # Start with something easy: JW Player in SWFObject
  1040. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1041. if mobj is None:
  1042. # Broaden the search a little bit
  1043. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1044. if mobj is None:
  1045. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1046. return
  1047. # It's possible that one of the regexes
  1048. # matched, but returned an empty group:
  1049. if mobj.group(1) is None:
  1050. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1051. return
  1052. video_url = urllib.unquote(mobj.group(1))
  1053. video_id = os.path.basename(video_url)
  1054. # here's a fun little line of code for you:
  1055. video_extension = os.path.splitext(video_id)[1][1:]
  1056. video_id = os.path.splitext(video_id)[0]
  1057. # it's tempting to parse this further, but you would
  1058. # have to take into account all the variations like
  1059. # Video Title - Site Name
  1060. # Site Name | Video Title
  1061. # Video Title - Tagline | Site Name
  1062. # and so on and so forth; it's just not practical
  1063. mobj = re.search(r'<title>(.*)</title>', webpage)
  1064. if mobj is None:
  1065. self._downloader.trouble(u'ERROR: unable to extract title')
  1066. return
  1067. video_title = mobj.group(1).decode('utf-8')
  1068. # video uploader is domain name
  1069. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1070. if mobj is None:
  1071. self._downloader.trouble(u'ERROR: unable to extract title')
  1072. return
  1073. video_uploader = mobj.group(1).decode('utf-8')
  1074. return [{
  1075. 'id': video_id.decode('utf-8'),
  1076. 'url': video_url.decode('utf-8'),
  1077. 'uploader': video_uploader,
  1078. 'upload_date': u'NA',
  1079. 'title': video_title,
  1080. 'ext': video_extension.decode('utf-8'),
  1081. }]
  1082. class YoutubeSearchIE(InfoExtractor):
  1083. """Information Extractor for YouTube search queries."""
  1084. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1085. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1086. _max_youtube_results = 1000
  1087. IE_NAME = u'youtube:search'
  1088. def __init__(self, downloader=None):
  1089. InfoExtractor.__init__(self, downloader)
  1090. def report_download_page(self, query, pagenum):
  1091. """Report attempt to download search page with given number."""
  1092. query = query.decode(preferredencoding())
  1093. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1094. def _real_extract(self, query):
  1095. mobj = re.match(self._VALID_URL, query)
  1096. if mobj is None:
  1097. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1098. return
  1099. prefix, query = query.split(':')
  1100. prefix = prefix[8:]
  1101. query = query.encode('utf-8')
  1102. if prefix == '':
  1103. self._download_n_results(query, 1)
  1104. return
  1105. elif prefix == 'all':
  1106. self._download_n_results(query, self._max_youtube_results)
  1107. return
  1108. else:
  1109. try:
  1110. n = long(prefix)
  1111. if n <= 0:
  1112. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1113. return
  1114. elif n > self._max_youtube_results:
  1115. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1116. n = self._max_youtube_results
  1117. self._download_n_results(query, n)
  1118. return
  1119. except ValueError: # parsing prefix as integer fails
  1120. self._download_n_results(query, 1)
  1121. return
  1122. def _download_n_results(self, query, n):
  1123. """Downloads a specified number of results for a query"""
  1124. video_ids = []
  1125. pagenum = 0
  1126. limit = n
  1127. while (50 * pagenum) < limit:
  1128. self.report_download_page(query, pagenum+1)
  1129. result_url = self._API_URL % (urllib.quote_plus(query), (50*pagenum)+1)
  1130. request = urllib2.Request(result_url)
  1131. try:
  1132. data = urllib2.urlopen(request).read()
  1133. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1134. self._downloader.trouble(u'ERROR: unable to download API page: %s' % compat_str(err))
  1135. return
  1136. api_response = json.loads(data)['data']
  1137. new_ids = list(video['id'] for video in api_response['items'])
  1138. video_ids += new_ids
  1139. limit = min(n, api_response['totalItems'])
  1140. pagenum += 1
  1141. if len(video_ids) > n:
  1142. video_ids = video_ids[:n]
  1143. for id in video_ids:
  1144. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1145. return
  1146. class GoogleSearchIE(InfoExtractor):
  1147. """Information Extractor for Google Video search queries."""
  1148. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1149. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1150. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1151. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1152. _max_google_results = 1000
  1153. IE_NAME = u'video.google:search'
  1154. def __init__(self, downloader=None):
  1155. InfoExtractor.__init__(self, downloader)
  1156. def report_download_page(self, query, pagenum):
  1157. """Report attempt to download playlist page with given number."""
  1158. query = query.decode(preferredencoding())
  1159. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1160. def _real_extract(self, query):
  1161. mobj = re.match(self._VALID_URL, query)
  1162. if mobj is None:
  1163. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1164. return
  1165. prefix, query = query.split(':')
  1166. prefix = prefix[8:]
  1167. query = query.encode('utf-8')
  1168. if prefix == '':
  1169. self._download_n_results(query, 1)
  1170. return
  1171. elif prefix == 'all':
  1172. self._download_n_results(query, self._max_google_results)
  1173. return
  1174. else:
  1175. try:
  1176. n = long(prefix)
  1177. if n <= 0:
  1178. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1179. return
  1180. elif n > self._max_google_results:
  1181. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1182. n = self._max_google_results
  1183. self._download_n_results(query, n)
  1184. return
  1185. except ValueError: # parsing prefix as integer fails
  1186. self._download_n_results(query, 1)
  1187. return
  1188. def _download_n_results(self, query, n):
  1189. """Downloads a specified number of results for a query"""
  1190. video_ids = []
  1191. pagenum = 0
  1192. while True:
  1193. self.report_download_page(query, pagenum)
  1194. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum*10)
  1195. request = urllib2.Request(result_url)
  1196. try:
  1197. page = urllib2.urlopen(request).read()
  1198. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1199. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1200. return
  1201. # Extract video identifiers
  1202. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1203. video_id = mobj.group(1)
  1204. if video_id not in video_ids:
  1205. video_ids.append(video_id)
  1206. if len(video_ids) == n:
  1207. # Specified n videos reached
  1208. for id in video_ids:
  1209. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1210. return
  1211. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1212. for id in video_ids:
  1213. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1214. return
  1215. pagenum = pagenum + 1
  1216. class YahooSearchIE(InfoExtractor):
  1217. """Information Extractor for Yahoo! Video search queries."""
  1218. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1219. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1220. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1221. _MORE_PAGES_INDICATOR = r'\s*Next'
  1222. _max_yahoo_results = 1000
  1223. IE_NAME = u'video.yahoo:search'
  1224. def __init__(self, downloader=None):
  1225. InfoExtractor.__init__(self, downloader)
  1226. def report_download_page(self, query, pagenum):
  1227. """Report attempt to download playlist page with given number."""
  1228. query = query.decode(preferredencoding())
  1229. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1230. def _real_extract(self, query):
  1231. mobj = re.match(self._VALID_URL, query)
  1232. if mobj is None:
  1233. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1234. return
  1235. prefix, query = query.split(':')
  1236. prefix = prefix[8:]
  1237. query = query.encode('utf-8')
  1238. if prefix == '':
  1239. self._download_n_results(query, 1)
  1240. return
  1241. elif prefix == 'all':
  1242. self._download_n_results(query, self._max_yahoo_results)
  1243. return
  1244. else:
  1245. try:
  1246. n = long(prefix)
  1247. if n <= 0:
  1248. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1249. return
  1250. elif n > self._max_yahoo_results:
  1251. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1252. n = self._max_yahoo_results
  1253. self._download_n_results(query, n)
  1254. return
  1255. except ValueError: # parsing prefix as integer fails
  1256. self._download_n_results(query, 1)
  1257. return
  1258. def _download_n_results(self, query, n):
  1259. """Downloads a specified number of results for a query"""
  1260. video_ids = []
  1261. already_seen = set()
  1262. pagenum = 1
  1263. while True:
  1264. self.report_download_page(query, pagenum)
  1265. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1266. request = urllib2.Request(result_url)
  1267. try:
  1268. page = urllib2.urlopen(request).read()
  1269. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1270. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1271. return
  1272. # Extract video identifiers
  1273. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1274. video_id = mobj.group(1)
  1275. if video_id not in already_seen:
  1276. video_ids.append(video_id)
  1277. already_seen.add(video_id)
  1278. if len(video_ids) == n:
  1279. # Specified n videos reached
  1280. for id in video_ids:
  1281. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1282. return
  1283. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1284. for id in video_ids:
  1285. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1286. return
  1287. pagenum = pagenum + 1
  1288. class YoutubePlaylistIE(InfoExtractor):
  1289. """Information Extractor for YouTube playlists."""
  1290. _VALID_URL = r'(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:(?:course|view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)(?:PL|EC)?|PL|EC)([0-9A-Za-z-_]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1291. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1292. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;([^&"]+&amp;)*list=.*?%s'
  1293. _MORE_PAGES_INDICATOR = r'yt-uix-pager-next'
  1294. IE_NAME = u'youtube:playlist'
  1295. def __init__(self, downloader=None):
  1296. InfoExtractor.__init__(self, downloader)
  1297. def report_download_page(self, playlist_id, pagenum):
  1298. """Report attempt to download playlist page with given number."""
  1299. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1300. def _real_extract(self, url):
  1301. # Extract playlist id
  1302. mobj = re.match(self._VALID_URL, url)
  1303. if mobj is None:
  1304. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1305. return
  1306. # Single video case
  1307. if mobj.group(3) is not None:
  1308. self._downloader.download([mobj.group(3)])
  1309. return
  1310. # Download playlist pages
  1311. # prefix is 'p' as default for playlists but there are other types that need extra care
  1312. playlist_prefix = mobj.group(1)
  1313. if playlist_prefix == 'a':
  1314. playlist_access = 'artist'
  1315. else:
  1316. playlist_prefix = 'p'
  1317. playlist_access = 'view_play_list'
  1318. playlist_id = mobj.group(2)
  1319. video_ids = []
  1320. pagenum = 1
  1321. while True:
  1322. self.report_download_page(playlist_id, pagenum)
  1323. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  1324. request = urllib2.Request(url)
  1325. try:
  1326. page = urllib2.urlopen(request).read()
  1327. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1328. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1329. return
  1330. # Extract video identifiers
  1331. ids_in_page = []
  1332. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  1333. if mobj.group(1) not in ids_in_page:
  1334. ids_in_page.append(mobj.group(1))
  1335. video_ids.extend(ids_in_page)
  1336. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1337. break
  1338. pagenum = pagenum + 1
  1339. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1340. playlistend = self._downloader.params.get('playlistend', -1)
  1341. if playlistend == -1:
  1342. video_ids = video_ids[playliststart:]
  1343. else:
  1344. video_ids = video_ids[playliststart:playlistend]
  1345. for id in video_ids:
  1346. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1347. return
  1348. class YoutubeChannelIE(InfoExtractor):
  1349. """Information Extractor for YouTube channels."""
  1350. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1351. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1352. _MORE_PAGES_INDICATOR = r'yt-uix-button-content">Next' # TODO
  1353. IE_NAME = u'youtube:channel'
  1354. def report_download_page(self, channel_id, pagenum):
  1355. """Report attempt to download channel page with given number."""
  1356. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1357. def _real_extract(self, url):
  1358. # Extract channel id
  1359. mobj = re.match(self._VALID_URL, url)
  1360. if mobj is None:
  1361. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1362. return
  1363. # Download channel pages
  1364. channel_id = mobj.group(1)
  1365. video_ids = []
  1366. pagenum = 1
  1367. while True:
  1368. self.report_download_page(channel_id, pagenum)
  1369. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1370. request = urllib2.Request(url)
  1371. try:
  1372. page = urllib2.urlopen(request).read()
  1373. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1374. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1375. return
  1376. # Extract video identifiers
  1377. ids_in_page = []
  1378. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1379. if mobj.group(1) not in ids_in_page:
  1380. ids_in_page.append(mobj.group(1))
  1381. video_ids.extend(ids_in_page)
  1382. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1383. break
  1384. pagenum = pagenum + 1
  1385. for id in video_ids:
  1386. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1387. return
  1388. class YoutubeUserIE(InfoExtractor):
  1389. """Information Extractor for YouTube users."""
  1390. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1391. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1392. _GDATA_PAGE_SIZE = 50
  1393. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1394. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1395. IE_NAME = u'youtube:user'
  1396. def __init__(self, downloader=None):
  1397. InfoExtractor.__init__(self, downloader)
  1398. def report_download_page(self, username, start_index):
  1399. """Report attempt to download user page."""
  1400. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1401. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1402. def _real_extract(self, url):
  1403. # Extract username
  1404. mobj = re.match(self._VALID_URL, url)
  1405. if mobj is None:
  1406. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1407. return
  1408. username = mobj.group(1)
  1409. # Download video ids using YouTube Data API. Result size per
  1410. # query is limited (currently to 50 videos) so we need to query
  1411. # page by page until there are no video ids - it means we got
  1412. # all of them.
  1413. video_ids = []
  1414. pagenum = 0
  1415. while True:
  1416. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1417. self.report_download_page(username, start_index)
  1418. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1419. try:
  1420. page = urllib2.urlopen(request).read()
  1421. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1422. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1423. return
  1424. # Extract video identifiers
  1425. ids_in_page = []
  1426. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1427. if mobj.group(1) not in ids_in_page:
  1428. ids_in_page.append(mobj.group(1))
  1429. video_ids.extend(ids_in_page)
  1430. # A little optimization - if current page is not
  1431. # "full", ie. does not contain PAGE_SIZE video ids then
  1432. # we can assume that this page is the last one - there
  1433. # are no more ids on further pages - no need to query
  1434. # again.
  1435. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1436. break
  1437. pagenum += 1
  1438. all_ids_count = len(video_ids)
  1439. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1440. playlistend = self._downloader.params.get('playlistend', -1)
  1441. if playlistend == -1:
  1442. video_ids = video_ids[playliststart:]
  1443. else:
  1444. video_ids = video_ids[playliststart:playlistend]
  1445. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1446. (username, all_ids_count, len(video_ids)))
  1447. for video_id in video_ids:
  1448. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1449. class BlipTVUserIE(InfoExtractor):
  1450. """Information Extractor for blip.tv users."""
  1451. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1452. _PAGE_SIZE = 12
  1453. IE_NAME = u'blip.tv:user'
  1454. def __init__(self, downloader=None):
  1455. InfoExtractor.__init__(self, downloader)
  1456. def report_download_page(self, username, pagenum):
  1457. """Report attempt to download user page."""
  1458. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1459. (self.IE_NAME, username, pagenum))
  1460. def _real_extract(self, url):
  1461. # Extract username
  1462. mobj = re.match(self._VALID_URL, url)
  1463. if mobj is None:
  1464. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1465. return
  1466. username = mobj.group(1)
  1467. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1468. request = urllib2.Request(url)
  1469. try:
  1470. page = urllib2.urlopen(request).read().decode('utf-8')
  1471. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1472. page_base = page_base % mobj.group(1)
  1473. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1474. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1475. return
  1476. # Download video ids using BlipTV Ajax calls. Result size per
  1477. # query is limited (currently to 12 videos) so we need to query
  1478. # page by page until there are no video ids - it means we got
  1479. # all of them.
  1480. video_ids = []
  1481. pagenum = 1
  1482. while True:
  1483. self.report_download_page(username, pagenum)
  1484. request = urllib2.Request( page_base + "&page=" + str(pagenum) )
  1485. try:
  1486. page = urllib2.urlopen(request).read().decode('utf-8')
  1487. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1488. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1489. return
  1490. # Extract video identifiers
  1491. ids_in_page = []
  1492. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1493. if mobj.group(1) not in ids_in_page:
  1494. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1495. video_ids.extend(ids_in_page)
  1496. # A little optimization - if current page is not
  1497. # "full", ie. does not contain PAGE_SIZE video ids then
  1498. # we can assume that this page is the last one - there
  1499. # are no more ids on further pages - no need to query
  1500. # again.
  1501. if len(ids_in_page) < self._PAGE_SIZE:
  1502. break
  1503. pagenum += 1
  1504. all_ids_count = len(video_ids)
  1505. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1506. playlistend = self._downloader.params.get('playlistend', -1)
  1507. if playlistend == -1:
  1508. video_ids = video_ids[playliststart:]
  1509. else:
  1510. video_ids = video_ids[playliststart:playlistend]
  1511. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1512. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1513. for video_id in video_ids:
  1514. self._downloader.download([u'http://blip.tv/'+video_id])
  1515. class DepositFilesIE(InfoExtractor):
  1516. """Information extractor for depositfiles.com"""
  1517. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1518. IE_NAME = u'DepositFiles'
  1519. def __init__(self, downloader=None):
  1520. InfoExtractor.__init__(self, downloader)
  1521. def report_download_webpage(self, file_id):
  1522. """Report webpage download."""
  1523. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1524. def report_extraction(self, file_id):
  1525. """Report information extraction."""
  1526. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1527. def _real_extract(self, url):
  1528. file_id = url.split('/')[-1]
  1529. # Rebuild url in english locale
  1530. url = 'http://depositfiles.com/en/files/' + file_id
  1531. # Retrieve file webpage with 'Free download' button pressed
  1532. free_download_indication = { 'gateway_result' : '1' }
  1533. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  1534. try:
  1535. self.report_download_webpage(file_id)
  1536. webpage = urllib2.urlopen(request).read()
  1537. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1538. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1539. return
  1540. # Search for the real file URL
  1541. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1542. if (mobj is None) or (mobj.group(1) is None):
  1543. # Try to figure out reason of the error.
  1544. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1545. if (mobj is not None) and (mobj.group(1) is not None):
  1546. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1547. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1548. else:
  1549. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1550. return
  1551. file_url = mobj.group(1)
  1552. file_extension = os.path.splitext(file_url)[1][1:]
  1553. # Search for file title
  1554. mobj = re.search(r'<b title="(.*?)">', webpage)
  1555. if mobj is None:
  1556. self._downloader.trouble(u'ERROR: unable to extract title')
  1557. return
  1558. file_title = mobj.group(1).decode('utf-8')
  1559. return [{
  1560. 'id': file_id.decode('utf-8'),
  1561. 'url': file_url.decode('utf-8'),
  1562. 'uploader': u'NA',
  1563. 'upload_date': u'NA',
  1564. 'title': file_title,
  1565. 'ext': file_extension.decode('utf-8'),
  1566. }]
  1567. class FacebookIE(InfoExtractor):
  1568. """Information Extractor for Facebook"""
  1569. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1570. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1571. _NETRC_MACHINE = 'facebook'
  1572. _available_formats = ['video', 'highqual', 'lowqual']
  1573. _video_extensions = {
  1574. 'video': 'mp4',
  1575. 'highqual': 'mp4',
  1576. 'lowqual': 'mp4',
  1577. }
  1578. IE_NAME = u'facebook'
  1579. def __init__(self, downloader=None):
  1580. InfoExtractor.__init__(self, downloader)
  1581. def _reporter(self, message):
  1582. """Add header and report message."""
  1583. self._downloader.to_screen(u'[facebook] %s' % message)
  1584. def report_login(self):
  1585. """Report attempt to log in."""
  1586. self._reporter(u'Logging in')
  1587. def report_video_webpage_download(self, video_id):
  1588. """Report attempt to download video webpage."""
  1589. self._reporter(u'%s: Downloading video webpage' % video_id)
  1590. def report_information_extraction(self, video_id):
  1591. """Report attempt to extract video information."""
  1592. self._reporter(u'%s: Extracting video information' % video_id)
  1593. def _parse_page(self, video_webpage):
  1594. """Extract video information from page"""
  1595. # General data
  1596. data = {'title': r'\("video_title", "(.*?)"\)',
  1597. 'description': r'<div class="datawrap">(.*?)</div>',
  1598. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1599. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1600. }
  1601. video_info = {}
  1602. for piece in data.keys():
  1603. mobj = re.search(data[piece], video_webpage)
  1604. if mobj is not None:
  1605. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1606. # Video urls
  1607. video_urls = {}
  1608. for fmt in self._available_formats:
  1609. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1610. if mobj is not None:
  1611. # URL is in a Javascript segment inside an escaped Unicode format within
  1612. # the generally utf-8 page
  1613. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1614. video_info['video_urls'] = video_urls
  1615. return video_info
  1616. def _real_initialize(self):
  1617. if self._downloader is None:
  1618. return
  1619. useremail = None
  1620. password = None
  1621. downloader_params = self._downloader.params
  1622. # Attempt to use provided username and password or .netrc data
  1623. if downloader_params.get('username', None) is not None:
  1624. useremail = downloader_params['username']
  1625. password = downloader_params['password']
  1626. elif downloader_params.get('usenetrc', False):
  1627. try:
  1628. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1629. if info is not None:
  1630. useremail = info[0]
  1631. password = info[2]
  1632. else:
  1633. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1634. except (IOError, netrc.NetrcParseError), err:
  1635. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  1636. return
  1637. if useremail is None:
  1638. return
  1639. # Log in
  1640. login_form = {
  1641. 'email': useremail,
  1642. 'pass': password,
  1643. 'login': 'Log+In'
  1644. }
  1645. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  1646. try:
  1647. self.report_login()
  1648. login_results = urllib2.urlopen(request).read()
  1649. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1650. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1651. return
  1652. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1653. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  1654. return
  1655. def _real_extract(self, url):
  1656. mobj = re.match(self._VALID_URL, url)
  1657. if mobj is None:
  1658. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1659. return
  1660. video_id = mobj.group('ID')
  1661. # Get video webpage
  1662. self.report_video_webpage_download(video_id)
  1663. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1664. try:
  1665. page = urllib2.urlopen(request)
  1666. video_webpage = page.read()
  1667. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1668. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  1669. return
  1670. # Start extracting information
  1671. self.report_information_extraction(video_id)
  1672. # Extract information
  1673. video_info = self._parse_page(video_webpage)
  1674. # uploader
  1675. if 'owner' not in video_info:
  1676. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1677. return
  1678. video_uploader = video_info['owner']
  1679. # title
  1680. if 'title' not in video_info:
  1681. self._downloader.trouble(u'ERROR: unable to extract video title')
  1682. return
  1683. video_title = video_info['title']
  1684. video_title = video_title.decode('utf-8')
  1685. # thumbnail image
  1686. if 'thumbnail' not in video_info:
  1687. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1688. video_thumbnail = ''
  1689. else:
  1690. video_thumbnail = video_info['thumbnail']
  1691. # upload date
  1692. upload_date = u'NA'
  1693. if 'upload_date' in video_info:
  1694. upload_time = video_info['upload_date']
  1695. timetuple = email.utils.parsedate_tz(upload_time)
  1696. if timetuple is not None:
  1697. try:
  1698. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1699. except:
  1700. pass
  1701. # description
  1702. video_description = video_info.get('description', 'No description available.')
  1703. url_map = video_info['video_urls']
  1704. if len(url_map.keys()) > 0:
  1705. # Decide which formats to download
  1706. req_format = self._downloader.params.get('format', None)
  1707. format_limit = self._downloader.params.get('format_limit', None)
  1708. if format_limit is not None and format_limit in self._available_formats:
  1709. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1710. else:
  1711. format_list = self._available_formats
  1712. existing_formats = [x for x in format_list if x in url_map]
  1713. if len(existing_formats) == 0:
  1714. self._downloader.trouble(u'ERROR: no known formats available for video')
  1715. return
  1716. if req_format is None:
  1717. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1718. elif req_format == 'worst':
  1719. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1720. elif req_format == '-1':
  1721. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1722. else:
  1723. # Specific format
  1724. if req_format not in url_map:
  1725. self._downloader.trouble(u'ERROR: requested format not available')
  1726. return
  1727. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1728. results = []
  1729. for format_param, video_real_url in video_url_list:
  1730. # Extension
  1731. video_extension = self._video_extensions.get(format_param, 'mp4')
  1732. results.append({
  1733. 'id': video_id.decode('utf-8'),
  1734. 'url': video_real_url.decode('utf-8'),
  1735. 'uploader': video_uploader.decode('utf-8'),
  1736. 'upload_date': upload_date,
  1737. 'title': video_title,
  1738. 'ext': video_extension.decode('utf-8'),
  1739. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1740. 'thumbnail': video_thumbnail.decode('utf-8'),
  1741. 'description': video_description.decode('utf-8'),
  1742. })
  1743. return results
  1744. class BlipTVIE(InfoExtractor):
  1745. """Information extractor for blip.tv"""
  1746. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1747. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1748. IE_NAME = u'blip.tv'
  1749. def report_extraction(self, file_id):
  1750. """Report information extraction."""
  1751. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1752. def report_direct_download(self, title):
  1753. """Report information extraction."""
  1754. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1755. def _real_extract(self, url):
  1756. mobj = re.match(self._VALID_URL, url)
  1757. if mobj is None:
  1758. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1759. return
  1760. if '?' in url:
  1761. cchar = '&'
  1762. else:
  1763. cchar = '?'
  1764. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1765. request = urllib2.Request(json_url.encode('utf-8'))
  1766. self.report_extraction(mobj.group(1))
  1767. info = None
  1768. try:
  1769. urlh = urllib2.urlopen(request)
  1770. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1771. basename = url.split('/')[-1]
  1772. title,ext = os.path.splitext(basename)
  1773. title = title.decode('UTF-8')
  1774. ext = ext.replace('.', '')
  1775. self.report_direct_download(title)
  1776. info = {
  1777. 'id': title,
  1778. 'url': url,
  1779. 'title': title,
  1780. 'ext': ext,
  1781. 'urlhandle': urlh
  1782. }
  1783. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1784. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1785. return
  1786. if info is None: # Regular URL
  1787. try:
  1788. json_code = urlh.read()
  1789. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1790. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1791. return
  1792. try:
  1793. json_data = json.loads(json_code)
  1794. if 'Post' in json_data:
  1795. data = json_data['Post']
  1796. else:
  1797. data = json_data
  1798. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1799. video_url = data['media']['url']
  1800. umobj = re.match(self._URL_EXT, video_url)
  1801. if umobj is None:
  1802. raise ValueError('Can not determine filename extension')
  1803. ext = umobj.group(1)
  1804. info = {
  1805. 'id': data['item_id'],
  1806. 'url': video_url,
  1807. 'uploader': data['display_name'],
  1808. 'upload_date': upload_date,
  1809. 'title': data['title'],
  1810. 'ext': ext,
  1811. 'format': data['media']['mimeType'],
  1812. 'thumbnail': data['thumbnailUrl'],
  1813. 'description': data['description'],
  1814. 'player_url': data['embedUrl']
  1815. }
  1816. except (ValueError,KeyError), err:
  1817. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1818. return
  1819. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1820. return [info]
  1821. class MyVideoIE(InfoExtractor):
  1822. """Information Extractor for myvideo.de."""
  1823. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1824. IE_NAME = u'myvideo'
  1825. def __init__(self, downloader=None):
  1826. InfoExtractor.__init__(self, downloader)
  1827. def report_download_webpage(self, video_id):
  1828. """Report webpage download."""
  1829. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1830. def report_extraction(self, video_id):
  1831. """Report information extraction."""
  1832. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1833. def _real_extract(self,url):
  1834. mobj = re.match(self._VALID_URL, url)
  1835. if mobj is None:
  1836. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1837. return
  1838. video_id = mobj.group(1)
  1839. # Get video webpage
  1840. request = urllib2.Request('http://www.myvideo.de/watch/%s' % video_id)
  1841. try:
  1842. self.report_download_webpage(video_id)
  1843. webpage = urllib2.urlopen(request).read()
  1844. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1845. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1846. return
  1847. self.report_extraction(video_id)
  1848. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1849. webpage)
  1850. if mobj is None:
  1851. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1852. return
  1853. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1854. mobj = re.search('<title>([^<]+)</title>', webpage)
  1855. if mobj is None:
  1856. self._downloader.trouble(u'ERROR: unable to extract title')
  1857. return
  1858. video_title = mobj.group(1)
  1859. return [{
  1860. 'id': video_id,
  1861. 'url': video_url,
  1862. 'uploader': u'NA',
  1863. 'upload_date': u'NA',
  1864. 'title': video_title,
  1865. 'ext': u'flv',
  1866. }]
  1867. class ComedyCentralIE(InfoExtractor):
  1868. """Information extractor for The Daily Show and Colbert Report """
  1869. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  1870. IE_NAME = u'comedycentral'
  1871. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1872. _video_extensions = {
  1873. '3500': 'mp4',
  1874. '2200': 'mp4',
  1875. '1700': 'mp4',
  1876. '1200': 'mp4',
  1877. '750': 'mp4',
  1878. '400': 'mp4',
  1879. }
  1880. _video_dimensions = {
  1881. '3500': '1280x720',
  1882. '2200': '960x540',
  1883. '1700': '768x432',
  1884. '1200': '640x360',
  1885. '750': '512x288',
  1886. '400': '384x216',
  1887. }
  1888. def report_extraction(self, episode_id):
  1889. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1890. def report_config_download(self, episode_id):
  1891. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  1892. def report_index_download(self, episode_id):
  1893. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1894. def report_player_url(self, episode_id):
  1895. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  1896. def _print_formats(self, formats):
  1897. print('Available formats:')
  1898. for x in formats:
  1899. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1900. def _real_extract(self, url):
  1901. mobj = re.match(self._VALID_URL, url)
  1902. if mobj is None:
  1903. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1904. return
  1905. if mobj.group('shortname'):
  1906. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1907. url = u'http://www.thedailyshow.com/full-episodes/'
  1908. else:
  1909. url = u'http://www.colbertnation.com/full-episodes/'
  1910. mobj = re.match(self._VALID_URL, url)
  1911. assert mobj is not None
  1912. dlNewest = not mobj.group('episode')
  1913. if dlNewest:
  1914. epTitle = mobj.group('showname')
  1915. else:
  1916. epTitle = mobj.group('episode')
  1917. req = urllib2.Request(url)
  1918. self.report_extraction(epTitle)
  1919. try:
  1920. htmlHandle = urllib2.urlopen(req)
  1921. html = htmlHandle.read()
  1922. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1923. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  1924. return
  1925. if dlNewest:
  1926. url = htmlHandle.geturl()
  1927. mobj = re.match(self._VALID_URL, url)
  1928. if mobj is None:
  1929. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  1930. return
  1931. if mobj.group('episode') == '':
  1932. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  1933. return
  1934. epTitle = mobj.group('episode')
  1935. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"', html)
  1936. if len(mMovieParams) == 0:
  1937. # The Colbert Report embeds the information in a without
  1938. # a URL prefix; so extract the alternate reference
  1939. # and then add the URL prefix manually.
  1940. altMovieParams = re.findall('data-mgid="([^"]*episode.*?:.*?)"', html)
  1941. if len(altMovieParams) == 0:
  1942. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  1943. return
  1944. else:
  1945. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  1946. playerUrl_raw = mMovieParams[0][0]
  1947. self.report_player_url(epTitle)
  1948. try:
  1949. urlHandle = urllib2.urlopen(playerUrl_raw)
  1950. playerUrl = urlHandle.geturl()
  1951. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1952. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + unicode(err))
  1953. return
  1954. uri = mMovieParams[0][1]
  1955. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + urllib.urlencode({'uri': uri})
  1956. self.report_index_download(epTitle)
  1957. try:
  1958. indexXml = urllib2.urlopen(indexUrl).read()
  1959. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1960. self._downloader.trouble(u'ERROR: unable to download episode index: ' + unicode(err))
  1961. return
  1962. results = []
  1963. idoc = xml.etree.ElementTree.fromstring(indexXml)
  1964. itemEls = idoc.findall('.//item')
  1965. for itemEl in itemEls:
  1966. mediaId = itemEl.findall('./guid')[0].text
  1967. shortMediaId = mediaId.split(':')[-1]
  1968. showId = mediaId.split(':')[-2].replace('.com', '')
  1969. officialTitle = itemEl.findall('./title')[0].text
  1970. officialDate = itemEl.findall('./pubDate')[0].text
  1971. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  1972. urllib.urlencode({'uri': mediaId}))
  1973. configReq = urllib2.Request(configUrl)
  1974. self.report_config_download(epTitle)
  1975. try:
  1976. configXml = urllib2.urlopen(configReq).read()
  1977. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1978. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  1979. return
  1980. cdoc = xml.etree.ElementTree.fromstring(configXml)
  1981. turls = []
  1982. for rendition in cdoc.findall('.//rendition'):
  1983. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  1984. turls.append(finfo)
  1985. if len(turls) == 0:
  1986. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  1987. continue
  1988. if self._downloader.params.get('listformats', None):
  1989. self._print_formats([i[0] for i in turls])
  1990. return
  1991. # For now, just pick the highest bitrate
  1992. format,video_url = turls[-1]
  1993. # Get the format arg from the arg stream
  1994. req_format = self._downloader.params.get('format', None)
  1995. # Select format if we can find one
  1996. for f,v in turls:
  1997. if f == req_format:
  1998. format, video_url = f, v
  1999. break
  2000. # Patch to download from alternative CDN, which does not
  2001. # break on current RTMPDump builds
  2002. broken_cdn = "rtmpe://viacomccstrmfs.fplive.net/viacomccstrm/gsp.comedystor/"
  2003. better_cdn = "rtmpe://cp10740.edgefcs.net/ondemand/mtvnorigin/gsp.comedystor/"
  2004. if video_url.startswith(broken_cdn):
  2005. video_url = video_url.replace(broken_cdn, better_cdn)
  2006. effTitle = showId + u'-' + epTitle
  2007. info = {
  2008. 'id': shortMediaId,
  2009. 'url': video_url,
  2010. 'uploader': showId,
  2011. 'upload_date': officialDate,
  2012. 'title': effTitle,
  2013. 'ext': 'mp4',
  2014. 'format': format,
  2015. 'thumbnail': None,
  2016. 'description': officialTitle,
  2017. 'player_url': None #playerUrl
  2018. }
  2019. results.append(info)
  2020. return results
  2021. class EscapistIE(InfoExtractor):
  2022. """Information extractor for The Escapist """
  2023. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2024. IE_NAME = u'escapist'
  2025. def report_extraction(self, showName):
  2026. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2027. def report_config_download(self, showName):
  2028. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2029. def _real_extract(self, url):
  2030. mobj = re.match(self._VALID_URL, url)
  2031. if mobj is None:
  2032. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2033. return
  2034. showName = mobj.group('showname')
  2035. videoId = mobj.group('episode')
  2036. self.report_extraction(showName)
  2037. try:
  2038. webPage = urllib2.urlopen(url)
  2039. webPageBytes = webPage.read()
  2040. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2041. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2042. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2043. self._downloader.trouble(u'ERROR: unable to download webpage: ' + unicode(err))
  2044. return
  2045. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2046. description = unescapeHTML(descMatch.group(1))
  2047. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2048. imgUrl = unescapeHTML(imgMatch.group(1))
  2049. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2050. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2051. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2052. configUrl = urllib2.unquote(configUrlMatch.group(1))
  2053. self.report_config_download(showName)
  2054. try:
  2055. configJSON = urllib2.urlopen(configUrl).read()
  2056. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2057. self._downloader.trouble(u'ERROR: unable to download configuration: ' + unicode(err))
  2058. return
  2059. # Technically, it's JavaScript, not JSON
  2060. configJSON = configJSON.replace("'", '"')
  2061. try:
  2062. config = json.loads(configJSON)
  2063. except (ValueError,), err:
  2064. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + unicode(err))
  2065. return
  2066. playlist = config['playlist']
  2067. videoUrl = playlist[1]['url']
  2068. info = {
  2069. 'id': videoId,
  2070. 'url': videoUrl,
  2071. 'uploader': showName,
  2072. 'upload_date': None,
  2073. 'title': showName,
  2074. 'ext': 'flv',
  2075. 'thumbnail': imgUrl,
  2076. 'description': description,
  2077. 'player_url': playerUrl,
  2078. }
  2079. return [info]
  2080. class CollegeHumorIE(InfoExtractor):
  2081. """Information extractor for collegehumor.com"""
  2082. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2083. IE_NAME = u'collegehumor'
  2084. def report_webpage(self, video_id):
  2085. """Report information extraction."""
  2086. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2087. def report_extraction(self, video_id):
  2088. """Report information extraction."""
  2089. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2090. def _real_extract(self, url):
  2091. mobj = re.match(self._VALID_URL, url)
  2092. if mobj is None:
  2093. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2094. return
  2095. video_id = mobj.group('videoid')
  2096. self.report_webpage(video_id)
  2097. request = urllib2.Request(url)
  2098. try:
  2099. webpage = urllib2.urlopen(request).read()
  2100. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2101. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2102. return
  2103. m = re.search(r'id="video:(?P<internalvideoid>[0-9]+)"', webpage)
  2104. if m is None:
  2105. self._downloader.trouble(u'ERROR: Cannot extract internal video ID')
  2106. return
  2107. internal_video_id = m.group('internalvideoid')
  2108. info = {
  2109. 'id': video_id,
  2110. 'internal_id': internal_video_id,
  2111. }
  2112. self.report_extraction(video_id)
  2113. xmlUrl = 'http://www.collegehumor.com/moogaloop/video:' + internal_video_id
  2114. try:
  2115. metaXml = urllib2.urlopen(xmlUrl).read()
  2116. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2117. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2118. return
  2119. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2120. try:
  2121. videoNode = mdoc.findall('./video')[0]
  2122. info['description'] = videoNode.findall('./description')[0].text
  2123. info['title'] = videoNode.findall('./caption')[0].text
  2124. info['url'] = videoNode.findall('./file')[0].text
  2125. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2126. info['ext'] = info['url'].rpartition('.')[2]
  2127. except IndexError:
  2128. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2129. return
  2130. return [info]
  2131. class XVideosIE(InfoExtractor):
  2132. """Information extractor for xvideos.com"""
  2133. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2134. IE_NAME = u'xvideos'
  2135. def report_webpage(self, video_id):
  2136. """Report information extraction."""
  2137. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2138. def report_extraction(self, video_id):
  2139. """Report information extraction."""
  2140. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2141. def _real_extract(self, url):
  2142. mobj = re.match(self._VALID_URL, url)
  2143. if mobj is None:
  2144. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2145. return
  2146. video_id = mobj.group(1).decode('utf-8')
  2147. self.report_webpage(video_id)
  2148. request = urllib2.Request(r'http://www.xvideos.com/video' + video_id)
  2149. try:
  2150. webpage = urllib2.urlopen(request).read()
  2151. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2152. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2153. return
  2154. self.report_extraction(video_id)
  2155. # Extract video URL
  2156. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2157. if mobj is None:
  2158. self._downloader.trouble(u'ERROR: unable to extract video url')
  2159. return
  2160. video_url = urllib2.unquote(mobj.group(1).decode('utf-8'))
  2161. # Extract title
  2162. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2163. if mobj is None:
  2164. self._downloader.trouble(u'ERROR: unable to extract video title')
  2165. return
  2166. video_title = mobj.group(1).decode('utf-8')
  2167. # Extract video thumbnail
  2168. mobj = re.search(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/([a-fA-F0-9.]+jpg)', webpage)
  2169. if mobj is None:
  2170. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2171. return
  2172. video_thumbnail = mobj.group(0).decode('utf-8')
  2173. info = {
  2174. 'id': video_id,
  2175. 'url': video_url,
  2176. 'uploader': None,
  2177. 'upload_date': None,
  2178. 'title': video_title,
  2179. 'ext': 'flv',
  2180. 'thumbnail': video_thumbnail,
  2181. 'description': None,
  2182. }
  2183. return [info]
  2184. class SoundcloudIE(InfoExtractor):
  2185. """Information extractor for soundcloud.com
  2186. To access the media, the uid of the song and a stream token
  2187. must be extracted from the page source and the script must make
  2188. a request to media.soundcloud.com/crossdomain.xml. Then
  2189. the media can be grabbed by requesting from an url composed
  2190. of the stream token and uid
  2191. """
  2192. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2193. IE_NAME = u'soundcloud'
  2194. def __init__(self, downloader=None):
  2195. InfoExtractor.__init__(self, downloader)
  2196. def report_webpage(self, video_id):
  2197. """Report information extraction."""
  2198. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2199. def report_extraction(self, video_id):
  2200. """Report information extraction."""
  2201. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2202. def _real_extract(self, url):
  2203. mobj = re.match(self._VALID_URL, url)
  2204. if mobj is None:
  2205. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2206. return
  2207. # extract uploader (which is in the url)
  2208. uploader = mobj.group(1).decode('utf-8')
  2209. # extract simple title (uploader + slug of song title)
  2210. slug_title = mobj.group(2).decode('utf-8')
  2211. simple_title = uploader + u'-' + slug_title
  2212. self.report_webpage('%s/%s' % (uploader, slug_title))
  2213. request = urllib2.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  2214. try:
  2215. webpage = urllib2.urlopen(request).read()
  2216. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2217. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2218. return
  2219. self.report_extraction('%s/%s' % (uploader, slug_title))
  2220. # extract uid and stream token that soundcloud hands out for access
  2221. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  2222. if mobj:
  2223. video_id = mobj.group(1)
  2224. stream_token = mobj.group(2)
  2225. # extract unsimplified title
  2226. mobj = re.search('"title":"(.*?)",', webpage)
  2227. if mobj:
  2228. title = mobj.group(1).decode('utf-8')
  2229. else:
  2230. title = simple_title
  2231. # construct media url (with uid/token)
  2232. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  2233. mediaURL = mediaURL % (video_id, stream_token)
  2234. # description
  2235. description = u'No description available'
  2236. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  2237. if mobj:
  2238. description = mobj.group(1)
  2239. # upload date
  2240. upload_date = None
  2241. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  2242. if mobj:
  2243. try:
  2244. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  2245. except Exception, e:
  2246. self._downloader.to_stderr(compat_str(e))
  2247. # for soundcloud, a request to a cross domain is required for cookies
  2248. request = urllib2.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  2249. return [{
  2250. 'id': video_id.decode('utf-8'),
  2251. 'url': mediaURL,
  2252. 'uploader': uploader.decode('utf-8'),
  2253. 'upload_date': upload_date,
  2254. 'title': title,
  2255. 'ext': u'mp3',
  2256. 'description': description.decode('utf-8')
  2257. }]
  2258. class InfoQIE(InfoExtractor):
  2259. """Information extractor for infoq.com"""
  2260. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2261. IE_NAME = u'infoq'
  2262. def report_webpage(self, video_id):
  2263. """Report information extraction."""
  2264. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2265. def report_extraction(self, video_id):
  2266. """Report information extraction."""
  2267. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2268. def _real_extract(self, url):
  2269. mobj = re.match(self._VALID_URL, url)
  2270. if mobj is None:
  2271. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2272. return
  2273. self.report_webpage(url)
  2274. request = urllib2.Request(url)
  2275. try:
  2276. webpage = urllib2.urlopen(request).read()
  2277. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2278. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2279. return
  2280. self.report_extraction(url)
  2281. # Extract video URL
  2282. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2283. if mobj is None:
  2284. self._downloader.trouble(u'ERROR: unable to extract video url')
  2285. return
  2286. video_url = 'rtmpe://video.infoq.com/cfx/st/' + urllib2.unquote(mobj.group(1).decode('base64'))
  2287. # Extract title
  2288. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2289. if mobj is None:
  2290. self._downloader.trouble(u'ERROR: unable to extract video title')
  2291. return
  2292. video_title = mobj.group(1).decode('utf-8')
  2293. # Extract description
  2294. video_description = u'No description available.'
  2295. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2296. if mobj is not None:
  2297. video_description = mobj.group(1).decode('utf-8')
  2298. video_filename = video_url.split('/')[-1]
  2299. video_id, extension = video_filename.split('.')
  2300. info = {
  2301. 'id': video_id,
  2302. 'url': video_url,
  2303. 'uploader': None,
  2304. 'upload_date': None,
  2305. 'title': video_title,
  2306. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2307. 'thumbnail': None,
  2308. 'description': video_description,
  2309. }
  2310. return [info]
  2311. class MixcloudIE(InfoExtractor):
  2312. """Information extractor for www.mixcloud.com"""
  2313. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2314. IE_NAME = u'mixcloud'
  2315. def __init__(self, downloader=None):
  2316. InfoExtractor.__init__(self, downloader)
  2317. def report_download_json(self, file_id):
  2318. """Report JSON download."""
  2319. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2320. def report_extraction(self, file_id):
  2321. """Report information extraction."""
  2322. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2323. def get_urls(self, jsonData, fmt, bitrate='best'):
  2324. """Get urls from 'audio_formats' section in json"""
  2325. file_url = None
  2326. try:
  2327. bitrate_list = jsonData[fmt]
  2328. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2329. bitrate = max(bitrate_list) # select highest
  2330. url_list = jsonData[fmt][bitrate]
  2331. except TypeError: # we have no bitrate info.
  2332. url_list = jsonData[fmt]
  2333. return url_list
  2334. def check_urls(self, url_list):
  2335. """Returns 1st active url from list"""
  2336. for url in url_list:
  2337. try:
  2338. urllib2.urlopen(url)
  2339. return url
  2340. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2341. url = None
  2342. return None
  2343. def _print_formats(self, formats):
  2344. print('Available formats:')
  2345. for fmt in formats.keys():
  2346. for b in formats[fmt]:
  2347. try:
  2348. ext = formats[fmt][b][0]
  2349. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2350. except TypeError: # we have no bitrate info
  2351. ext = formats[fmt][0]
  2352. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2353. break
  2354. def _real_extract(self, url):
  2355. mobj = re.match(self._VALID_URL, url)
  2356. if mobj is None:
  2357. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2358. return
  2359. # extract uploader & filename from url
  2360. uploader = mobj.group(1).decode('utf-8')
  2361. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2362. # construct API request
  2363. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2364. # retrieve .json file with links to files
  2365. request = urllib2.Request(file_url)
  2366. try:
  2367. self.report_download_json(file_url)
  2368. jsonData = urllib2.urlopen(request).read()
  2369. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2370. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2371. return
  2372. # parse JSON
  2373. json_data = json.loads(jsonData)
  2374. player_url = json_data['player_swf_url']
  2375. formats = dict(json_data['audio_formats'])
  2376. req_format = self._downloader.params.get('format', None)
  2377. bitrate = None
  2378. if self._downloader.params.get('listformats', None):
  2379. self._print_formats(formats)
  2380. return
  2381. if req_format is None or req_format == 'best':
  2382. for format_param in formats.keys():
  2383. url_list = self.get_urls(formats, format_param)
  2384. # check urls
  2385. file_url = self.check_urls(url_list)
  2386. if file_url is not None:
  2387. break # got it!
  2388. else:
  2389. if req_format not in formats.keys():
  2390. self._downloader.trouble(u'ERROR: format is not available')
  2391. return
  2392. url_list = self.get_urls(formats, req_format)
  2393. file_url = self.check_urls(url_list)
  2394. format_param = req_format
  2395. return [{
  2396. 'id': file_id.decode('utf-8'),
  2397. 'url': file_url.decode('utf-8'),
  2398. 'uploader': uploader.decode('utf-8'),
  2399. 'upload_date': u'NA',
  2400. 'title': json_data['name'],
  2401. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2402. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2403. 'thumbnail': json_data['thumbnail_url'],
  2404. 'description': json_data['description'],
  2405. 'player_url': player_url.decode('utf-8'),
  2406. }]
  2407. class StanfordOpenClassroomIE(InfoExtractor):
  2408. """Information extractor for Stanford's Open ClassRoom"""
  2409. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2410. IE_NAME = u'stanfordoc'
  2411. def report_download_webpage(self, objid):
  2412. """Report information extraction."""
  2413. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2414. def report_extraction(self, video_id):
  2415. """Report information extraction."""
  2416. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2417. def _real_extract(self, url):
  2418. mobj = re.match(self._VALID_URL, url)
  2419. if mobj is None:
  2420. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2421. return
  2422. if mobj.group('course') and mobj.group('video'): # A specific video
  2423. course = mobj.group('course')
  2424. video = mobj.group('video')
  2425. info = {
  2426. 'id': course + '_' + video,
  2427. }
  2428. self.report_extraction(info['id'])
  2429. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2430. xmlUrl = baseUrl + video + '.xml'
  2431. try:
  2432. metaXml = urllib2.urlopen(xmlUrl).read()
  2433. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2434. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % unicode(err))
  2435. return
  2436. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2437. try:
  2438. info['title'] = mdoc.findall('./title')[0].text
  2439. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2440. except IndexError:
  2441. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2442. return
  2443. info['ext'] = info['url'].rpartition('.')[2]
  2444. return [info]
  2445. elif mobj.group('course'): # A course page
  2446. course = mobj.group('course')
  2447. info = {
  2448. 'id': course,
  2449. 'type': 'playlist',
  2450. }
  2451. self.report_download_webpage(info['id'])
  2452. try:
  2453. coursepage = urllib2.urlopen(url).read()
  2454. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2455. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  2456. return
  2457. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2458. if m:
  2459. info['title'] = unescapeHTML(m.group(1))
  2460. else:
  2461. info['title'] = info['id']
  2462. m = re.search('<description>([^<]+)</description>', coursepage)
  2463. if m:
  2464. info['description'] = unescapeHTML(m.group(1))
  2465. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2466. info['list'] = [
  2467. {
  2468. 'type': 'reference',
  2469. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2470. }
  2471. for vpage in links]
  2472. results = []
  2473. for entry in info['list']:
  2474. assert entry['type'] == 'reference'
  2475. results += self.extract(entry['url'])
  2476. return results
  2477. else: # Root page
  2478. info = {
  2479. 'id': 'Stanford OpenClassroom',
  2480. 'type': 'playlist',
  2481. }
  2482. self.report_download_webpage(info['id'])
  2483. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2484. try:
  2485. rootpage = urllib2.urlopen(rootURL).read()
  2486. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2487. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  2488. return
  2489. info['title'] = info['id']
  2490. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2491. info['list'] = [
  2492. {
  2493. 'type': 'reference',
  2494. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2495. }
  2496. for cpage in links]
  2497. results = []
  2498. for entry in info['list']:
  2499. assert entry['type'] == 'reference'
  2500. results += self.extract(entry['url'])
  2501. return results
  2502. class MTVIE(InfoExtractor):
  2503. """Information extractor for MTV.com"""
  2504. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2505. IE_NAME = u'mtv'
  2506. def report_webpage(self, video_id):
  2507. """Report information extraction."""
  2508. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2509. def report_extraction(self, video_id):
  2510. """Report information extraction."""
  2511. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2512. def _real_extract(self, url):
  2513. mobj = re.match(self._VALID_URL, url)
  2514. if mobj is None:
  2515. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2516. return
  2517. if not mobj.group('proto'):
  2518. url = 'http://' + url
  2519. video_id = mobj.group('videoid')
  2520. self.report_webpage(video_id)
  2521. request = urllib2.Request(url)
  2522. try:
  2523. webpage = urllib2.urlopen(request).read()
  2524. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2525. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2526. return
  2527. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2528. if mobj is None:
  2529. self._downloader.trouble(u'ERROR: unable to extract song name')
  2530. return
  2531. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2532. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2533. if mobj is None:
  2534. self._downloader.trouble(u'ERROR: unable to extract performer')
  2535. return
  2536. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2537. video_title = performer + ' - ' + song_name
  2538. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2539. if mobj is None:
  2540. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2541. return
  2542. mtvn_uri = mobj.group(1)
  2543. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2544. if mobj is None:
  2545. self._downloader.trouble(u'ERROR: unable to extract content id')
  2546. return
  2547. content_id = mobj.group(1)
  2548. videogen_url = 'http://www.mtv.com/player/includes/mediaGen.jhtml?uri=' + mtvn_uri + '&id=' + content_id + '&vid=' + video_id + '&ref=www.mtvn.com&viewUri=' + mtvn_uri
  2549. self.report_extraction(video_id)
  2550. request = urllib2.Request(videogen_url)
  2551. try:
  2552. metadataXml = urllib2.urlopen(request).read()
  2553. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2554. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2555. return
  2556. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2557. renditions = mdoc.findall('.//rendition')
  2558. # For now, always pick the highest quality.
  2559. rendition = renditions[-1]
  2560. try:
  2561. _,_,ext = rendition.attrib['type'].partition('/')
  2562. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2563. video_url = rendition.find('./src').text
  2564. except KeyError:
  2565. self._downloader.trouble('Invalid rendition field.')
  2566. return
  2567. info = {
  2568. 'id': video_id,
  2569. 'url': video_url,
  2570. 'uploader': performer,
  2571. 'title': video_title,
  2572. 'ext': ext,
  2573. 'format': format,
  2574. }
  2575. return [info]
  2576. class YoukuIE(InfoExtractor):
  2577. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2578. IE_NAME = u'Youku'
  2579. def __init__(self, downloader=None):
  2580. InfoExtractor.__init__(self, downloader)
  2581. def report_download_webpage(self, file_id):
  2582. """Report webpage download."""
  2583. self._downloader.to_screen(u'[Youku] %s: Downloading webpage' % file_id)
  2584. def report_extraction(self, file_id):
  2585. """Report information extraction."""
  2586. self._downloader.to_screen(u'[Youku] %s: Extracting information' % file_id)
  2587. def _gen_sid(self):
  2588. nowTime = int(time.time() * 1000)
  2589. random1 = random.randint(1000,1998)
  2590. random2 = random.randint(1000,9999)
  2591. return "%d%d%d" %(nowTime,random1,random2)
  2592. def _get_file_ID_mix_string(self, seed):
  2593. mixed = []
  2594. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2595. seed = float(seed)
  2596. for i in range(len(source)):
  2597. seed = (seed * 211 + 30031 ) % 65536
  2598. index = math.floor(seed / 65536 * len(source) )
  2599. mixed.append(source[int(index)])
  2600. source.remove(source[int(index)])
  2601. #return ''.join(mixed)
  2602. return mixed
  2603. def _get_file_id(self, fileId, seed):
  2604. mixed = self._get_file_ID_mix_string(seed)
  2605. ids = fileId.split('*')
  2606. realId = []
  2607. for ch in ids:
  2608. if ch:
  2609. realId.append(mixed[int(ch)])
  2610. return ''.join(realId)
  2611. def _real_extract(self, url):
  2612. mobj = re.match(self._VALID_URL, url)
  2613. if mobj is None:
  2614. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2615. return
  2616. video_id = mobj.group('ID')
  2617. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2618. request = urllib2.Request(info_url, None, std_headers)
  2619. try:
  2620. self.report_download_webpage(video_id)
  2621. jsondata = urllib2.urlopen(request).read()
  2622. except (urllib2.URLError, httplib.HTTPException, socket.error) as err:
  2623. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2624. return
  2625. self.report_extraction(video_id)
  2626. try:
  2627. config = json.loads(jsondata)
  2628. video_title = config['data'][0]['title']
  2629. seed = config['data'][0]['seed']
  2630. format = self._downloader.params.get('format', None)
  2631. supported_format = config['data'][0]['streamfileids'].keys()
  2632. if format is None or format == 'best':
  2633. if 'hd2' in supported_format:
  2634. format = 'hd2'
  2635. else:
  2636. format = 'flv'
  2637. ext = u'flv'
  2638. elif format == 'worst':
  2639. format = 'mp4'
  2640. ext = u'mp4'
  2641. else:
  2642. format = 'flv'
  2643. ext = u'flv'
  2644. fileid = config['data'][0]['streamfileids'][format]
  2645. seg_number = len(config['data'][0]['segs'][format])
  2646. keys=[]
  2647. for i in xrange(seg_number):
  2648. keys.append(config['data'][0]['segs'][format][i]['k'])
  2649. #TODO check error
  2650. #youku only could be viewed from mainland china
  2651. except:
  2652. self._downloader.trouble(u'ERROR: unable to extract info section')
  2653. return
  2654. files_info=[]
  2655. sid = self._gen_sid()
  2656. fileid = self._get_file_id(fileid, seed)
  2657. #column 8,9 of fileid represent the segment number
  2658. #fileid[7:9] should be changed
  2659. for index, key in enumerate(keys):
  2660. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2661. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2662. info = {
  2663. 'id': '%s_part%02d' % (video_id, index),
  2664. 'url': download_url,
  2665. 'uploader': None,
  2666. 'title': video_title,
  2667. 'ext': ext,
  2668. }
  2669. files_info.append(info)
  2670. return files_info
  2671. class XNXXIE(InfoExtractor):
  2672. """Information extractor for xnxx.com"""
  2673. _VALID_URL = r'^http://video\.xnxx\.com/video([0-9]+)/(.*)'
  2674. IE_NAME = u'xnxx'
  2675. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2676. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2677. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2678. def report_webpage(self, video_id):
  2679. """Report information extraction"""
  2680. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2681. def report_extraction(self, video_id):
  2682. """Report information extraction"""
  2683. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2684. def _real_extract(self, url):
  2685. mobj = re.match(self._VALID_URL, url)
  2686. if mobj is None:
  2687. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2688. return
  2689. video_id = mobj.group(1).decode('utf-8')
  2690. self.report_webpage(video_id)
  2691. # Get webpage content
  2692. try:
  2693. webpage = urllib2.urlopen(url).read()
  2694. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2695. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2696. return
  2697. result = re.search(self.VIDEO_URL_RE, webpage)
  2698. if result is None:
  2699. self._downloader.trouble(u'ERROR: unable to extract video url')
  2700. return
  2701. video_url = urllib.unquote(result.group(1).decode('utf-8'))
  2702. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2703. if result is None:
  2704. self._downloader.trouble(u'ERROR: unable to extract video title')
  2705. return
  2706. video_title = result.group(1).decode('utf-8')
  2707. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2708. if result is None:
  2709. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2710. return
  2711. video_thumbnail = result.group(1).decode('utf-8')
  2712. return [{
  2713. 'id': video_id,
  2714. 'url': video_url,
  2715. 'uploader': None,
  2716. 'upload_date': None,
  2717. 'title': video_title,
  2718. 'ext': 'flv',
  2719. 'thumbnail': video_thumbnail,
  2720. 'description': None,
  2721. }]
  2722. class GooglePlusIE(InfoExtractor):
  2723. """Information extractor for plus.google.com."""
  2724. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:\w+/)*?(\d+)/posts/(\w+)'
  2725. IE_NAME = u'plus.google'
  2726. def __init__(self, downloader=None):
  2727. InfoExtractor.__init__(self, downloader)
  2728. def report_extract_entry(self, url):
  2729. """Report downloading extry"""
  2730. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url.decode('utf-8'))
  2731. def report_date(self, upload_date):
  2732. """Report downloading extry"""
  2733. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2734. def report_uploader(self, uploader):
  2735. """Report downloading extry"""
  2736. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader.decode('utf-8'))
  2737. def report_title(self, video_title):
  2738. """Report downloading extry"""
  2739. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title.decode('utf-8'))
  2740. def report_extract_vid_page(self, video_page):
  2741. """Report information extraction."""
  2742. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page.decode('utf-8'))
  2743. def _real_extract(self, url):
  2744. # Extract id from URL
  2745. mobj = re.match(self._VALID_URL, url)
  2746. if mobj is None:
  2747. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2748. return
  2749. post_url = mobj.group(0)
  2750. video_id = mobj.group(2)
  2751. video_extension = 'flv'
  2752. # Step 1, Retrieve post webpage to extract further information
  2753. self.report_extract_entry(post_url)
  2754. request = urllib2.Request(post_url)
  2755. try:
  2756. webpage = urllib2.urlopen(request).read()
  2757. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2758. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2759. return
  2760. # Extract update date
  2761. upload_date = u'NA'
  2762. pattern = 'title="Timestamp">(.*?)</a>'
  2763. mobj = re.search(pattern, webpage)
  2764. if mobj:
  2765. upload_date = mobj.group(1)
  2766. # Convert timestring to a format suitable for filename
  2767. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2768. upload_date = upload_date.strftime('%Y%m%d')
  2769. self.report_date(upload_date)
  2770. # Extract uploader
  2771. uploader = u'NA'
  2772. pattern = r'rel\="author".*?>(.*?)</a>'
  2773. mobj = re.search(pattern, webpage)
  2774. if mobj:
  2775. uploader = mobj.group(1)
  2776. self.report_uploader(uploader)
  2777. # Extract title
  2778. # Get the first line for title
  2779. video_title = u'NA'
  2780. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2781. mobj = re.search(pattern, webpage)
  2782. if mobj:
  2783. video_title = mobj.group(1)
  2784. self.report_title(video_title)
  2785. # Step 2, Stimulate clicking the image box to launch video
  2786. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2787. mobj = re.search(pattern, webpage)
  2788. if mobj is None:
  2789. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2790. video_page = mobj.group(1)
  2791. request = urllib2.Request(video_page)
  2792. try:
  2793. webpage = urllib2.urlopen(request).read()
  2794. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2795. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2796. return
  2797. self.report_extract_vid_page(video_page)
  2798. # Extract video links on video page
  2799. """Extract video links of all sizes"""
  2800. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2801. mobj = re.findall(pattern, webpage)
  2802. if len(mobj) == 0:
  2803. self._downloader.trouble(u'ERROR: unable to extract video links')
  2804. # Sort in resolution
  2805. links = sorted(mobj)
  2806. # Choose the lowest of the sort, i.e. highest resolution
  2807. video_url = links[-1]
  2808. # Only get the url. The resolution part in the tuple has no use anymore
  2809. video_url = video_url[-1]
  2810. # Treat escaped \u0026 style hex
  2811. video_url = unicode(video_url, "unicode_escape")
  2812. return [{
  2813. 'id': video_id.decode('utf-8'),
  2814. 'url': video_url,
  2815. 'uploader': uploader.decode('utf-8'),
  2816. 'upload_date': upload_date.decode('utf-8'),
  2817. 'title': video_title.decode('utf-8'),
  2818. 'ext': video_extension.decode('utf-8'),
  2819. }]