InfoExtractors.py 169 KB

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