InfoExtractors.py 157 KB

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