InfoExtractors.py 118 KB

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