InfoExtractors.py 158 KB

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