InfoExtractors.py 173 KB

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