InfoExtractors.py 171 KB

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