InfoExtractors.py 115 KB

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