InfoExtractors.py 165 KB

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