InfoExtractors.py 188 KB

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