InfoExtractors.py 186 KB

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