InfoExtractors.py 167 KB

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