InfoExtractors.py 187 KB

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