InfoExtractors.py 151 KB

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