InfoExtractors.py 167 KB

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