InfoExtractors.py 115 KB

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