InfoExtractors.py 120 KB

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