InfoExtractors.py 159 KB

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