InfoExtractors.py 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345
  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. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  939. self._downloader.report_error(u'The author has restricted the access to this video, try with the "--referer" option')
  940. else:
  941. self._downloader.report_error(u'unable to extract info section')
  942. return
  943. # Extract title
  944. video_title = config["video"]["title"]
  945. # Extract uploader and uploader_id
  946. video_uploader = config["video"]["owner"]["name"]
  947. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  948. # Extract video thumbnail
  949. video_thumbnail = config["video"]["thumbnail"]
  950. # Extract video description
  951. video_description = get_element_by_attribute("itemprop", "description", webpage)
  952. if video_description: video_description = clean_html(video_description)
  953. else: video_description = u''
  954. # Extract upload date
  955. video_upload_date = None
  956. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  957. if mobj is not None:
  958. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  959. # Vimeo specific: extract request signature and timestamp
  960. sig = config['request']['signature']
  961. timestamp = config['request']['timestamp']
  962. # Vimeo specific: extract video codec and quality information
  963. # First consider quality, then codecs, then take everything
  964. # TODO bind to format param
  965. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  966. files = { 'hd': [], 'sd': [], 'other': []}
  967. for codec_name, codec_extension in codecs:
  968. if codec_name in config["video"]["files"]:
  969. if 'hd' in config["video"]["files"][codec_name]:
  970. files['hd'].append((codec_name, codec_extension, 'hd'))
  971. elif 'sd' in config["video"]["files"][codec_name]:
  972. files['sd'].append((codec_name, codec_extension, 'sd'))
  973. else:
  974. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  975. for quality in ('hd', 'sd', 'other'):
  976. if len(files[quality]) > 0:
  977. video_quality = files[quality][0][2]
  978. video_codec = files[quality][0][0]
  979. video_extension = files[quality][0][1]
  980. self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  981. break
  982. else:
  983. self._downloader.report_error(u'no known codec found')
  984. return
  985. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  986. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  987. return [{
  988. 'id': video_id,
  989. 'url': video_url,
  990. 'uploader': video_uploader,
  991. 'uploader_id': video_uploader_id,
  992. 'upload_date': video_upload_date,
  993. 'title': video_title,
  994. 'ext': video_extension,
  995. 'thumbnail': video_thumbnail,
  996. 'description': video_description,
  997. }]
  998. class ArteTvIE(InfoExtractor):
  999. """arte.tv information extractor."""
  1000. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  1001. _LIVE_URL = r'index-[0-9]+\.html$'
  1002. IE_NAME = u'arte.tv'
  1003. def fetch_webpage(self, url):
  1004. request = compat_urllib_request.Request(url)
  1005. try:
  1006. self.report_download_webpage(url)
  1007. webpage = compat_urllib_request.urlopen(request).read()
  1008. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1009. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  1010. return
  1011. except ValueError as err:
  1012. self._downloader.report_error(u'Invalid URL: %s' % url)
  1013. return
  1014. return webpage
  1015. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  1016. page = self.fetch_webpage(url)
  1017. mobj = re.search(regex, page, regexFlags)
  1018. info = {}
  1019. if mobj is None:
  1020. self._downloader.report_error(u'Invalid URL: %s' % url)
  1021. return
  1022. for (i, key, err) in matchTuples:
  1023. if mobj.group(i) is None:
  1024. self._downloader.report_error(err)
  1025. return
  1026. else:
  1027. info[key] = mobj.group(i)
  1028. return info
  1029. def extractLiveStream(self, url):
  1030. video_lang = url.split('/')[-4]
  1031. info = self.grep_webpage(
  1032. url,
  1033. r'src="(.*?/videothek_js.*?\.js)',
  1034. 0,
  1035. [
  1036. (1, 'url', u'Invalid URL: %s' % url)
  1037. ]
  1038. )
  1039. http_host = url.split('/')[2]
  1040. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  1041. info = self.grep_webpage(
  1042. next_url,
  1043. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  1044. '(http://.*?\.swf).*?' +
  1045. '(rtmp://.*?)\'',
  1046. re.DOTALL,
  1047. [
  1048. (1, 'path', u'could not extract video path: %s' % url),
  1049. (2, 'player', u'could not extract video player: %s' % url),
  1050. (3, 'url', u'could not extract video url: %s' % url)
  1051. ]
  1052. )
  1053. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  1054. def extractPlus7Stream(self, url):
  1055. video_lang = url.split('/')[-3]
  1056. info = self.grep_webpage(
  1057. url,
  1058. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  1059. 0,
  1060. [
  1061. (1, 'url', u'Invalid URL: %s' % url)
  1062. ]
  1063. )
  1064. next_url = compat_urllib_parse.unquote(info.get('url'))
  1065. info = self.grep_webpage(
  1066. next_url,
  1067. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  1068. 0,
  1069. [
  1070. (1, 'url', u'Could not find <video> tag: %s' % url)
  1071. ]
  1072. )
  1073. next_url = compat_urllib_parse.unquote(info.get('url'))
  1074. info = self.grep_webpage(
  1075. next_url,
  1076. r'<video id="(.*?)".*?>.*?' +
  1077. '<name>(.*?)</name>.*?' +
  1078. '<dateVideo>(.*?)</dateVideo>.*?' +
  1079. '<url quality="hd">(.*?)</url>',
  1080. re.DOTALL,
  1081. [
  1082. (1, 'id', u'could not extract video id: %s' % url),
  1083. (2, 'title', u'could not extract video title: %s' % url),
  1084. (3, 'date', u'could not extract video date: %s' % url),
  1085. (4, 'url', u'could not extract video url: %s' % url)
  1086. ]
  1087. )
  1088. return {
  1089. 'id': info.get('id'),
  1090. 'url': compat_urllib_parse.unquote(info.get('url')),
  1091. 'uploader': u'arte.tv',
  1092. 'upload_date': info.get('date'),
  1093. 'title': info.get('title').decode('utf-8'),
  1094. 'ext': u'mp4',
  1095. 'format': u'NA',
  1096. 'player_url': None,
  1097. }
  1098. def _real_extract(self, url):
  1099. video_id = url.split('/')[-1]
  1100. self.report_extraction(video_id)
  1101. if re.search(self._LIVE_URL, video_id) is not None:
  1102. self.extractLiveStream(url)
  1103. return
  1104. else:
  1105. info = self.extractPlus7Stream(url)
  1106. return [info]
  1107. class GenericIE(InfoExtractor):
  1108. """Generic last-resort information extractor."""
  1109. _VALID_URL = r'.*'
  1110. IE_NAME = u'generic'
  1111. def report_download_webpage(self, video_id):
  1112. """Report webpage download."""
  1113. if not self._downloader.params.get('test', False):
  1114. self._downloader.report_warning(u'Falling back on generic information extractor.')
  1115. super(GenericIE, self).report_download_webpage(video_id)
  1116. def report_following_redirect(self, new_url):
  1117. """Report information extraction."""
  1118. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1119. def _test_redirect(self, url):
  1120. """Check if it is a redirect, like url shorteners, in case return the new url."""
  1121. class HeadRequest(compat_urllib_request.Request):
  1122. def get_method(self):
  1123. return "HEAD"
  1124. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1125. """
  1126. Subclass the HTTPRedirectHandler to make it use our
  1127. HeadRequest also on the redirected URL
  1128. """
  1129. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1130. if code in (301, 302, 303, 307):
  1131. newurl = newurl.replace(' ', '%20')
  1132. newheaders = dict((k,v) for k,v in req.headers.items()
  1133. if k.lower() not in ("content-length", "content-type"))
  1134. return HeadRequest(newurl,
  1135. headers=newheaders,
  1136. origin_req_host=req.get_origin_req_host(),
  1137. unverifiable=True)
  1138. else:
  1139. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1140. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1141. """
  1142. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1143. """
  1144. def http_error_405(self, req, fp, code, msg, headers):
  1145. fp.read()
  1146. fp.close()
  1147. newheaders = dict((k,v) for k,v in req.headers.items()
  1148. if k.lower() not in ("content-length", "content-type"))
  1149. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1150. headers=newheaders,
  1151. origin_req_host=req.get_origin_req_host(),
  1152. unverifiable=True))
  1153. # Build our opener
  1154. opener = compat_urllib_request.OpenerDirector()
  1155. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1156. HTTPMethodFallback, HEADRedirectHandler,
  1157. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1158. opener.add_handler(handler())
  1159. response = opener.open(HeadRequest(url))
  1160. new_url = response.geturl()
  1161. if url == new_url:
  1162. return False
  1163. self.report_following_redirect(new_url)
  1164. return new_url
  1165. def _real_extract(self, url):
  1166. new_url = self._test_redirect(url)
  1167. if new_url: return [self.url_result(new_url)]
  1168. video_id = url.split('/')[-1]
  1169. try:
  1170. webpage = self._download_webpage(url, video_id)
  1171. except ValueError as err:
  1172. # since this is the last-resort InfoExtractor, if
  1173. # this error is thrown, it'll be thrown here
  1174. self._downloader.report_error(u'Invalid URL: %s' % url)
  1175. return
  1176. self.report_extraction(video_id)
  1177. # Start with something easy: JW Player in SWFObject
  1178. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1179. if mobj is None:
  1180. # Broaden the search a little bit
  1181. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1182. if mobj is None:
  1183. # Broaden the search a little bit: JWPlayer JS loader
  1184. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  1185. if mobj is None:
  1186. self._downloader.report_error(u'Invalid URL: %s' % url)
  1187. return
  1188. # It's possible that one of the regexes
  1189. # matched, but returned an empty group:
  1190. if mobj.group(1) is None:
  1191. self._downloader.report_error(u'Invalid URL: %s' % url)
  1192. return
  1193. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1194. video_id = os.path.basename(video_url)
  1195. # here's a fun little line of code for you:
  1196. video_extension = os.path.splitext(video_id)[1][1:]
  1197. video_id = os.path.splitext(video_id)[0]
  1198. # it's tempting to parse this further, but you would
  1199. # have to take into account all the variations like
  1200. # Video Title - Site Name
  1201. # Site Name | Video Title
  1202. # Video Title - Tagline | Site Name
  1203. # and so on and so forth; it's just not practical
  1204. mobj = re.search(r'<title>(.*)</title>', webpage)
  1205. if mobj is None:
  1206. self._downloader.report_error(u'unable to extract title')
  1207. return
  1208. video_title = mobj.group(1)
  1209. # video uploader is domain name
  1210. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1211. if mobj is None:
  1212. self._downloader.report_error(u'unable to extract title')
  1213. return
  1214. video_uploader = mobj.group(1)
  1215. return [{
  1216. 'id': video_id,
  1217. 'url': video_url,
  1218. 'uploader': video_uploader,
  1219. 'upload_date': None,
  1220. 'title': video_title,
  1221. 'ext': video_extension,
  1222. }]
  1223. class YoutubeSearchIE(InfoExtractor):
  1224. """Information Extractor for YouTube search queries."""
  1225. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1226. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1227. _max_youtube_results = 1000
  1228. IE_NAME = u'youtube:search'
  1229. def report_download_page(self, query, pagenum):
  1230. """Report attempt to download search page with given number."""
  1231. query = query.decode(preferredencoding())
  1232. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1233. def _real_extract(self, query):
  1234. mobj = re.match(self._VALID_URL, query)
  1235. if mobj is None:
  1236. self._downloader.report_error(u'invalid search query "%s"' % query)
  1237. return
  1238. prefix, query = query.split(':')
  1239. prefix = prefix[8:]
  1240. query = query.encode('utf-8')
  1241. if prefix == '':
  1242. return self._get_n_results(query, 1)
  1243. elif prefix == 'all':
  1244. self._get_n_results(query, self._max_youtube_results)
  1245. else:
  1246. try:
  1247. n = int(prefix)
  1248. if n <= 0:
  1249. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1250. return
  1251. elif n > self._max_youtube_results:
  1252. self._downloader.report_warning(u'ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1253. n = self._max_youtube_results
  1254. return self._get_n_results(query, n)
  1255. except ValueError: # parsing prefix as integer fails
  1256. return self._get_n_results(query, 1)
  1257. def _get_n_results(self, query, n):
  1258. """Get a specified number of results for a query"""
  1259. video_ids = []
  1260. pagenum = 0
  1261. limit = n
  1262. while (50 * pagenum) < limit:
  1263. self.report_download_page(query, pagenum+1)
  1264. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1265. request = compat_urllib_request.Request(result_url)
  1266. try:
  1267. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1268. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1269. self._downloader.report_error(u'unable to download API page: %s' % compat_str(err))
  1270. return
  1271. api_response = json.loads(data)['data']
  1272. if not 'items' in api_response:
  1273. self._downloader.report_error(u'[youtube] No video results')
  1274. return
  1275. new_ids = list(video['id'] for video in api_response['items'])
  1276. video_ids += new_ids
  1277. limit = min(n, api_response['totalItems'])
  1278. pagenum += 1
  1279. if len(video_ids) > n:
  1280. video_ids = video_ids[:n]
  1281. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  1282. return videos
  1283. class GoogleSearchIE(InfoExtractor):
  1284. """Information Extractor for Google Video search queries."""
  1285. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1286. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1287. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1288. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1289. _max_google_results = 1000
  1290. IE_NAME = u'video.google:search'
  1291. def report_download_page(self, query, pagenum):
  1292. """Report attempt to download playlist page with given number."""
  1293. query = query.decode(preferredencoding())
  1294. self.to_screen(u'query "%s": Downloading page %s' % (query, pagenum))
  1295. def _real_extract(self, query):
  1296. mobj = re.match(self._VALID_URL, query)
  1297. if mobj is None:
  1298. self._downloader.report_error(u'invalid search query "%s"' % query)
  1299. return
  1300. prefix, query = query.split(':')
  1301. prefix = prefix[8:]
  1302. query = query.encode('utf-8')
  1303. if prefix == '':
  1304. self._download_n_results(query, 1)
  1305. return
  1306. elif prefix == 'all':
  1307. self._download_n_results(query, self._max_google_results)
  1308. return
  1309. else:
  1310. try:
  1311. n = int(prefix)
  1312. if n <= 0:
  1313. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1314. return
  1315. elif n > self._max_google_results:
  1316. self._downloader.report_warning(u'gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1317. n = self._max_google_results
  1318. self._download_n_results(query, n)
  1319. return
  1320. except ValueError: # parsing prefix as integer fails
  1321. self._download_n_results(query, 1)
  1322. return
  1323. def _download_n_results(self, query, n):
  1324. """Downloads a specified number of results for a query"""
  1325. video_ids = []
  1326. pagenum = 0
  1327. while True:
  1328. self.report_download_page(query, pagenum)
  1329. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1330. request = compat_urllib_request.Request(result_url)
  1331. try:
  1332. page = compat_urllib_request.urlopen(request).read()
  1333. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1334. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1335. return
  1336. # Extract video identifiers
  1337. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1338. video_id = mobj.group(1)
  1339. if video_id not in video_ids:
  1340. video_ids.append(video_id)
  1341. if len(video_ids) == n:
  1342. # Specified n videos reached
  1343. for id in video_ids:
  1344. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1345. return
  1346. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1347. for id in video_ids:
  1348. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1349. return
  1350. pagenum = pagenum + 1
  1351. class YahooSearchIE(InfoExtractor):
  1352. """Information Extractor for Yahoo! Video search queries."""
  1353. _WORKING = False
  1354. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1355. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1356. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1357. _MORE_PAGES_INDICATOR = r'\s*Next'
  1358. _max_yahoo_results = 1000
  1359. IE_NAME = u'video.yahoo:search'
  1360. def report_download_page(self, query, pagenum):
  1361. """Report attempt to download playlist page with given number."""
  1362. query = query.decode(preferredencoding())
  1363. self.to_screen(u'query "%s": Downloading page %s' % (query, pagenum))
  1364. def _real_extract(self, query):
  1365. mobj = re.match(self._VALID_URL, query)
  1366. if mobj is None:
  1367. self._downloader.report_error(u'invalid search query "%s"' % query)
  1368. return
  1369. prefix, query = query.split(':')
  1370. prefix = prefix[8:]
  1371. query = query.encode('utf-8')
  1372. if prefix == '':
  1373. self._download_n_results(query, 1)
  1374. return
  1375. elif prefix == 'all':
  1376. self._download_n_results(query, self._max_yahoo_results)
  1377. return
  1378. else:
  1379. try:
  1380. n = int(prefix)
  1381. if n <= 0:
  1382. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1383. return
  1384. elif n > self._max_yahoo_results:
  1385. self._downloader.report_warning(u'yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1386. n = self._max_yahoo_results
  1387. self._download_n_results(query, n)
  1388. return
  1389. except ValueError: # parsing prefix as integer fails
  1390. self._download_n_results(query, 1)
  1391. return
  1392. def _download_n_results(self, query, n):
  1393. """Downloads a specified number of results for a query"""
  1394. video_ids = []
  1395. already_seen = set()
  1396. pagenum = 1
  1397. while True:
  1398. self.report_download_page(query, pagenum)
  1399. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1400. request = compat_urllib_request.Request(result_url)
  1401. try:
  1402. page = compat_urllib_request.urlopen(request).read()
  1403. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1404. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1405. return
  1406. # Extract video identifiers
  1407. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1408. video_id = mobj.group(1)
  1409. if video_id not in already_seen:
  1410. video_ids.append(video_id)
  1411. already_seen.add(video_id)
  1412. if len(video_ids) == n:
  1413. # Specified n videos reached
  1414. for id in video_ids:
  1415. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1416. return
  1417. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1418. for id in video_ids:
  1419. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1420. return
  1421. pagenum = pagenum + 1
  1422. class YoutubePlaylistIE(InfoExtractor):
  1423. """Information Extractor for YouTube playlists."""
  1424. _VALID_URL = r"""(?:
  1425. (?:https?://)?
  1426. (?:\w+\.)?
  1427. youtube\.com/
  1428. (?:
  1429. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1430. \? (?:.*?&)*? (?:p|a|list)=
  1431. | p/
  1432. )
  1433. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  1434. .*
  1435. |
  1436. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  1437. )"""
  1438. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json'
  1439. _MAX_RESULTS = 50
  1440. IE_NAME = u'youtube:playlist'
  1441. @classmethod
  1442. def suitable(cls, url):
  1443. """Receives a URL and returns True if suitable for this IE."""
  1444. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1445. def report_download_page(self, playlist_id, pagenum):
  1446. """Report attempt to download playlist page with given number."""
  1447. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1448. def _real_extract(self, url):
  1449. # Extract playlist id
  1450. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1451. if mobj is None:
  1452. self._downloader.report_error(u'invalid url: %s' % url)
  1453. return
  1454. # Download playlist videos from API
  1455. playlist_id = mobj.group(1) or mobj.group(2)
  1456. page_num = 1
  1457. videos = []
  1458. while True:
  1459. self.report_download_page(playlist_id, page_num)
  1460. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  1461. try:
  1462. page = compat_urllib_request.urlopen(url).read().decode('utf8')
  1463. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1464. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1465. return
  1466. try:
  1467. response = json.loads(page)
  1468. except ValueError as err:
  1469. self._downloader.report_error(u'Invalid JSON in API response: ' + compat_str(err))
  1470. return
  1471. if 'feed' not in response:
  1472. self._downloader.report_error(u'Got a malformed response from YouTube API')
  1473. return
  1474. playlist_title = response['feed']['title']['$t']
  1475. if 'entry' not in response['feed']:
  1476. # Number of videos is a multiple of self._MAX_RESULTS
  1477. break
  1478. videos += [ (entry['yt$position']['$t'], entry['content']['src'])
  1479. for entry in response['feed']['entry']
  1480. if 'content' in entry ]
  1481. if len(response['feed']['entry']) < self._MAX_RESULTS:
  1482. break
  1483. page_num += 1
  1484. videos = [v[1] for v in sorted(videos)]
  1485. url_results = [self.url_result(url, 'Youtube') for url in videos]
  1486. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  1487. class YoutubeChannelIE(InfoExtractor):
  1488. """Information Extractor for YouTube channels."""
  1489. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1490. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1491. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1492. _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'
  1493. IE_NAME = u'youtube:channel'
  1494. def report_download_page(self, channel_id, pagenum):
  1495. """Report attempt to download channel page with given number."""
  1496. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1497. def extract_videos_from_page(self, page):
  1498. ids_in_page = []
  1499. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1500. if mobj.group(1) not in ids_in_page:
  1501. ids_in_page.append(mobj.group(1))
  1502. return ids_in_page
  1503. def _real_extract(self, url):
  1504. # Extract channel id
  1505. mobj = re.match(self._VALID_URL, url)
  1506. if mobj is None:
  1507. self._downloader.report_error(u'invalid url: %s' % url)
  1508. return
  1509. # Download channel page
  1510. channel_id = mobj.group(1)
  1511. video_ids = []
  1512. pagenum = 1
  1513. self.report_download_page(channel_id, pagenum)
  1514. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1515. request = compat_urllib_request.Request(url)
  1516. try:
  1517. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1518. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1519. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1520. return
  1521. # Extract video identifiers
  1522. ids_in_page = self.extract_videos_from_page(page)
  1523. video_ids.extend(ids_in_page)
  1524. # Download any subsequent channel pages using the json-based channel_ajax query
  1525. if self._MORE_PAGES_INDICATOR in page:
  1526. while True:
  1527. pagenum = pagenum + 1
  1528. self.report_download_page(channel_id, pagenum)
  1529. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1530. request = compat_urllib_request.Request(url)
  1531. try:
  1532. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1533. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1534. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1535. return
  1536. page = json.loads(page)
  1537. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1538. video_ids.extend(ids_in_page)
  1539. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1540. break
  1541. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1542. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  1543. url_entries = [self.url_result(url, 'Youtube') for url in urls]
  1544. return [self.playlist_result(url_entries, channel_id)]
  1545. class YoutubeUserIE(InfoExtractor):
  1546. """Information Extractor for YouTube users."""
  1547. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1548. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1549. _GDATA_PAGE_SIZE = 50
  1550. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1551. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1552. IE_NAME = u'youtube:user'
  1553. def report_download_page(self, username, start_index):
  1554. """Report attempt to download user page."""
  1555. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1556. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1557. def _real_extract(self, url):
  1558. # Extract username
  1559. mobj = re.match(self._VALID_URL, url)
  1560. if mobj is None:
  1561. self._downloader.report_error(u'invalid url: %s' % url)
  1562. return
  1563. username = mobj.group(1)
  1564. # Download video ids using YouTube Data API. Result size per
  1565. # query is limited (currently to 50 videos) so we need to query
  1566. # page by page until there are no video ids - it means we got
  1567. # all of them.
  1568. video_ids = []
  1569. pagenum = 0
  1570. while True:
  1571. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1572. self.report_download_page(username, start_index)
  1573. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1574. try:
  1575. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1576. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1577. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1578. return
  1579. # Extract video identifiers
  1580. ids_in_page = []
  1581. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1582. if mobj.group(1) not in ids_in_page:
  1583. ids_in_page.append(mobj.group(1))
  1584. video_ids.extend(ids_in_page)
  1585. # A little optimization - if current page is not
  1586. # "full", ie. does not contain PAGE_SIZE video ids then
  1587. # we can assume that this page is the last one - there
  1588. # are no more ids on further pages - no need to query
  1589. # again.
  1590. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1591. break
  1592. pagenum += 1
  1593. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  1594. url_results = [self.url_result(url, 'Youtube') for url in urls]
  1595. return [self.playlist_result(url_results, playlist_title = username)]
  1596. class BlipTVUserIE(InfoExtractor):
  1597. """Information Extractor for blip.tv users."""
  1598. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1599. _PAGE_SIZE = 12
  1600. IE_NAME = u'blip.tv:user'
  1601. def report_download_page(self, username, pagenum):
  1602. """Report attempt to download user page."""
  1603. self.to_screen(u'user %s: Downloading video ids from page %d' %
  1604. (username, pagenum))
  1605. def _real_extract(self, url):
  1606. # Extract username
  1607. mobj = re.match(self._VALID_URL, url)
  1608. if mobj is None:
  1609. self._downloader.report_error(u'invalid url: %s' % url)
  1610. return
  1611. username = mobj.group(1)
  1612. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1613. request = compat_urllib_request.Request(url)
  1614. try:
  1615. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1616. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1617. page_base = page_base % mobj.group(1)
  1618. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1619. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1620. return
  1621. # Download video ids using BlipTV Ajax calls. Result size per
  1622. # query is limited (currently to 12 videos) so we need to query
  1623. # page by page until there are no video ids - it means we got
  1624. # all of them.
  1625. video_ids = []
  1626. pagenum = 1
  1627. while True:
  1628. self.report_download_page(username, pagenum)
  1629. url = page_base + "&page=" + str(pagenum)
  1630. request = compat_urllib_request.Request( url )
  1631. try:
  1632. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1633. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1634. self._downloader.report_error(u'unable to download webpage: %s' % str(err))
  1635. return
  1636. # Extract video identifiers
  1637. ids_in_page = []
  1638. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1639. if mobj.group(1) not in ids_in_page:
  1640. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1641. video_ids.extend(ids_in_page)
  1642. # A little optimization - if current page is not
  1643. # "full", ie. does not contain PAGE_SIZE video ids then
  1644. # we can assume that this page is the last one - there
  1645. # are no more ids on further pages - no need to query
  1646. # again.
  1647. if len(ids_in_page) < self._PAGE_SIZE:
  1648. break
  1649. pagenum += 1
  1650. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  1651. url_entries = [self.url_result(url, 'BlipTV') for url in urls]
  1652. return [self.playlist_result(url_entries, playlist_title = username)]
  1653. class DepositFilesIE(InfoExtractor):
  1654. """Information extractor for depositfiles.com"""
  1655. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1656. def _real_extract(self, url):
  1657. file_id = url.split('/')[-1]
  1658. # Rebuild url in english locale
  1659. url = 'http://depositfiles.com/en/files/' + file_id
  1660. # Retrieve file webpage with 'Free download' button pressed
  1661. free_download_indication = { 'gateway_result' : '1' }
  1662. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1663. try:
  1664. self.report_download_webpage(file_id)
  1665. webpage = compat_urllib_request.urlopen(request).read()
  1666. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1667. self._downloader.report_error(u'Unable to retrieve file webpage: %s' % compat_str(err))
  1668. return
  1669. # Search for the real file URL
  1670. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1671. if (mobj is None) or (mobj.group(1) is None):
  1672. # Try to figure out reason of the error.
  1673. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1674. if (mobj is not None) and (mobj.group(1) is not None):
  1675. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1676. self._downloader.report_error(u'%s' % restriction_message)
  1677. else:
  1678. self._downloader.report_error(u'unable to extract download URL from: %s' % url)
  1679. return
  1680. file_url = mobj.group(1)
  1681. file_extension = os.path.splitext(file_url)[1][1:]
  1682. # Search for file title
  1683. mobj = re.search(r'<b title="(.*?)">', webpage)
  1684. if mobj is None:
  1685. self._downloader.report_error(u'unable to extract title')
  1686. return
  1687. file_title = mobj.group(1).decode('utf-8')
  1688. return [{
  1689. 'id': file_id.decode('utf-8'),
  1690. 'url': file_url.decode('utf-8'),
  1691. 'uploader': None,
  1692. 'upload_date': None,
  1693. 'title': file_title,
  1694. 'ext': file_extension.decode('utf-8'),
  1695. }]
  1696. class FacebookIE(InfoExtractor):
  1697. """Information Extractor for Facebook"""
  1698. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1699. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1700. _NETRC_MACHINE = 'facebook'
  1701. IE_NAME = u'facebook'
  1702. def report_login(self):
  1703. """Report attempt to log in."""
  1704. self.to_screen(u'Logging in')
  1705. def _real_initialize(self):
  1706. if self._downloader is None:
  1707. return
  1708. useremail = None
  1709. password = None
  1710. downloader_params = self._downloader.params
  1711. # Attempt to use provided username and password or .netrc data
  1712. if downloader_params.get('username', None) is not None:
  1713. useremail = downloader_params['username']
  1714. password = downloader_params['password']
  1715. elif downloader_params.get('usenetrc', False):
  1716. try:
  1717. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1718. if info is not None:
  1719. useremail = info[0]
  1720. password = info[2]
  1721. else:
  1722. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1723. except (IOError, netrc.NetrcParseError) as err:
  1724. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  1725. return
  1726. if useremail is None:
  1727. return
  1728. # Log in
  1729. login_form = {
  1730. 'email': useremail,
  1731. 'pass': password,
  1732. 'login': 'Log+In'
  1733. }
  1734. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1735. try:
  1736. self.report_login()
  1737. login_results = compat_urllib_request.urlopen(request).read()
  1738. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1739. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1740. return
  1741. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1742. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  1743. return
  1744. def _real_extract(self, url):
  1745. mobj = re.match(self._VALID_URL, url)
  1746. if mobj is None:
  1747. self._downloader.report_error(u'invalid URL: %s' % url)
  1748. return
  1749. video_id = mobj.group('ID')
  1750. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  1751. webpage = self._download_webpage(url, video_id)
  1752. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  1753. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  1754. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  1755. if not m:
  1756. raise ExtractorError(u'Cannot parse data')
  1757. data = dict(json.loads(m.group(1)))
  1758. params_raw = compat_urllib_parse.unquote(data['params'])
  1759. params = json.loads(params_raw)
  1760. video_data = params['video_data'][0]
  1761. video_url = video_data.get('hd_src')
  1762. if not video_url:
  1763. video_url = video_data['sd_src']
  1764. if not video_url:
  1765. raise ExtractorError(u'Cannot find video URL')
  1766. video_duration = int(video_data['video_duration'])
  1767. thumbnail = video_data['thumbnail_src']
  1768. m = re.search('<h2 class="uiHeaderTitle">([^<]+)</h2>', webpage)
  1769. if not m:
  1770. raise ExtractorError(u'Cannot find title in webpage')
  1771. video_title = unescapeHTML(m.group(1))
  1772. info = {
  1773. 'id': video_id,
  1774. 'title': video_title,
  1775. 'url': video_url,
  1776. 'ext': 'mp4',
  1777. 'duration': video_duration,
  1778. 'thumbnail': thumbnail,
  1779. }
  1780. return [info]
  1781. class BlipTVIE(InfoExtractor):
  1782. """Information extractor for blip.tv"""
  1783. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1784. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1785. IE_NAME = u'blip.tv'
  1786. def report_direct_download(self, title):
  1787. """Report information extraction."""
  1788. self.to_screen(u'%s: Direct download detected' % title)
  1789. def _real_extract(self, url):
  1790. mobj = re.match(self._VALID_URL, url)
  1791. if mobj is None:
  1792. self._downloader.report_error(u'invalid URL: %s' % url)
  1793. return
  1794. urlp = compat_urllib_parse_urlparse(url)
  1795. if urlp.path.startswith('/play/'):
  1796. request = compat_urllib_request.Request(url)
  1797. response = compat_urllib_request.urlopen(request)
  1798. redirecturl = response.geturl()
  1799. rurlp = compat_urllib_parse_urlparse(redirecturl)
  1800. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  1801. url = 'http://blip.tv/a/a-' + file_id
  1802. return self._real_extract(url)
  1803. if '?' in url:
  1804. cchar = '&'
  1805. else:
  1806. cchar = '?'
  1807. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1808. request = compat_urllib_request.Request(json_url)
  1809. request.add_header('User-Agent', 'iTunes/10.6.1')
  1810. self.report_extraction(mobj.group(1))
  1811. info = None
  1812. try:
  1813. urlh = compat_urllib_request.urlopen(request)
  1814. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1815. basename = url.split('/')[-1]
  1816. title,ext = os.path.splitext(basename)
  1817. title = title.decode('UTF-8')
  1818. ext = ext.replace('.', '')
  1819. self.report_direct_download(title)
  1820. info = {
  1821. 'id': title,
  1822. 'url': url,
  1823. 'uploader': None,
  1824. 'upload_date': None,
  1825. 'title': title,
  1826. 'ext': ext,
  1827. 'urlhandle': urlh
  1828. }
  1829. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1830. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1831. if info is None: # Regular URL
  1832. try:
  1833. json_code_bytes = urlh.read()
  1834. json_code = json_code_bytes.decode('utf-8')
  1835. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1836. self._downloader.report_error(u'unable to read video info webpage: %s' % compat_str(err))
  1837. return
  1838. try:
  1839. json_data = json.loads(json_code)
  1840. if 'Post' in json_data:
  1841. data = json_data['Post']
  1842. else:
  1843. data = json_data
  1844. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1845. video_url = data['media']['url']
  1846. umobj = re.match(self._URL_EXT, video_url)
  1847. if umobj is None:
  1848. raise ValueError('Can not determine filename extension')
  1849. ext = umobj.group(1)
  1850. info = {
  1851. 'id': data['item_id'],
  1852. 'url': video_url,
  1853. 'uploader': data['display_name'],
  1854. 'upload_date': upload_date,
  1855. 'title': data['title'],
  1856. 'ext': ext,
  1857. 'format': data['media']['mimeType'],
  1858. 'thumbnail': data['thumbnailUrl'],
  1859. 'description': data['description'],
  1860. 'player_url': data['embedUrl'],
  1861. 'user_agent': 'iTunes/10.6.1',
  1862. }
  1863. except (ValueError,KeyError) as err:
  1864. self._downloader.report_error(u'unable to parse video information: %s' % repr(err))
  1865. return
  1866. return [info]
  1867. class MyVideoIE(InfoExtractor):
  1868. """Information Extractor for myvideo.de."""
  1869. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1870. IE_NAME = u'myvideo'
  1871. def _real_extract(self,url):
  1872. mobj = re.match(self._VALID_URL, url)
  1873. if mobj is None:
  1874. self._download.report_error(u'invalid URL: %s' % url)
  1875. return
  1876. video_id = mobj.group(1)
  1877. # Get video webpage
  1878. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  1879. webpage = self._download_webpage(webpage_url, video_id)
  1880. self.report_extraction(video_id)
  1881. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/.*?\.jpg\'',
  1882. webpage)
  1883. if mobj is None:
  1884. self._downloader.report_error(u'unable to extract media URL')
  1885. return
  1886. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1887. mobj = re.search('<title>([^<]+)</title>', webpage)
  1888. if mobj is None:
  1889. self._downloader.report_error(u'unable to extract title')
  1890. return
  1891. video_title = mobj.group(1)
  1892. return [{
  1893. 'id': video_id,
  1894. 'url': video_url,
  1895. 'uploader': None,
  1896. 'upload_date': None,
  1897. 'title': video_title,
  1898. 'ext': u'flv',
  1899. }]
  1900. class ComedyCentralIE(InfoExtractor):
  1901. """Information extractor for The Daily Show and Colbert Report """
  1902. # urls can be abbreviations like :thedailyshow or :colbert
  1903. # urls for episodes like:
  1904. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1905. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1906. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1907. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1908. |(https?://)?(www\.)?
  1909. (?P<showname>thedailyshow|colbertnation)\.com/
  1910. (full-episodes/(?P<episode>.*)|
  1911. (?P<clip>
  1912. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1913. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1914. $"""
  1915. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1916. _video_extensions = {
  1917. '3500': 'mp4',
  1918. '2200': 'mp4',
  1919. '1700': 'mp4',
  1920. '1200': 'mp4',
  1921. '750': 'mp4',
  1922. '400': 'mp4',
  1923. }
  1924. _video_dimensions = {
  1925. '3500': '1280x720',
  1926. '2200': '960x540',
  1927. '1700': '768x432',
  1928. '1200': '640x360',
  1929. '750': '512x288',
  1930. '400': '384x216',
  1931. }
  1932. @classmethod
  1933. def suitable(cls, url):
  1934. """Receives a URL and returns True if suitable for this IE."""
  1935. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1936. def report_config_download(self, episode_id, media_id):
  1937. self.to_screen(u'%s: Downloading configuration for %s' % (episode_id, media_id))
  1938. def report_index_download(self, episode_id):
  1939. self.to_screen(u'%s: Downloading show index' % episode_id)
  1940. def _print_formats(self, formats):
  1941. print('Available formats:')
  1942. for x in formats:
  1943. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1944. def _real_extract(self, url):
  1945. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1946. if mobj is None:
  1947. self._downloader.report_error(u'invalid URL: %s' % url)
  1948. return
  1949. if mobj.group('shortname'):
  1950. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1951. url = u'http://www.thedailyshow.com/full-episodes/'
  1952. else:
  1953. url = u'http://www.colbertnation.com/full-episodes/'
  1954. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1955. assert mobj is not None
  1956. if mobj.group('clip'):
  1957. if mobj.group('showname') == 'thedailyshow':
  1958. epTitle = mobj.group('tdstitle')
  1959. else:
  1960. epTitle = mobj.group('cntitle')
  1961. dlNewest = False
  1962. else:
  1963. dlNewest = not mobj.group('episode')
  1964. if dlNewest:
  1965. epTitle = mobj.group('showname')
  1966. else:
  1967. epTitle = mobj.group('episode')
  1968. req = compat_urllib_request.Request(url)
  1969. self.report_extraction(epTitle)
  1970. try:
  1971. htmlHandle = compat_urllib_request.urlopen(req)
  1972. html = htmlHandle.read()
  1973. webpage = html.decode('utf-8')
  1974. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1975. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1976. return
  1977. if dlNewest:
  1978. url = htmlHandle.geturl()
  1979. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1980. if mobj is None:
  1981. self._downloader.report_error(u'Invalid redirected URL: ' + url)
  1982. return
  1983. if mobj.group('episode') == '':
  1984. self._downloader.report_error(u'Redirected URL is still not specific: ' + url)
  1985. return
  1986. epTitle = mobj.group('episode')
  1987. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  1988. if len(mMovieParams) == 0:
  1989. # The Colbert Report embeds the information in a without
  1990. # a URL prefix; so extract the alternate reference
  1991. # and then add the URL prefix manually.
  1992. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  1993. if len(altMovieParams) == 0:
  1994. self._downloader.report_error(u'unable to find Flash URL in webpage ' + url)
  1995. return
  1996. else:
  1997. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  1998. uri = mMovieParams[0][1]
  1999. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2000. self.report_index_download(epTitle)
  2001. try:
  2002. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2003. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2004. self._downloader.report_error(u'unable to download episode index: ' + compat_str(err))
  2005. return
  2006. results = []
  2007. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2008. itemEls = idoc.findall('.//item')
  2009. for partNum,itemEl in enumerate(itemEls):
  2010. mediaId = itemEl.findall('./guid')[0].text
  2011. shortMediaId = mediaId.split(':')[-1]
  2012. showId = mediaId.split(':')[-2].replace('.com', '')
  2013. officialTitle = itemEl.findall('./title')[0].text
  2014. officialDate = itemEl.findall('./pubDate')[0].text
  2015. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2016. compat_urllib_parse.urlencode({'uri': mediaId}))
  2017. configReq = compat_urllib_request.Request(configUrl)
  2018. self.report_config_download(epTitle, shortMediaId)
  2019. try:
  2020. configXml = compat_urllib_request.urlopen(configReq).read()
  2021. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2022. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  2023. return
  2024. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2025. turls = []
  2026. for rendition in cdoc.findall('.//rendition'):
  2027. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2028. turls.append(finfo)
  2029. if len(turls) == 0:
  2030. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  2031. continue
  2032. if self._downloader.params.get('listformats', None):
  2033. self._print_formats([i[0] for i in turls])
  2034. return
  2035. # For now, just pick the highest bitrate
  2036. format,rtmp_video_url = turls[-1]
  2037. # Get the format arg from the arg stream
  2038. req_format = self._downloader.params.get('format', None)
  2039. # Select format if we can find one
  2040. for f,v in turls:
  2041. if f == req_format:
  2042. format, rtmp_video_url = f, v
  2043. break
  2044. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  2045. if not m:
  2046. raise ExtractorError(u'Cannot transform RTMP url')
  2047. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  2048. video_url = base + m.group('finalid')
  2049. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  2050. info = {
  2051. 'id': shortMediaId,
  2052. 'url': video_url,
  2053. 'uploader': showId,
  2054. 'upload_date': officialDate,
  2055. 'title': effTitle,
  2056. 'ext': 'mp4',
  2057. 'format': format,
  2058. 'thumbnail': None,
  2059. 'description': officialTitle,
  2060. }
  2061. results.append(info)
  2062. return results
  2063. class EscapistIE(InfoExtractor):
  2064. """Information extractor for The Escapist """
  2065. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2066. IE_NAME = u'escapist'
  2067. def report_config_download(self, showName):
  2068. self.to_screen(u'%s: Downloading configuration' % showName)
  2069. def _real_extract(self, url):
  2070. mobj = re.match(self._VALID_URL, url)
  2071. if mobj is None:
  2072. self._downloader.report_error(u'invalid URL: %s' % url)
  2073. return
  2074. showName = mobj.group('showname')
  2075. videoId = mobj.group('episode')
  2076. self.report_extraction(showName)
  2077. try:
  2078. webPage = compat_urllib_request.urlopen(url)
  2079. webPageBytes = webPage.read()
  2080. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2081. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2082. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2083. self._downloader.report_error(u'unable to download webpage: ' + compat_str(err))
  2084. return
  2085. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2086. description = unescapeHTML(descMatch.group(1))
  2087. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2088. imgUrl = unescapeHTML(imgMatch.group(1))
  2089. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2090. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2091. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2092. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2093. self.report_config_download(showName)
  2094. try:
  2095. configJSON = compat_urllib_request.urlopen(configUrl)
  2096. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2097. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2098. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2099. self._downloader.report_error(u'unable to download configuration: ' + compat_str(err))
  2100. return
  2101. # Technically, it's JavaScript, not JSON
  2102. configJSON = configJSON.replace("'", '"')
  2103. try:
  2104. config = json.loads(configJSON)
  2105. except (ValueError,) as err:
  2106. self._downloader.report_error(u'Invalid JSON in configuration file: ' + compat_str(err))
  2107. return
  2108. playlist = config['playlist']
  2109. videoUrl = playlist[1]['url']
  2110. info = {
  2111. 'id': videoId,
  2112. 'url': videoUrl,
  2113. 'uploader': showName,
  2114. 'upload_date': None,
  2115. 'title': showName,
  2116. 'ext': 'mp4',
  2117. 'thumbnail': imgUrl,
  2118. 'description': description,
  2119. 'player_url': playerUrl,
  2120. }
  2121. return [info]
  2122. class CollegeHumorIE(InfoExtractor):
  2123. """Information extractor for collegehumor.com"""
  2124. _WORKING = False
  2125. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2126. IE_NAME = u'collegehumor'
  2127. def report_manifest(self, video_id):
  2128. """Report information extraction."""
  2129. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  2130. def _real_extract(self, url):
  2131. mobj = re.match(self._VALID_URL, url)
  2132. if mobj is None:
  2133. self._downloader.report_error(u'invalid URL: %s' % url)
  2134. return
  2135. video_id = mobj.group('videoid')
  2136. info = {
  2137. 'id': video_id,
  2138. 'uploader': None,
  2139. 'upload_date': None,
  2140. }
  2141. self.report_extraction(video_id)
  2142. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2143. try:
  2144. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2145. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2146. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2147. return
  2148. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2149. try:
  2150. videoNode = mdoc.findall('./video')[0]
  2151. info['description'] = videoNode.findall('./description')[0].text
  2152. info['title'] = videoNode.findall('./caption')[0].text
  2153. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2154. manifest_url = videoNode.findall('./file')[0].text
  2155. except IndexError:
  2156. self._downloader.report_error(u'Invalid metadata XML file')
  2157. return
  2158. manifest_url += '?hdcore=2.10.3'
  2159. self.report_manifest(video_id)
  2160. try:
  2161. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2162. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2163. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2164. return
  2165. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2166. try:
  2167. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2168. node_id = media_node.attrib['url']
  2169. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2170. except IndexError as err:
  2171. self._downloader.report_error(u'Invalid manifest file')
  2172. return
  2173. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2174. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2175. info['url'] = url
  2176. info['ext'] = 'f4f'
  2177. return [info]
  2178. class XVideosIE(InfoExtractor):
  2179. """Information extractor for xvideos.com"""
  2180. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2181. IE_NAME = u'xvideos'
  2182. def _real_extract(self, url):
  2183. mobj = re.match(self._VALID_URL, url)
  2184. if mobj is None:
  2185. self._downloader.report_error(u'invalid URL: %s' % url)
  2186. return
  2187. video_id = mobj.group(1)
  2188. webpage = self._download_webpage(url, video_id)
  2189. self.report_extraction(video_id)
  2190. # Extract video URL
  2191. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2192. if mobj is None:
  2193. self._downloader.report_error(u'unable to extract video url')
  2194. return
  2195. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2196. # Extract title
  2197. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2198. if mobj is None:
  2199. self._downloader.report_error(u'unable to extract video title')
  2200. return
  2201. video_title = mobj.group(1)
  2202. # Extract video thumbnail
  2203. 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)
  2204. if mobj is None:
  2205. self._downloader.report_error(u'unable to extract video thumbnail')
  2206. return
  2207. video_thumbnail = mobj.group(0)
  2208. info = {
  2209. 'id': video_id,
  2210. 'url': video_url,
  2211. 'uploader': None,
  2212. 'upload_date': None,
  2213. 'title': video_title,
  2214. 'ext': 'flv',
  2215. 'thumbnail': video_thumbnail,
  2216. 'description': None,
  2217. }
  2218. return [info]
  2219. class SoundcloudIE(InfoExtractor):
  2220. """Information extractor for soundcloud.com
  2221. To access the media, the uid of the song and a stream token
  2222. must be extracted from the page source and the script must make
  2223. a request to media.soundcloud.com/crossdomain.xml. Then
  2224. the media can be grabbed by requesting from an url composed
  2225. of the stream token and uid
  2226. """
  2227. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2228. IE_NAME = u'soundcloud'
  2229. def report_resolve(self, video_id):
  2230. """Report information extraction."""
  2231. self.to_screen(u'%s: Resolving id' % video_id)
  2232. def _real_extract(self, url):
  2233. mobj = re.match(self._VALID_URL, url)
  2234. if mobj is None:
  2235. self._downloader.report_error(u'invalid URL: %s' % url)
  2236. return
  2237. # extract uploader (which is in the url)
  2238. uploader = mobj.group(1)
  2239. # extract simple title (uploader + slug of song title)
  2240. slug_title = mobj.group(2)
  2241. simple_title = uploader + u'-' + slug_title
  2242. self.report_resolve('%s/%s' % (uploader, slug_title))
  2243. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2244. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2245. request = compat_urllib_request.Request(resolv_url)
  2246. try:
  2247. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2248. info_json = info_json_bytes.decode('utf-8')
  2249. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2250. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err))
  2251. return
  2252. info = json.loads(info_json)
  2253. video_id = info['id']
  2254. self.report_extraction('%s/%s' % (uploader, slug_title))
  2255. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2256. request = compat_urllib_request.Request(streams_url)
  2257. try:
  2258. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2259. stream_json = stream_json_bytes.decode('utf-8')
  2260. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2261. self._downloader.report_error(u'unable to download stream definitions: %s' % compat_str(err))
  2262. return
  2263. streams = json.loads(stream_json)
  2264. mediaURL = streams['http_mp3_128_url']
  2265. return [{
  2266. 'id': info['id'],
  2267. 'url': mediaURL,
  2268. 'uploader': info['user']['username'],
  2269. 'upload_date': info['created_at'],
  2270. 'title': info['title'],
  2271. 'ext': u'mp3',
  2272. 'description': info['description'],
  2273. }]
  2274. class SoundcloudSetIE(InfoExtractor):
  2275. """Information extractor for soundcloud.com sets
  2276. To access the media, the uid of the song and a stream token
  2277. must be extracted from the page source and the script must make
  2278. a request to media.soundcloud.com/crossdomain.xml. Then
  2279. the media can be grabbed by requesting from an url composed
  2280. of the stream token and uid
  2281. """
  2282. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  2283. IE_NAME = u'soundcloud'
  2284. def report_resolve(self, video_id):
  2285. """Report information extraction."""
  2286. self.to_screen(u'%s: Resolving id' % video_id)
  2287. def _real_extract(self, url):
  2288. mobj = re.match(self._VALID_URL, url)
  2289. if mobj is None:
  2290. self._downloader.report_error(u'invalid URL: %s' % url)
  2291. return
  2292. # extract uploader (which is in the url)
  2293. uploader = mobj.group(1)
  2294. # extract simple title (uploader + slug of song title)
  2295. slug_title = mobj.group(2)
  2296. simple_title = uploader + u'-' + slug_title
  2297. self.report_resolve('%s/sets/%s' % (uploader, slug_title))
  2298. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  2299. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2300. request = compat_urllib_request.Request(resolv_url)
  2301. try:
  2302. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2303. info_json = info_json_bytes.decode('utf-8')
  2304. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2305. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err))
  2306. return
  2307. videos = []
  2308. info = json.loads(info_json)
  2309. if 'errors' in info:
  2310. for err in info['errors']:
  2311. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  2312. return
  2313. for track in info['tracks']:
  2314. video_id = track['id']
  2315. self.report_extraction('%s/sets/%s' % (uploader, slug_title))
  2316. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2317. request = compat_urllib_request.Request(streams_url)
  2318. try:
  2319. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2320. stream_json = stream_json_bytes.decode('utf-8')
  2321. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2322. self._downloader.report_error(u'unable to download stream definitions: %s' % compat_str(err))
  2323. return
  2324. streams = json.loads(stream_json)
  2325. mediaURL = streams['http_mp3_128_url']
  2326. videos.append({
  2327. 'id': video_id,
  2328. 'url': mediaURL,
  2329. 'uploader': track['user']['username'],
  2330. 'upload_date': track['created_at'],
  2331. 'title': track['title'],
  2332. 'ext': u'mp3',
  2333. 'description': track['description'],
  2334. })
  2335. return videos
  2336. class InfoQIE(InfoExtractor):
  2337. """Information extractor for infoq.com"""
  2338. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2339. def _real_extract(self, url):
  2340. mobj = re.match(self._VALID_URL, url)
  2341. if mobj is None:
  2342. self._downloader.report_error(u'invalid URL: %s' % url)
  2343. return
  2344. webpage = self._download_webpage(url, video_id=url)
  2345. self.report_extraction(url)
  2346. # Extract video URL
  2347. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  2348. if mobj is None:
  2349. self._downloader.report_error(u'unable to extract video url')
  2350. return
  2351. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  2352. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  2353. # Extract title
  2354. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2355. if mobj is None:
  2356. self._downloader.report_error(u'unable to extract video title')
  2357. return
  2358. video_title = mobj.group(1)
  2359. # Extract description
  2360. video_description = u'No description available.'
  2361. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2362. if mobj is not None:
  2363. video_description = mobj.group(1)
  2364. video_filename = video_url.split('/')[-1]
  2365. video_id, extension = video_filename.split('.')
  2366. info = {
  2367. 'id': video_id,
  2368. 'url': video_url,
  2369. 'uploader': None,
  2370. 'upload_date': None,
  2371. 'title': video_title,
  2372. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2373. 'thumbnail': None,
  2374. 'description': video_description,
  2375. }
  2376. return [info]
  2377. class MixcloudIE(InfoExtractor):
  2378. """Information extractor for www.mixcloud.com"""
  2379. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2380. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2381. IE_NAME = u'mixcloud'
  2382. def report_download_json(self, file_id):
  2383. """Report JSON download."""
  2384. self.to_screen(u'Downloading json')
  2385. def get_urls(self, jsonData, fmt, bitrate='best'):
  2386. """Get urls from 'audio_formats' section in json"""
  2387. file_url = None
  2388. try:
  2389. bitrate_list = jsonData[fmt]
  2390. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2391. bitrate = max(bitrate_list) # select highest
  2392. url_list = jsonData[fmt][bitrate]
  2393. except TypeError: # we have no bitrate info.
  2394. url_list = jsonData[fmt]
  2395. return url_list
  2396. def check_urls(self, url_list):
  2397. """Returns 1st active url from list"""
  2398. for url in url_list:
  2399. try:
  2400. compat_urllib_request.urlopen(url)
  2401. return url
  2402. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2403. url = None
  2404. return None
  2405. def _print_formats(self, formats):
  2406. print('Available formats:')
  2407. for fmt in formats.keys():
  2408. for b in formats[fmt]:
  2409. try:
  2410. ext = formats[fmt][b][0]
  2411. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2412. except TypeError: # we have no bitrate info
  2413. ext = formats[fmt][0]
  2414. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2415. break
  2416. def _real_extract(self, url):
  2417. mobj = re.match(self._VALID_URL, url)
  2418. if mobj is None:
  2419. self._downloader.report_error(u'invalid URL: %s' % url)
  2420. return
  2421. # extract uploader & filename from url
  2422. uploader = mobj.group(1).decode('utf-8')
  2423. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2424. # construct API request
  2425. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2426. # retrieve .json file with links to files
  2427. request = compat_urllib_request.Request(file_url)
  2428. try:
  2429. self.report_download_json(file_url)
  2430. jsonData = compat_urllib_request.urlopen(request).read()
  2431. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2432. self._downloader.report_error(u'Unable to retrieve file: %s' % compat_str(err))
  2433. return
  2434. # parse JSON
  2435. json_data = json.loads(jsonData)
  2436. player_url = json_data['player_swf_url']
  2437. formats = dict(json_data['audio_formats'])
  2438. req_format = self._downloader.params.get('format', None)
  2439. bitrate = None
  2440. if self._downloader.params.get('listformats', None):
  2441. self._print_formats(formats)
  2442. return
  2443. if req_format is None or req_format == 'best':
  2444. for format_param in formats.keys():
  2445. url_list = self.get_urls(formats, format_param)
  2446. # check urls
  2447. file_url = self.check_urls(url_list)
  2448. if file_url is not None:
  2449. break # got it!
  2450. else:
  2451. if req_format not in formats:
  2452. self._downloader.report_error(u'format is not available')
  2453. return
  2454. url_list = self.get_urls(formats, req_format)
  2455. file_url = self.check_urls(url_list)
  2456. format_param = req_format
  2457. return [{
  2458. 'id': file_id.decode('utf-8'),
  2459. 'url': file_url.decode('utf-8'),
  2460. 'uploader': uploader.decode('utf-8'),
  2461. 'upload_date': None,
  2462. 'title': json_data['name'],
  2463. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2464. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2465. 'thumbnail': json_data['thumbnail_url'],
  2466. 'description': json_data['description'],
  2467. 'player_url': player_url.decode('utf-8'),
  2468. }]
  2469. class StanfordOpenClassroomIE(InfoExtractor):
  2470. """Information extractor for Stanford's Open ClassRoom"""
  2471. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2472. IE_NAME = u'stanfordoc'
  2473. def _real_extract(self, url):
  2474. mobj = re.match(self._VALID_URL, url)
  2475. if mobj is None:
  2476. raise ExtractorError(u'Invalid URL: %s' % url)
  2477. if mobj.group('course') and mobj.group('video'): # A specific video
  2478. course = mobj.group('course')
  2479. video = mobj.group('video')
  2480. info = {
  2481. 'id': course + '_' + video,
  2482. 'uploader': None,
  2483. 'upload_date': None,
  2484. }
  2485. self.report_extraction(info['id'])
  2486. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2487. xmlUrl = baseUrl + video + '.xml'
  2488. try:
  2489. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2490. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2491. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2492. return
  2493. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2494. try:
  2495. info['title'] = mdoc.findall('./title')[0].text
  2496. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2497. except IndexError:
  2498. self._downloader.report_error(u'Invalid metadata XML file')
  2499. return
  2500. info['ext'] = info['url'].rpartition('.')[2]
  2501. return [info]
  2502. elif mobj.group('course'): # A course page
  2503. course = mobj.group('course')
  2504. info = {
  2505. 'id': course,
  2506. 'type': 'playlist',
  2507. 'uploader': None,
  2508. 'upload_date': None,
  2509. }
  2510. coursepage = self._download_webpage(url, info['id'],
  2511. note='Downloading course info page',
  2512. errnote='Unable to download course info page')
  2513. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2514. if m:
  2515. info['title'] = unescapeHTML(m.group(1))
  2516. else:
  2517. info['title'] = info['id']
  2518. m = re.search('<description>([^<]+)</description>', coursepage)
  2519. if m:
  2520. info['description'] = unescapeHTML(m.group(1))
  2521. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2522. info['list'] = [
  2523. {
  2524. 'type': 'reference',
  2525. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2526. }
  2527. for vpage in links]
  2528. results = []
  2529. for entry in info['list']:
  2530. assert entry['type'] == 'reference'
  2531. results += self.extract(entry['url'])
  2532. return results
  2533. else: # Root page
  2534. info = {
  2535. 'id': 'Stanford OpenClassroom',
  2536. 'type': 'playlist',
  2537. 'uploader': None,
  2538. 'upload_date': None,
  2539. }
  2540. self.report_download_webpage(info['id'])
  2541. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2542. try:
  2543. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2544. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2545. self._downloader.report_error(u'unable to download course info page: ' + compat_str(err))
  2546. return
  2547. info['title'] = info['id']
  2548. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2549. info['list'] = [
  2550. {
  2551. 'type': 'reference',
  2552. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2553. }
  2554. for cpage in links]
  2555. results = []
  2556. for entry in info['list']:
  2557. assert entry['type'] == 'reference'
  2558. results += self.extract(entry['url'])
  2559. return results
  2560. class MTVIE(InfoExtractor):
  2561. """Information extractor for MTV.com"""
  2562. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2563. IE_NAME = u'mtv'
  2564. def _real_extract(self, url):
  2565. mobj = re.match(self._VALID_URL, url)
  2566. if mobj is None:
  2567. self._downloader.report_error(u'invalid URL: %s' % url)
  2568. return
  2569. if not mobj.group('proto'):
  2570. url = 'http://' + url
  2571. video_id = mobj.group('videoid')
  2572. webpage = self._download_webpage(url, video_id)
  2573. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2574. if mobj is None:
  2575. self._downloader.report_error(u'unable to extract song name')
  2576. return
  2577. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2578. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2579. if mobj is None:
  2580. self._downloader.report_error(u'unable to extract performer')
  2581. return
  2582. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2583. video_title = performer + ' - ' + song_name
  2584. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2585. if mobj is None:
  2586. self._downloader.report_error(u'unable to mtvn_uri')
  2587. return
  2588. mtvn_uri = mobj.group(1)
  2589. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2590. if mobj is None:
  2591. self._downloader.report_error(u'unable to extract content id')
  2592. return
  2593. content_id = mobj.group(1)
  2594. 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
  2595. self.report_extraction(video_id)
  2596. request = compat_urllib_request.Request(videogen_url)
  2597. try:
  2598. metadataXml = compat_urllib_request.urlopen(request).read()
  2599. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2600. self._downloader.report_error(u'unable to download video metadata: %s' % compat_str(err))
  2601. return
  2602. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2603. renditions = mdoc.findall('.//rendition')
  2604. # For now, always pick the highest quality.
  2605. rendition = renditions[-1]
  2606. try:
  2607. _,_,ext = rendition.attrib['type'].partition('/')
  2608. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2609. video_url = rendition.find('./src').text
  2610. except KeyError:
  2611. self._downloader.report_error('Invalid rendition field.')
  2612. return
  2613. info = {
  2614. 'id': video_id,
  2615. 'url': video_url,
  2616. 'uploader': performer,
  2617. 'upload_date': None,
  2618. 'title': video_title,
  2619. 'ext': ext,
  2620. 'format': format,
  2621. }
  2622. return [info]
  2623. class YoukuIE(InfoExtractor):
  2624. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2625. def _gen_sid(self):
  2626. nowTime = int(time.time() * 1000)
  2627. random1 = random.randint(1000,1998)
  2628. random2 = random.randint(1000,9999)
  2629. return "%d%d%d" %(nowTime,random1,random2)
  2630. def _get_file_ID_mix_string(self, seed):
  2631. mixed = []
  2632. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2633. seed = float(seed)
  2634. for i in range(len(source)):
  2635. seed = (seed * 211 + 30031 ) % 65536
  2636. index = math.floor(seed / 65536 * len(source) )
  2637. mixed.append(source[int(index)])
  2638. source.remove(source[int(index)])
  2639. #return ''.join(mixed)
  2640. return mixed
  2641. def _get_file_id(self, fileId, seed):
  2642. mixed = self._get_file_ID_mix_string(seed)
  2643. ids = fileId.split('*')
  2644. realId = []
  2645. for ch in ids:
  2646. if ch:
  2647. realId.append(mixed[int(ch)])
  2648. return ''.join(realId)
  2649. def _real_extract(self, url):
  2650. mobj = re.match(self._VALID_URL, url)
  2651. if mobj is None:
  2652. self._downloader.report_error(u'invalid URL: %s' % url)
  2653. return
  2654. video_id = mobj.group('ID')
  2655. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2656. request = compat_urllib_request.Request(info_url, None, std_headers)
  2657. try:
  2658. self.report_download_webpage(video_id)
  2659. jsondata = compat_urllib_request.urlopen(request).read()
  2660. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2661. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  2662. return
  2663. self.report_extraction(video_id)
  2664. try:
  2665. jsonstr = jsondata.decode('utf-8')
  2666. config = json.loads(jsonstr)
  2667. video_title = config['data'][0]['title']
  2668. seed = config['data'][0]['seed']
  2669. format = self._downloader.params.get('format', None)
  2670. supported_format = list(config['data'][0]['streamfileids'].keys())
  2671. if format is None or format == 'best':
  2672. if 'hd2' in supported_format:
  2673. format = 'hd2'
  2674. else:
  2675. format = 'flv'
  2676. ext = u'flv'
  2677. elif format == 'worst':
  2678. format = 'mp4'
  2679. ext = u'mp4'
  2680. else:
  2681. format = 'flv'
  2682. ext = u'flv'
  2683. fileid = config['data'][0]['streamfileids'][format]
  2684. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2685. except (UnicodeDecodeError, ValueError, KeyError):
  2686. self._downloader.report_error(u'unable to extract info section')
  2687. return
  2688. files_info=[]
  2689. sid = self._gen_sid()
  2690. fileid = self._get_file_id(fileid, seed)
  2691. #column 8,9 of fileid represent the segment number
  2692. #fileid[7:9] should be changed
  2693. for index, key in enumerate(keys):
  2694. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2695. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2696. info = {
  2697. 'id': '%s_part%02d' % (video_id, index),
  2698. 'url': download_url,
  2699. 'uploader': None,
  2700. 'upload_date': None,
  2701. 'title': video_title,
  2702. 'ext': ext,
  2703. }
  2704. files_info.append(info)
  2705. return files_info
  2706. class XNXXIE(InfoExtractor):
  2707. """Information extractor for xnxx.com"""
  2708. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  2709. IE_NAME = u'xnxx'
  2710. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2711. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2712. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2713. def _real_extract(self, url):
  2714. mobj = re.match(self._VALID_URL, url)
  2715. if mobj is None:
  2716. self._downloader.report_error(u'invalid URL: %s' % url)
  2717. return
  2718. video_id = mobj.group(1)
  2719. self.report_download_webpage(video_id)
  2720. # Get webpage content
  2721. try:
  2722. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2723. webpage = webpage_bytes.decode('utf-8')
  2724. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2725. self._downloader.report_error(u'unable to download video webpage: %s' % err)
  2726. return
  2727. result = re.search(self.VIDEO_URL_RE, webpage)
  2728. if result is None:
  2729. self._downloader.report_error(u'unable to extract video url')
  2730. return
  2731. video_url = compat_urllib_parse.unquote(result.group(1))
  2732. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2733. if result is None:
  2734. self._downloader.report_error(u'unable to extract video title')
  2735. return
  2736. video_title = result.group(1)
  2737. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2738. if result is None:
  2739. self._downloader.report_error(u'unable to extract video thumbnail')
  2740. return
  2741. video_thumbnail = result.group(1)
  2742. return [{
  2743. 'id': video_id,
  2744. 'url': video_url,
  2745. 'uploader': None,
  2746. 'upload_date': None,
  2747. 'title': video_title,
  2748. 'ext': 'flv',
  2749. 'thumbnail': video_thumbnail,
  2750. 'description': None,
  2751. }]
  2752. class GooglePlusIE(InfoExtractor):
  2753. """Information extractor for plus.google.com."""
  2754. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2755. IE_NAME = u'plus.google'
  2756. def report_extract_entry(self, url):
  2757. """Report downloading extry"""
  2758. self.to_screen(u'Downloading entry: %s' % url)
  2759. def report_date(self, upload_date):
  2760. """Report downloading extry"""
  2761. self.to_screen(u'Entry date: %s' % upload_date)
  2762. def report_uploader(self, uploader):
  2763. """Report downloading extry"""
  2764. self.to_screen(u'Uploader: %s' % uploader)
  2765. def report_title(self, video_title):
  2766. """Report downloading extry"""
  2767. self.to_screen(u'Title: %s' % video_title)
  2768. def report_extract_vid_page(self, video_page):
  2769. """Report information extraction."""
  2770. self.to_screen(u'Extracting video page: %s' % video_page)
  2771. def _real_extract(self, url):
  2772. # Extract id from URL
  2773. mobj = re.match(self._VALID_URL, url)
  2774. if mobj is None:
  2775. self._downloader.report_error(u'Invalid URL: %s' % url)
  2776. return
  2777. post_url = mobj.group(0)
  2778. video_id = mobj.group(1)
  2779. video_extension = 'flv'
  2780. # Step 1, Retrieve post webpage to extract further information
  2781. self.report_extract_entry(post_url)
  2782. request = compat_urllib_request.Request(post_url)
  2783. try:
  2784. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2785. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2786. self._downloader.report_error(u'Unable to retrieve entry webpage: %s' % compat_str(err))
  2787. return
  2788. # Extract update date
  2789. upload_date = None
  2790. pattern = 'title="Timestamp">(.*?)</a>'
  2791. mobj = re.search(pattern, webpage)
  2792. if mobj:
  2793. upload_date = mobj.group(1)
  2794. # Convert timestring to a format suitable for filename
  2795. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2796. upload_date = upload_date.strftime('%Y%m%d')
  2797. self.report_date(upload_date)
  2798. # Extract uploader
  2799. uploader = None
  2800. pattern = r'rel\="author".*?>(.*?)</a>'
  2801. mobj = re.search(pattern, webpage)
  2802. if mobj:
  2803. uploader = mobj.group(1)
  2804. self.report_uploader(uploader)
  2805. # Extract title
  2806. # Get the first line for title
  2807. video_title = u'NA'
  2808. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2809. mobj = re.search(pattern, webpage)
  2810. if mobj:
  2811. video_title = mobj.group(1)
  2812. self.report_title(video_title)
  2813. # Step 2, Stimulate clicking the image box to launch video
  2814. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2815. mobj = re.search(pattern, webpage)
  2816. if mobj is None:
  2817. self._downloader.report_error(u'unable to extract video page URL')
  2818. video_page = mobj.group(1)
  2819. request = compat_urllib_request.Request(video_page)
  2820. try:
  2821. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2822. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2823. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  2824. return
  2825. self.report_extract_vid_page(video_page)
  2826. # Extract video links on video page
  2827. """Extract video links of all sizes"""
  2828. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2829. mobj = re.findall(pattern, webpage)
  2830. if len(mobj) == 0:
  2831. self._downloader.report_error(u'unable to extract video links')
  2832. # Sort in resolution
  2833. links = sorted(mobj)
  2834. # Choose the lowest of the sort, i.e. highest resolution
  2835. video_url = links[-1]
  2836. # Only get the url. The resolution part in the tuple has no use anymore
  2837. video_url = video_url[-1]
  2838. # Treat escaped \u0026 style hex
  2839. try:
  2840. video_url = video_url.decode("unicode_escape")
  2841. except AttributeError: # Python 3
  2842. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2843. return [{
  2844. 'id': video_id,
  2845. 'url': video_url,
  2846. 'uploader': uploader,
  2847. 'upload_date': upload_date,
  2848. 'title': video_title,
  2849. 'ext': video_extension,
  2850. }]
  2851. class NBAIE(InfoExtractor):
  2852. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2853. IE_NAME = u'nba'
  2854. def _real_extract(self, url):
  2855. mobj = re.match(self._VALID_URL, url)
  2856. if mobj is None:
  2857. self._downloader.report_error(u'invalid URL: %s' % url)
  2858. return
  2859. video_id = mobj.group(1)
  2860. if video_id.endswith('/index.html'):
  2861. video_id = video_id[:-len('/index.html')]
  2862. webpage = self._download_webpage(url, video_id)
  2863. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2864. def _findProp(rexp, default=None):
  2865. m = re.search(rexp, webpage)
  2866. if m:
  2867. return unescapeHTML(m.group(1))
  2868. else:
  2869. return default
  2870. shortened_video_id = video_id.rpartition('/')[2]
  2871. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2872. info = {
  2873. 'id': shortened_video_id,
  2874. 'url': video_url,
  2875. 'ext': 'mp4',
  2876. 'title': title,
  2877. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2878. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2879. }
  2880. return [info]
  2881. class JustinTVIE(InfoExtractor):
  2882. """Information extractor for justin.tv and twitch.tv"""
  2883. # TODO: One broadcast may be split into multiple videos. The key
  2884. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2885. # starts at 1 and increases. Can we treat all parts as one video?
  2886. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2887. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  2888. _JUSTIN_PAGE_LIMIT = 100
  2889. IE_NAME = u'justin.tv'
  2890. def report_download_page(self, channel, offset):
  2891. """Report attempt to download a single page of videos."""
  2892. self.to_screen(u'%s: Downloading video information from %d to %d' %
  2893. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  2894. # Return count of items, list of *valid* items
  2895. def _parse_page(self, url):
  2896. try:
  2897. urlh = compat_urllib_request.urlopen(url)
  2898. webpage_bytes = urlh.read()
  2899. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2900. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2901. self._downloader.report_error(u'unable to download video info JSON: %s' % compat_str(err))
  2902. return
  2903. response = json.loads(webpage)
  2904. if type(response) != list:
  2905. error_text = response.get('error', 'unknown error')
  2906. self._downloader.report_error(u'Justin.tv API: %s' % error_text)
  2907. return
  2908. info = []
  2909. for clip in response:
  2910. video_url = clip['video_file_url']
  2911. if video_url:
  2912. video_extension = os.path.splitext(video_url)[1][1:]
  2913. video_date = re.sub('-', '', clip['start_time'][:10])
  2914. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  2915. video_id = clip['id']
  2916. video_title = clip.get('title', video_id)
  2917. info.append({
  2918. 'id': video_id,
  2919. 'url': video_url,
  2920. 'title': video_title,
  2921. 'uploader': clip.get('channel_name', video_uploader_id),
  2922. 'uploader_id': video_uploader_id,
  2923. 'upload_date': video_date,
  2924. 'ext': video_extension,
  2925. })
  2926. return (len(response), info)
  2927. def _real_extract(self, url):
  2928. mobj = re.match(self._VALID_URL, url)
  2929. if mobj is None:
  2930. self._downloader.report_error(u'invalid URL: %s' % url)
  2931. return
  2932. api = 'http://api.justin.tv'
  2933. video_id = mobj.group(mobj.lastindex)
  2934. paged = False
  2935. if mobj.lastindex == 1:
  2936. paged = True
  2937. api += '/channel/archives/%s.json'
  2938. else:
  2939. api += '/broadcast/by_archive/%s.json'
  2940. api = api % (video_id,)
  2941. self.report_extraction(video_id)
  2942. info = []
  2943. offset = 0
  2944. limit = self._JUSTIN_PAGE_LIMIT
  2945. while True:
  2946. if paged:
  2947. self.report_download_page(video_id, offset)
  2948. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  2949. page_count, page_info = self._parse_page(page_url)
  2950. info.extend(page_info)
  2951. if not paged or page_count != limit:
  2952. break
  2953. offset += limit
  2954. return info
  2955. class FunnyOrDieIE(InfoExtractor):
  2956. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  2957. def _real_extract(self, url):
  2958. mobj = re.match(self._VALID_URL, url)
  2959. if mobj is None:
  2960. self._downloader.report_error(u'invalid URL: %s' % url)
  2961. return
  2962. video_id = mobj.group('id')
  2963. webpage = self._download_webpage(url, video_id)
  2964. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  2965. if not m:
  2966. self._downloader.report_error(u'unable to find video information')
  2967. video_url = unescapeHTML(m.group('url'))
  2968. m = re.search(r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>", webpage, flags=re.DOTALL)
  2969. if not m:
  2970. m = re.search(r'<title>(?P<title>[^<]+?)</title>', webpage)
  2971. if not m:
  2972. self._downloader.report_error(u'Cannot find video title')
  2973. title = clean_html(m.group('title'))
  2974. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  2975. if m:
  2976. desc = unescapeHTML(m.group('desc'))
  2977. else:
  2978. desc = None
  2979. info = {
  2980. 'id': video_id,
  2981. 'url': video_url,
  2982. 'ext': 'mp4',
  2983. 'title': title,
  2984. 'description': desc,
  2985. }
  2986. return [info]
  2987. class SteamIE(InfoExtractor):
  2988. _VALID_URL = r"""http://store.steampowered.com/
  2989. (agecheck/)?
  2990. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  2991. (?P<gameID>\d+)/?
  2992. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  2993. """
  2994. @classmethod
  2995. def suitable(cls, url):
  2996. """Receives a URL and returns True if suitable for this IE."""
  2997. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  2998. def _real_extract(self, url):
  2999. m = re.match(self._VALID_URL, url, re.VERBOSE)
  3000. gameID = m.group('gameID')
  3001. videourl = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970' % gameID
  3002. self.report_age_confirmation()
  3003. webpage = self._download_webpage(videourl, gameID)
  3004. game_title = re.search(r'<h2 class="pageheader">(?P<game_title>.*?)</h2>', webpage).group('game_title')
  3005. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  3006. mweb = re.finditer(urlRE, webpage)
  3007. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  3008. titles = re.finditer(namesRE, webpage)
  3009. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  3010. thumbs = re.finditer(thumbsRE, webpage)
  3011. videos = []
  3012. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  3013. video_id = vid.group('videoID')
  3014. title = vtitle.group('videoName')
  3015. video_url = vid.group('videoURL')
  3016. video_thumb = thumb.group('thumbnail')
  3017. if not video_url:
  3018. self._downloader.report_error(u'Cannot find video url for %s' % video_id)
  3019. info = {
  3020. 'id':video_id,
  3021. 'url':video_url,
  3022. 'ext': 'flv',
  3023. 'title': unescapeHTML(title),
  3024. 'thumbnail': video_thumb
  3025. }
  3026. videos.append(info)
  3027. return [self.playlist_result(videos, gameID, game_title)]
  3028. class UstreamIE(InfoExtractor):
  3029. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  3030. IE_NAME = u'ustream'
  3031. def _real_extract(self, url):
  3032. m = re.match(self._VALID_URL, url)
  3033. video_id = m.group('videoID')
  3034. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  3035. webpage = self._download_webpage(url, video_id)
  3036. m = re.search(r'data-title="(?P<title>.+)"',webpage)
  3037. title = m.group('title')
  3038. m = re.search(r'<a class="state" data-content-type="channel" data-content-id="(?P<uploader>\d+)"',webpage)
  3039. uploader = m.group('uploader')
  3040. info = {
  3041. 'id':video_id,
  3042. 'url':video_url,
  3043. 'ext': 'flv',
  3044. 'title': title,
  3045. 'uploader': uploader
  3046. }
  3047. return [info]
  3048. class WorldStarHipHopIE(InfoExtractor):
  3049. _VALID_URL = r'http://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  3050. IE_NAME = u'WorldStarHipHop'
  3051. def _real_extract(self, url):
  3052. _src_url = r"""(http://hw-videos.*(?:mp4|flv))"""
  3053. webpage_src = compat_urllib_request.urlopen(url).read()
  3054. webpage_src = webpage_src.decode('utf-8')
  3055. mobj = re.search(_src_url, webpage_src)
  3056. m = re.match(self._VALID_URL, url)
  3057. video_id = m.group('id')
  3058. if mobj is not None:
  3059. video_url = mobj.group()
  3060. if 'mp4' in video_url:
  3061. ext = 'mp4'
  3062. else:
  3063. ext = 'flv'
  3064. else:
  3065. self._downloader.report_error(u'Cannot find video url for %s' % video_id)
  3066. return
  3067. _title = r"""<title>(.*)</title>"""
  3068. mobj = re.search(_title, webpage_src)
  3069. if mobj is not None:
  3070. title = mobj.group(1)
  3071. else:
  3072. title = 'World Start Hip Hop - %s' % time.ctime()
  3073. _thumbnail = r"""rel="image_src" href="(.*)" />"""
  3074. mobj = re.search(_thumbnail, webpage_src)
  3075. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  3076. if mobj is not None:
  3077. thumbnail = mobj.group(1)
  3078. else:
  3079. _title = r"""candytitles.*>(.*)</span>"""
  3080. mobj = re.search(_title, webpage_src)
  3081. if mobj is not None:
  3082. title = mobj.group(1)
  3083. thumbnail = None
  3084. results = [{
  3085. 'id': video_id,
  3086. 'url' : video_url,
  3087. 'title' : title,
  3088. 'thumbnail' : thumbnail,
  3089. 'ext' : ext,
  3090. }]
  3091. return results
  3092. class RBMARadioIE(InfoExtractor):
  3093. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  3094. def _real_extract(self, url):
  3095. m = re.match(self._VALID_URL, url)
  3096. video_id = m.group('videoID')
  3097. webpage = self._download_webpage(url, video_id)
  3098. m = re.search(r'<script>window.gon = {.*?};gon\.show=(.+?);</script>', webpage)
  3099. if not m:
  3100. raise ExtractorError(u'Cannot find metadata')
  3101. json_data = m.group(1)
  3102. try:
  3103. data = json.loads(json_data)
  3104. except ValueError as e:
  3105. raise ExtractorError(u'Invalid JSON: ' + str(e))
  3106. video_url = data['akamai_url'] + '&cbr=256'
  3107. url_parts = compat_urllib_parse_urlparse(video_url)
  3108. video_ext = url_parts.path.rpartition('.')[2]
  3109. info = {
  3110. 'id': video_id,
  3111. 'url': video_url,
  3112. 'ext': video_ext,
  3113. 'title': data['title'],
  3114. 'description': data.get('teaser_text'),
  3115. 'location': data.get('country_of_origin'),
  3116. 'uploader': data.get('host', {}).get('name'),
  3117. 'uploader_id': data.get('host', {}).get('slug'),
  3118. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  3119. 'duration': data.get('duration'),
  3120. }
  3121. return [info]
  3122. class YouPornIE(InfoExtractor):
  3123. """Information extractor for youporn.com."""
  3124. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  3125. def _print_formats(self, formats):
  3126. """Print all available formats"""
  3127. print(u'Available formats:')
  3128. print(u'ext\t\tformat')
  3129. print(u'---------------------------------')
  3130. for format in formats:
  3131. print(u'%s\t\t%s' % (format['ext'], format['format']))
  3132. def _specific(self, req_format, formats):
  3133. for x in formats:
  3134. if(x["format"]==req_format):
  3135. return x
  3136. return None
  3137. def _real_extract(self, url):
  3138. mobj = re.match(self._VALID_URL, url)
  3139. if mobj is None:
  3140. self._downloader.report_error(u'invalid URL: %s' % url)
  3141. return
  3142. video_id = mobj.group('videoid')
  3143. req = compat_urllib_request.Request(url)
  3144. req.add_header('Cookie', 'age_verified=1')
  3145. webpage = self._download_webpage(req, video_id)
  3146. # Get the video title
  3147. result = re.search(r'<h1.*?>(?P<title>.*)</h1>', webpage)
  3148. if result is None:
  3149. raise ExtractorError(u'Unable to extract video title')
  3150. video_title = result.group('title').strip()
  3151. # Get the video date
  3152. result = re.search(r'Date:</label>(?P<date>.*) </li>', webpage)
  3153. if result is None:
  3154. self._downloader.report_warning(u'unable to extract video date')
  3155. upload_date = None
  3156. else:
  3157. upload_date = result.group('date').strip()
  3158. # Get the video uploader
  3159. result = re.search(r'Submitted:</label>(?P<uploader>.*)</li>', webpage)
  3160. if result is None:
  3161. self._downloader.report_warning(u'unable to extract uploader')
  3162. video_uploader = None
  3163. else:
  3164. video_uploader = result.group('uploader').strip()
  3165. video_uploader = clean_html( video_uploader )
  3166. # Get all of the formats available
  3167. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  3168. result = re.search(DOWNLOAD_LIST_RE, webpage)
  3169. if result is None:
  3170. raise ExtractorError(u'Unable to extract download list')
  3171. download_list_html = result.group('download_list').strip()
  3172. # Get all of the links from the page
  3173. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  3174. links = re.findall(LINK_RE, download_list_html)
  3175. if(len(links) == 0):
  3176. raise ExtractorError(u'ERROR: no known formats available for video')
  3177. self.to_screen(u'Links found: %d' % len(links))
  3178. formats = []
  3179. for link in links:
  3180. # A link looks like this:
  3181. # 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
  3182. # A path looks like this:
  3183. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  3184. video_url = unescapeHTML( link )
  3185. path = compat_urllib_parse_urlparse( video_url ).path
  3186. extension = os.path.splitext( path )[1][1:]
  3187. format = path.split('/')[4].split('_')[:2]
  3188. size = format[0]
  3189. bitrate = format[1]
  3190. format = "-".join( format )
  3191. title = u'%s-%s-%s' % (video_title, size, bitrate)
  3192. formats.append({
  3193. 'id': video_id,
  3194. 'url': video_url,
  3195. 'uploader': video_uploader,
  3196. 'upload_date': upload_date,
  3197. 'title': title,
  3198. 'ext': extension,
  3199. 'format': format,
  3200. 'thumbnail': None,
  3201. 'description': None,
  3202. 'player_url': None
  3203. })
  3204. if self._downloader.params.get('listformats', None):
  3205. self._print_formats(formats)
  3206. return
  3207. req_format = self._downloader.params.get('format', None)
  3208. self.to_screen(u'Format: %s' % req_format)
  3209. if req_format is None or req_format == 'best':
  3210. return [formats[0]]
  3211. elif req_format == 'worst':
  3212. return [formats[-1]]
  3213. elif req_format in ('-1', 'all'):
  3214. return formats
  3215. else:
  3216. format = self._specific( req_format, formats )
  3217. if result is None:
  3218. self._downloader.report_error(u'requested format not available')
  3219. return
  3220. return [format]
  3221. class PornotubeIE(InfoExtractor):
  3222. """Information extractor for pornotube.com."""
  3223. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  3224. def _real_extract(self, url):
  3225. mobj = re.match(self._VALID_URL, url)
  3226. if mobj is None:
  3227. self._downloader.report_error(u'invalid URL: %s' % url)
  3228. return
  3229. video_id = mobj.group('videoid')
  3230. video_title = mobj.group('title')
  3231. # Get webpage content
  3232. webpage = self._download_webpage(url, video_id)
  3233. # Get the video URL
  3234. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  3235. result = re.search(VIDEO_URL_RE, webpage)
  3236. if result is None:
  3237. self._downloader.report_error(u'unable to extract video url')
  3238. return
  3239. video_url = compat_urllib_parse.unquote(result.group('url'))
  3240. #Get the uploaded date
  3241. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  3242. result = re.search(VIDEO_UPLOADED_RE, webpage)
  3243. if result is None:
  3244. self._downloader.report_error(u'unable to extract video title')
  3245. return
  3246. upload_date = result.group('date')
  3247. info = {'id': video_id,
  3248. 'url': video_url,
  3249. 'uploader': None,
  3250. 'upload_date': upload_date,
  3251. 'title': video_title,
  3252. 'ext': 'flv',
  3253. 'format': 'flv'}
  3254. return [info]
  3255. class YouJizzIE(InfoExtractor):
  3256. """Information extractor for youjizz.com."""
  3257. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  3258. def _real_extract(self, url):
  3259. mobj = re.match(self._VALID_URL, url)
  3260. if mobj is None:
  3261. self._downloader.report_error(u'invalid URL: %s' % url)
  3262. return
  3263. video_id = mobj.group('videoid')
  3264. # Get webpage content
  3265. webpage = self._download_webpage(url, video_id)
  3266. # Get the video title
  3267. result = re.search(r'<title>(?P<title>.*)</title>', webpage)
  3268. if result is None:
  3269. raise ExtractorError(u'ERROR: unable to extract video title')
  3270. video_title = result.group('title').strip()
  3271. # Get the embed page
  3272. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  3273. if result is None:
  3274. raise ExtractorError(u'ERROR: unable to extract embed page')
  3275. embed_page_url = result.group(0).strip()
  3276. video_id = result.group('videoid')
  3277. webpage = self._download_webpage(embed_page_url, video_id)
  3278. # Get the video URL
  3279. result = re.search(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);', webpage)
  3280. if result is None:
  3281. raise ExtractorError(u'ERROR: unable to extract video url')
  3282. video_url = result.group('source')
  3283. info = {'id': video_id,
  3284. 'url': video_url,
  3285. 'title': video_title,
  3286. 'ext': 'flv',
  3287. 'format': 'flv',
  3288. 'player_url': embed_page_url}
  3289. return [info]
  3290. class EightTracksIE(InfoExtractor):
  3291. IE_NAME = '8tracks'
  3292. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  3293. def _real_extract(self, url):
  3294. mobj = re.match(self._VALID_URL, url)
  3295. if mobj is None:
  3296. raise ExtractorError(u'Invalid URL: %s' % url)
  3297. playlist_id = mobj.group('id')
  3298. webpage = self._download_webpage(url, playlist_id)
  3299. m = re.search(r"PAGE.mix = (.*?);\n", webpage, flags=re.DOTALL)
  3300. if not m:
  3301. raise ExtractorError(u'Cannot find trax information')
  3302. json_like = m.group(1)
  3303. data = json.loads(json_like)
  3304. session = str(random.randint(0, 1000000000))
  3305. mix_id = data['id']
  3306. track_count = data['tracks_count']
  3307. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  3308. next_url = first_url
  3309. res = []
  3310. for i in itertools.count():
  3311. api_json = self._download_webpage(next_url, playlist_id,
  3312. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  3313. errnote=u'Failed to download song information')
  3314. api_data = json.loads(api_json)
  3315. track_data = api_data[u'set']['track']
  3316. info = {
  3317. 'id': track_data['id'],
  3318. 'url': track_data['track_file_stream_url'],
  3319. 'title': track_data['performer'] + u' - ' + track_data['name'],
  3320. 'raw_title': track_data['name'],
  3321. 'uploader_id': data['user']['login'],
  3322. 'ext': 'm4a',
  3323. }
  3324. res.append(info)
  3325. if api_data['set']['at_last_track']:
  3326. break
  3327. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  3328. return res
  3329. class KeekIE(InfoExtractor):
  3330. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  3331. IE_NAME = u'keek'
  3332. def _real_extract(self, url):
  3333. m = re.match(self._VALID_URL, url)
  3334. video_id = m.group('videoID')
  3335. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  3336. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  3337. webpage = self._download_webpage(url, video_id)
  3338. m = re.search(r'<meta property="og:title" content="(?P<title>.*?)"', webpage)
  3339. title = unescapeHTML(m.group('title'))
  3340. m = re.search(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>', webpage)
  3341. uploader = clean_html(m.group('uploader'))
  3342. info = {
  3343. 'id': video_id,
  3344. 'url': video_url,
  3345. 'ext': 'mp4',
  3346. 'title': title,
  3347. 'thumbnail': thumbnail,
  3348. 'uploader': uploader
  3349. }
  3350. return [info]
  3351. class TEDIE(InfoExtractor):
  3352. _VALID_URL=r'''http://www.ted.com/
  3353. (
  3354. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  3355. |
  3356. ((?P<type_talk>talks)) # We have a simple talk
  3357. )
  3358. /(?P<name>\w+) # Here goes the name and then ".html"
  3359. '''
  3360. @classmethod
  3361. def suitable(cls, url):
  3362. """Receives a URL and returns True if suitable for this IE."""
  3363. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3364. def _real_extract(self, url):
  3365. m=re.match(self._VALID_URL, url, re.VERBOSE)
  3366. if m.group('type_talk'):
  3367. return [self._talk_info(url)]
  3368. else :
  3369. playlist_id=m.group('playlist_id')
  3370. name=m.group('name')
  3371. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  3372. return [self._playlist_videos_info(url,name,playlist_id)]
  3373. def _talk_video_link(self,mediaSlug):
  3374. '''Returns the video link for that mediaSlug'''
  3375. return 'http://download.ted.com/talks/%s.mp4' % mediaSlug
  3376. def _playlist_videos_info(self,url,name,playlist_id=0):
  3377. '''Returns the videos of the playlist'''
  3378. video_RE=r'''
  3379. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  3380. ([.\s]*?)data-playlist_item_id="(\d+)"
  3381. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  3382. '''
  3383. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  3384. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  3385. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  3386. m_names=re.finditer(video_name_RE,webpage)
  3387. playlist_RE = r'div class="headline">(\s*?)<h1>(\s*?)<span>(?P<playlist_title>.*?)</span>'
  3388. m_playlist = re.search(playlist_RE, webpage)
  3389. playlist_title = m_playlist.group('playlist_title')
  3390. playlist_entries = []
  3391. for m_video, m_name in zip(m_videos,m_names):
  3392. video_id=m_video.group('video_id')
  3393. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  3394. playlist_entries.append(self.url_result(talk_url, 'TED'))
  3395. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  3396. def _talk_info(self, url, video_id=0):
  3397. """Return the video for the talk in the url"""
  3398. m=re.match(self._VALID_URL, url,re.VERBOSE)
  3399. videoName=m.group('name')
  3400. webpage=self._download_webpage(url, video_id, 'Downloading \"%s\" page' % videoName)
  3401. # If the url includes the language we get the title translated
  3402. title_RE=r'<span id="altHeadline" >(?P<title>.*)</span>'
  3403. title=re.search(title_RE, webpage).group('title')
  3404. info_RE=r'''<script\ type="text/javascript">var\ talkDetails\ =(.*?)
  3405. "id":(?P<videoID>[\d]+).*?
  3406. "mediaSlug":"(?P<mediaSlug>[\w\d]+?)"'''
  3407. thumb_RE=r'</span>[\s.]*</div>[\s.]*<img src="(?P<thumbnail>.*?)"'
  3408. thumb_match=re.search(thumb_RE,webpage)
  3409. info_match=re.search(info_RE,webpage,re.VERBOSE)
  3410. video_id=info_match.group('videoID')
  3411. mediaSlug=info_match.group('mediaSlug')
  3412. video_url=self._talk_video_link(mediaSlug)
  3413. info = {
  3414. 'id': video_id,
  3415. 'url': video_url,
  3416. 'ext': 'mp4',
  3417. 'title': title,
  3418. 'thumbnail': thumb_match.group('thumbnail')
  3419. }
  3420. return info
  3421. class MySpassIE(InfoExtractor):
  3422. _VALID_URL = r'http://www.myspass.de/.*'
  3423. def _real_extract(self, url):
  3424. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  3425. # video id is the last path element of the URL
  3426. # usually there is a trailing slash, so also try the second but last
  3427. url_path = compat_urllib_parse_urlparse(url).path
  3428. url_parent_path, video_id = os.path.split(url_path)
  3429. if not video_id:
  3430. _, video_id = os.path.split(url_parent_path)
  3431. # get metadata
  3432. metadata_url = META_DATA_URL_TEMPLATE % video_id
  3433. metadata_text = self._download_webpage(metadata_url, video_id)
  3434. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  3435. # extract values from metadata
  3436. url_flv_el = metadata.find('url_flv')
  3437. if url_flv_el is None:
  3438. self._downloader.report_error(u'unable to extract download url')
  3439. return
  3440. video_url = url_flv_el.text
  3441. extension = os.path.splitext(video_url)[1][1:]
  3442. title_el = metadata.find('title')
  3443. if title_el is None:
  3444. self._downloader.report_error(u'unable to extract title')
  3445. return
  3446. title = title_el.text
  3447. format_id_el = metadata.find('format_id')
  3448. if format_id_el is None:
  3449. format = ext
  3450. else:
  3451. format = format_id_el.text
  3452. description_el = metadata.find('description')
  3453. if description_el is not None:
  3454. description = description_el.text
  3455. else:
  3456. description = None
  3457. imagePreview_el = metadata.find('imagePreview')
  3458. if imagePreview_el is not None:
  3459. thumbnail = imagePreview_el.text
  3460. else:
  3461. thumbnail = None
  3462. info = {
  3463. 'id': video_id,
  3464. 'url': video_url,
  3465. 'title': title,
  3466. 'ext': extension,
  3467. 'format': format,
  3468. 'thumbnail': thumbnail,
  3469. 'description': description
  3470. }
  3471. return [info]
  3472. class SpiegelIE(InfoExtractor):
  3473. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  3474. def _real_extract(self, url):
  3475. m = re.match(self._VALID_URL, url)
  3476. video_id = m.group('videoID')
  3477. webpage = self._download_webpage(url, video_id)
  3478. m = re.search(r'<div class="spVideoTitle">(.*?)</div>', webpage)
  3479. if not m:
  3480. raise ExtractorError(u'Cannot find title')
  3481. video_title = unescapeHTML(m.group(1))
  3482. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  3483. xml_code = self._download_webpage(xml_url, video_id,
  3484. note=u'Downloading XML', errnote=u'Failed to download XML')
  3485. idoc = xml.etree.ElementTree.fromstring(xml_code)
  3486. last_type = idoc[-1]
  3487. filename = last_type.findall('./filename')[0].text
  3488. duration = float(last_type.findall('./duration')[0].text)
  3489. video_url = 'http://video2.spiegel.de/flash/' + filename
  3490. video_ext = filename.rpartition('.')[2]
  3491. info = {
  3492. 'id': video_id,
  3493. 'url': video_url,
  3494. 'ext': video_ext,
  3495. 'title': video_title,
  3496. 'duration': duration,
  3497. }
  3498. return [info]
  3499. class LiveLeakIE(InfoExtractor):
  3500. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  3501. IE_NAME = u'liveleak'
  3502. def _real_extract(self, url):
  3503. mobj = re.match(self._VALID_URL, url)
  3504. if mobj is None:
  3505. self._downloader.report_error(u'invalid URL: %s' % url)
  3506. return
  3507. video_id = mobj.group('video_id')
  3508. webpage = self._download_webpage(url, video_id)
  3509. m = re.search(r'file: "(.*?)",', webpage)
  3510. if not m:
  3511. self._downloader.report_error(u'unable to find video url')
  3512. return
  3513. video_url = m.group(1)
  3514. m = re.search(r'<meta property="og:title" content="(?P<title>.*?)"', webpage)
  3515. if not m:
  3516. self._downloader.report_error(u'Cannot find video title')
  3517. title = unescapeHTML(m.group('title')).replace('LiveLeak.com -', '').strip()
  3518. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3519. if m:
  3520. desc = unescapeHTML(m.group('desc'))
  3521. else:
  3522. desc = None
  3523. m = re.search(r'By:.*?(\w+)</a>', webpage)
  3524. if m:
  3525. uploader = clean_html(m.group(1))
  3526. else:
  3527. uploader = None
  3528. info = {
  3529. 'id': video_id,
  3530. 'url': video_url,
  3531. 'ext': 'mp4',
  3532. 'title': title,
  3533. 'description': desc,
  3534. 'uploader': uploader
  3535. }
  3536. return [info]
  3537. class ARDIE(InfoExtractor):
  3538. _VALID_URL = r'^(?:https?://)?(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[^/\?]+)(?:\?.*)?'
  3539. _TITLE = r'<h1(?: class="boxTopHeadline")?>(?P<title>.*)</h1>'
  3540. _MEDIA_STREAM = r'mediaCollection\.addMediaStream\((?P<media_type>\d+), (?P<quality>\d+), "(?P<rtmp_url>[^"]*)", "(?P<video_url>[^"]*)", "[^"]*"\)'
  3541. def _real_extract(self, url):
  3542. # determine video id from url
  3543. m = re.match(self._VALID_URL, url)
  3544. numid = re.search(r'documentId=([0-9]+)', url)
  3545. if numid:
  3546. video_id = numid.group(1)
  3547. else:
  3548. video_id = m.group('video_id')
  3549. # determine title and media streams from webpage
  3550. html = self._download_webpage(url, video_id)
  3551. title = re.search(self._TITLE, html).group('title')
  3552. streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
  3553. if not streams:
  3554. assert '"fsk"' in html
  3555. self._downloader.report_error(u'this video is only available after 8:00 pm')
  3556. return
  3557. # choose default media type and highest quality for now
  3558. stream = max([s for s in streams if int(s["media_type"]) == 0],
  3559. key=lambda s: int(s["quality"]))
  3560. # there's two possibilities: RTMP stream or HTTP download
  3561. info = {'id': video_id, 'title': title, 'ext': 'mp4'}
  3562. if stream['rtmp_url']:
  3563. self.to_screen(u'RTMP download detected')
  3564. assert stream['video_url'].startswith('mp4:')
  3565. info["url"] = stream["rtmp_url"]
  3566. info["play_path"] = stream['video_url']
  3567. else:
  3568. assert stream["video_url"].endswith('.mp4')
  3569. info["url"] = stream["video_url"]
  3570. return [info]
  3571. class TumblrIE(InfoExtractor):
  3572. _VALID_URL = r'http://(?P<blog_name>.*?).tumblr.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  3573. def _real_extract(self, url):
  3574. m_url = re.match(self._VALID_URL, url)
  3575. video_id = m_url.group('id')
  3576. blog = m_url.group('blog_name')
  3577. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  3578. webpage = self._download_webpage(url, video_id)
  3579. re_video = r'src=\\x22(?P<video_url>http://%s.tumblr.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  3580. video = re.search(re_video, webpage)
  3581. if video is None:
  3582. self.to_screen("No video founded")
  3583. return []
  3584. video_url = video.group('video_url')
  3585. ext = video.group('ext')
  3586. re_thumb = r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22' # We pick the first poster
  3587. thumb = re.search(re_thumb, webpage).group('thumb').replace('\\', '')
  3588. # The only place where you can get a title, it's not complete,
  3589. # but searching in other places doesn't work for all videos
  3590. re_title = r'<title>(.*?) - (?P<title>.*?)</title>'
  3591. title = unescapeHTML(re.search(re_title, webpage).group('title'))
  3592. return [{'id': video_id,
  3593. 'url': video_url,
  3594. 'title': title,
  3595. 'thumbnail': thumb,
  3596. 'ext': ext
  3597. }]
  3598. def gen_extractors():
  3599. """ Return a list of an instance of every supported extractor.
  3600. The order does matter; the first extractor matched is the one handling the URL.
  3601. """
  3602. return [
  3603. YoutubePlaylistIE(),
  3604. YoutubeChannelIE(),
  3605. YoutubeUserIE(),
  3606. YoutubeSearchIE(),
  3607. YoutubeIE(),
  3608. MetacafeIE(),
  3609. DailymotionIE(),
  3610. GoogleSearchIE(),
  3611. PhotobucketIE(),
  3612. YahooIE(),
  3613. YahooSearchIE(),
  3614. DepositFilesIE(),
  3615. FacebookIE(),
  3616. BlipTVUserIE(),
  3617. BlipTVIE(),
  3618. VimeoIE(),
  3619. MyVideoIE(),
  3620. ComedyCentralIE(),
  3621. EscapistIE(),
  3622. CollegeHumorIE(),
  3623. XVideosIE(),
  3624. SoundcloudSetIE(),
  3625. SoundcloudIE(),
  3626. InfoQIE(),
  3627. MixcloudIE(),
  3628. StanfordOpenClassroomIE(),
  3629. MTVIE(),
  3630. YoukuIE(),
  3631. XNXXIE(),
  3632. YouJizzIE(),
  3633. PornotubeIE(),
  3634. YouPornIE(),
  3635. GooglePlusIE(),
  3636. ArteTvIE(),
  3637. NBAIE(),
  3638. WorldStarHipHopIE(),
  3639. JustinTVIE(),
  3640. FunnyOrDieIE(),
  3641. SteamIE(),
  3642. UstreamIE(),
  3643. RBMARadioIE(),
  3644. EightTracksIE(),
  3645. KeekIE(),
  3646. TEDIE(),
  3647. MySpassIE(),
  3648. SpiegelIE(),
  3649. LiveLeakIE(),
  3650. ARDIE(),
  3651. TumblrIE(),
  3652. GenericIE()
  3653. ]
  3654. def get_info_extractor(ie_name):
  3655. """Returns the info extractor class with the given ie_name"""
  3656. return globals()[ie_name+'IE']