InfoExtractors.py 166 KB

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