InfoExtractors.py 167 KB

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