InfoExtractors.py 167 KB

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