InfoExtractors.py 176 KB

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