InfoExtractors.py 167 KB

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