InfoExtractors.py 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. import hashlib
  18. import binascii
  19. import urllib
  20. from .utils import *
  21. from .extractor.common import InfoExtractor, SearchInfoExtractor
  22. from .extractor.dailymotion import DailymotionIE
  23. from .extractor.metacafe import MetacafeIE
  24. from .extractor.statigram import StatigramIE
  25. from .extractor.youtube import YoutubeIE, YoutubePlaylistIE, YoutubeUserIE, YoutubeChannelIE
  26. class PhotobucketIE(InfoExtractor):
  27. """Information extractor for photobucket.com."""
  28. # TODO: the original _VALID_URL was:
  29. # r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  30. # Check if it's necessary to keep the old extracion process
  31. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*(([\?\&]current=)|_)(?P<id>.*)\.(?P<ext>(flv)|(mp4))'
  32. IE_NAME = u'photobucket'
  33. def _real_extract(self, url):
  34. # Extract id from URL
  35. mobj = re.match(self._VALID_URL, url)
  36. if mobj is None:
  37. raise ExtractorError(u'Invalid URL: %s' % url)
  38. video_id = mobj.group('id')
  39. video_extension = mobj.group('ext')
  40. # Retrieve video webpage to extract further information
  41. webpage = self._download_webpage(url, video_id)
  42. # Extract URL, uploader, and title from webpage
  43. self.report_extraction(video_id)
  44. # We try first by looking the javascript code:
  45. mobj = re.search(r'Pb\.Data\.Shared\.put\(Pb\.Data\.Shared\.MEDIA, (?P<json>.*?)\);', webpage)
  46. if mobj is not None:
  47. info = json.loads(mobj.group('json'))
  48. return [{
  49. 'id': video_id,
  50. 'url': info[u'downloadUrl'],
  51. 'uploader': info[u'username'],
  52. 'upload_date': datetime.date.fromtimestamp(info[u'creationDate']).strftime('%Y%m%d'),
  53. 'title': info[u'title'],
  54. 'ext': video_extension,
  55. 'thumbnail': info[u'thumbUrl'],
  56. }]
  57. # We try looking in other parts of the webpage
  58. video_url = self._search_regex(r'<link rel="video_src" href=".*\?file=([^"]+)" />',
  59. webpage, u'video URL')
  60. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  61. if mobj is None:
  62. raise ExtractorError(u'Unable to extract title')
  63. video_title = mobj.group(1).decode('utf-8')
  64. video_uploader = mobj.group(2).decode('utf-8')
  65. return [{
  66. 'id': video_id.decode('utf-8'),
  67. 'url': video_url.decode('utf-8'),
  68. 'uploader': video_uploader,
  69. 'upload_date': None,
  70. 'title': video_title,
  71. 'ext': video_extension.decode('utf-8'),
  72. }]
  73. class YahooIE(InfoExtractor):
  74. """Information extractor for screen.yahoo.com."""
  75. _VALID_URL = r'http://screen\.yahoo\.com/.*?-(?P<id>\d*?)\.html'
  76. def _real_extract(self, url):
  77. mobj = re.match(self._VALID_URL, url)
  78. if mobj is None:
  79. raise ExtractorError(u'Invalid URL: %s' % url)
  80. video_id = mobj.group('id')
  81. webpage = self._download_webpage(url, video_id)
  82. m_id = re.search(r'YUI\.namespace\("Media"\)\.CONTENT_ID = "(?P<new_id>.+?)";', webpage)
  83. if m_id is None:
  84. # TODO: Check which url parameters are required
  85. info_url = 'http://cosmos.bcst.yahoo.com/rest/v2/pops;lmsoverride=1;outputformat=mrss;cb=974419660;id=%s;rd=news.yahoo.com;datacontext=mdb;lg=KCa2IihxG3qE60vQ7HtyUy' % video_id
  86. webpage = self._download_webpage(info_url, video_id, u'Downloading info webpage')
  87. info_re = r'''<title><!\[CDATA\[(?P<title>.*?)\]\]></title>.*
  88. <description><!\[CDATA\[(?P<description>.*?)\]\]></description>.*
  89. <media:pubStart><!\[CDATA\[(?P<date>.*?)\ .*\]\]></media:pubStart>.*
  90. <media:content\ medium="image"\ url="(?P<thumb>.*?)"\ name="LARGETHUMB"
  91. '''
  92. self.report_extraction(video_id)
  93. m_info = re.search(info_re, webpage, re.VERBOSE|re.DOTALL)
  94. if m_info is None:
  95. raise ExtractorError(u'Unable to extract video info')
  96. video_title = m_info.group('title')
  97. video_description = m_info.group('description')
  98. video_thumb = m_info.group('thumb')
  99. video_date = m_info.group('date')
  100. video_date = datetime.datetime.strptime(video_date, '%m/%d/%Y').strftime('%Y%m%d')
  101. # TODO: Find a way to get mp4 videos
  102. rest_url = 'http://cosmos.bcst.yahoo.com/rest/v2/pops;element=stream;outputformat=mrss;id=%s;lmsoverride=1;bw=375;dynamicstream=1;cb=83521105;tech=flv,mp4;rd=news.yahoo.com;datacontext=mdb;lg=KCa2IihxG3qE60vQ7HtyUy' % video_id
  103. webpage = self._download_webpage(rest_url, video_id, u'Downloading video url webpage')
  104. m_rest = re.search(r'<media:content url="(?P<url>.*?)" path="(?P<path>.*?)"', webpage)
  105. video_url = m_rest.group('url')
  106. video_path = m_rest.group('path')
  107. if m_rest is None:
  108. raise ExtractorError(u'Unable to extract video url')
  109. else: # We have to use a different method if another id is defined
  110. long_id = m_id.group('new_id')
  111. info_url = 'http://video.query.yahoo.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.media.video.streams%20WHERE%20id%3D%22' + long_id + '%22%20AND%20format%3D%22mp4%2Cflv%22%20AND%20protocol%3D%22rtmp%2Chttp%22%20AND%20plrs%3D%2286Gj0vCaSzV_Iuf6hNylf2%22%20AND%20acctid%3D%22389%22%20AND%20plidl%3D%22%22%20AND%20pspid%3D%22792700001%22%20AND%20offnetwork%3D%22false%22%20AND%20site%3D%22ivy%22%20AND%20lang%3D%22en-US%22%20AND%20region%3D%22US%22%20AND%20override%3D%22none%22%3B&env=prod&format=json&callback=YUI.Env.JSONP.yui_3_8_1_1_1368368376830_335'
  112. webpage = self._download_webpage(info_url, video_id, u'Downloading info json')
  113. json_str = re.search(r'YUI.Env.JSONP.yui.*?\((.*?)\);', webpage).group(1)
  114. info = json.loads(json_str)
  115. res = info[u'query'][u'results'][u'mediaObj'][0]
  116. stream = res[u'streams'][0]
  117. video_path = stream[u'path']
  118. video_url = stream[u'host']
  119. meta = res[u'meta']
  120. video_title = meta[u'title']
  121. video_description = meta[u'description']
  122. video_thumb = meta[u'thumbnail']
  123. video_date = None # I can't find it
  124. info_dict = {
  125. 'id': video_id,
  126. 'url': video_url,
  127. 'play_path': video_path,
  128. 'title':video_title,
  129. 'description': video_description,
  130. 'thumbnail': video_thumb,
  131. 'upload_date': video_date,
  132. 'ext': 'flv',
  133. }
  134. return info_dict
  135. class VimeoIE(InfoExtractor):
  136. """Information extractor for vimeo.com."""
  137. # _VALID_URL matches Vimeo URLs
  138. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo(?P<pro>pro)?\.com/(?:(?:(?:groups|album)/[^/]+)|(?:.*?)/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)'
  139. IE_NAME = u'vimeo'
  140. def _verify_video_password(self, url, video_id, webpage):
  141. password = self._downloader.params.get('password', None)
  142. if password is None:
  143. raise ExtractorError(u'This video is protected by a password, use the --password option')
  144. token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
  145. data = compat_urllib_parse.urlencode({'password': password,
  146. 'token': token})
  147. # I didn't manage to use the password with https
  148. if url.startswith('https'):
  149. pass_url = url.replace('https','http')
  150. else:
  151. pass_url = url
  152. password_request = compat_urllib_request.Request(pass_url+'/password', data)
  153. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  154. password_request.add_header('Cookie', 'xsrft=%s' % token)
  155. pass_web = self._download_webpage(password_request, video_id,
  156. u'Verifying the password',
  157. u'Wrong password')
  158. def _real_extract(self, url, new_video=True):
  159. # Extract ID from URL
  160. mobj = re.match(self._VALID_URL, url)
  161. if mobj is None:
  162. raise ExtractorError(u'Invalid URL: %s' % url)
  163. video_id = mobj.group('id')
  164. if not mobj.group('proto'):
  165. url = 'https://' + url
  166. if mobj.group('direct_link') or mobj.group('pro'):
  167. url = 'https://vimeo.com/' + video_id
  168. # Retrieve video webpage to extract further information
  169. request = compat_urllib_request.Request(url, None, std_headers)
  170. webpage = self._download_webpage(request, video_id)
  171. # Now we begin extracting as much information as we can from what we
  172. # retrieved. First we extract the information common to all extractors,
  173. # and latter we extract those that are Vimeo specific.
  174. self.report_extraction(video_id)
  175. # Extract the config JSON
  176. try:
  177. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  178. config = json.loads(config)
  179. except:
  180. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  181. raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
  182. if re.search('If so please provide the correct password.', webpage):
  183. self._verify_video_password(url, video_id, webpage)
  184. return self._real_extract(url)
  185. else:
  186. raise ExtractorError(u'Unable to extract info section')
  187. # Extract title
  188. video_title = config["video"]["title"]
  189. # Extract uploader and uploader_id
  190. video_uploader = config["video"]["owner"]["name"]
  191. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  192. # Extract video thumbnail
  193. video_thumbnail = config["video"]["thumbnail"]
  194. # Extract video description
  195. video_description = get_element_by_attribute("itemprop", "description", webpage)
  196. if video_description: video_description = clean_html(video_description)
  197. else: video_description = u''
  198. # Extract upload date
  199. video_upload_date = None
  200. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  201. if mobj is not None:
  202. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  203. # Vimeo specific: extract request signature and timestamp
  204. sig = config['request']['signature']
  205. timestamp = config['request']['timestamp']
  206. # Vimeo specific: extract video codec and quality information
  207. # First consider quality, then codecs, then take everything
  208. # TODO bind to format param
  209. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  210. files = { 'hd': [], 'sd': [], 'other': []}
  211. for codec_name, codec_extension in codecs:
  212. if codec_name in config["video"]["files"]:
  213. if 'hd' in config["video"]["files"][codec_name]:
  214. files['hd'].append((codec_name, codec_extension, 'hd'))
  215. elif 'sd' in config["video"]["files"][codec_name]:
  216. files['sd'].append((codec_name, codec_extension, 'sd'))
  217. else:
  218. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  219. for quality in ('hd', 'sd', 'other'):
  220. if len(files[quality]) > 0:
  221. video_quality = files[quality][0][2]
  222. video_codec = files[quality][0][0]
  223. video_extension = files[quality][0][1]
  224. self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  225. break
  226. else:
  227. raise ExtractorError(u'No known codec found')
  228. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  229. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  230. return [{
  231. 'id': video_id,
  232. 'url': video_url,
  233. 'uploader': video_uploader,
  234. 'uploader_id': video_uploader_id,
  235. 'upload_date': video_upload_date,
  236. 'title': video_title,
  237. 'ext': video_extension,
  238. 'thumbnail': video_thumbnail,
  239. 'description': video_description,
  240. }]
  241. class ArteTvIE(InfoExtractor):
  242. """arte.tv information extractor."""
  243. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  244. _LIVE_URL = r'index-[0-9]+\.html$'
  245. IE_NAME = u'arte.tv'
  246. def fetch_webpage(self, url):
  247. request = compat_urllib_request.Request(url)
  248. try:
  249. self.report_download_webpage(url)
  250. webpage = compat_urllib_request.urlopen(request).read()
  251. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  252. raise ExtractorError(u'Unable to retrieve video webpage: %s' % compat_str(err))
  253. except ValueError as err:
  254. raise ExtractorError(u'Invalid URL: %s' % url)
  255. return webpage
  256. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  257. page = self.fetch_webpage(url)
  258. mobj = re.search(regex, page, regexFlags)
  259. info = {}
  260. if mobj is None:
  261. raise ExtractorError(u'Invalid URL: %s' % url)
  262. for (i, key, err) in matchTuples:
  263. if mobj.group(i) is None:
  264. raise ExtractorError(err)
  265. else:
  266. info[key] = mobj.group(i)
  267. return info
  268. def extractLiveStream(self, url):
  269. video_lang = url.split('/')[-4]
  270. info = self.grep_webpage(
  271. url,
  272. r'src="(.*?/videothek_js.*?\.js)',
  273. 0,
  274. [
  275. (1, 'url', u'Invalid URL: %s' % url)
  276. ]
  277. )
  278. http_host = url.split('/')[2]
  279. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  280. info = self.grep_webpage(
  281. next_url,
  282. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  283. '(http://.*?\.swf).*?' +
  284. '(rtmp://.*?)\'',
  285. re.DOTALL,
  286. [
  287. (1, 'path', u'could not extract video path: %s' % url),
  288. (2, 'player', u'could not extract video player: %s' % url),
  289. (3, 'url', u'could not extract video url: %s' % url)
  290. ]
  291. )
  292. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  293. def extractPlus7Stream(self, url):
  294. video_lang = url.split('/')[-3]
  295. info = self.grep_webpage(
  296. url,
  297. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  298. 0,
  299. [
  300. (1, 'url', u'Invalid URL: %s' % url)
  301. ]
  302. )
  303. next_url = compat_urllib_parse.unquote(info.get('url'))
  304. info = self.grep_webpage(
  305. next_url,
  306. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  307. 0,
  308. [
  309. (1, 'url', u'Could not find <video> tag: %s' % url)
  310. ]
  311. )
  312. next_url = compat_urllib_parse.unquote(info.get('url'))
  313. info = self.grep_webpage(
  314. next_url,
  315. r'<video id="(.*?)".*?>.*?' +
  316. '<name>(.*?)</name>.*?' +
  317. '<dateVideo>(.*?)</dateVideo>.*?' +
  318. '<url quality="hd">(.*?)</url>',
  319. re.DOTALL,
  320. [
  321. (1, 'id', u'could not extract video id: %s' % url),
  322. (2, 'title', u'could not extract video title: %s' % url),
  323. (3, 'date', u'could not extract video date: %s' % url),
  324. (4, 'url', u'could not extract video url: %s' % url)
  325. ]
  326. )
  327. return {
  328. 'id': info.get('id'),
  329. 'url': compat_urllib_parse.unquote(info.get('url')),
  330. 'uploader': u'arte.tv',
  331. 'upload_date': unified_strdate(info.get('date')),
  332. 'title': info.get('title').decode('utf-8'),
  333. 'ext': u'mp4',
  334. 'format': u'NA',
  335. 'player_url': None,
  336. }
  337. def _real_extract(self, url):
  338. video_id = url.split('/')[-1]
  339. self.report_extraction(video_id)
  340. if re.search(self._LIVE_URL, video_id) is not None:
  341. self.extractLiveStream(url)
  342. return
  343. else:
  344. info = self.extractPlus7Stream(url)
  345. return [info]
  346. class GenericIE(InfoExtractor):
  347. """Generic last-resort information extractor."""
  348. _VALID_URL = r'.*'
  349. IE_NAME = u'generic'
  350. def report_download_webpage(self, video_id):
  351. """Report webpage download."""
  352. if not self._downloader.params.get('test', False):
  353. self._downloader.report_warning(u'Falling back on generic information extractor.')
  354. super(GenericIE, self).report_download_webpage(video_id)
  355. def report_following_redirect(self, new_url):
  356. """Report information extraction."""
  357. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  358. def _test_redirect(self, url):
  359. """Check if it is a redirect, like url shorteners, in case return the new url."""
  360. class HeadRequest(compat_urllib_request.Request):
  361. def get_method(self):
  362. return "HEAD"
  363. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  364. """
  365. Subclass the HTTPRedirectHandler to make it use our
  366. HeadRequest also on the redirected URL
  367. """
  368. def redirect_request(self, req, fp, code, msg, headers, newurl):
  369. if code in (301, 302, 303, 307):
  370. newurl = newurl.replace(' ', '%20')
  371. newheaders = dict((k,v) for k,v in req.headers.items()
  372. if k.lower() not in ("content-length", "content-type"))
  373. return HeadRequest(newurl,
  374. headers=newheaders,
  375. origin_req_host=req.get_origin_req_host(),
  376. unverifiable=True)
  377. else:
  378. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  379. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  380. """
  381. Fallback to GET if HEAD is not allowed (405 HTTP error)
  382. """
  383. def http_error_405(self, req, fp, code, msg, headers):
  384. fp.read()
  385. fp.close()
  386. newheaders = dict((k,v) for k,v in req.headers.items()
  387. if k.lower() not in ("content-length", "content-type"))
  388. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  389. headers=newheaders,
  390. origin_req_host=req.get_origin_req_host(),
  391. unverifiable=True))
  392. # Build our opener
  393. opener = compat_urllib_request.OpenerDirector()
  394. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  395. HTTPMethodFallback, HEADRedirectHandler,
  396. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  397. opener.add_handler(handler())
  398. response = opener.open(HeadRequest(url))
  399. if response is None:
  400. raise ExtractorError(u'Invalid URL protocol')
  401. new_url = response.geturl()
  402. if url == new_url:
  403. return False
  404. self.report_following_redirect(new_url)
  405. return new_url
  406. def _real_extract(self, url):
  407. new_url = self._test_redirect(url)
  408. if new_url: return [self.url_result(new_url)]
  409. video_id = url.split('/')[-1]
  410. try:
  411. webpage = self._download_webpage(url, video_id)
  412. except ValueError as err:
  413. # since this is the last-resort InfoExtractor, if
  414. # this error is thrown, it'll be thrown here
  415. raise ExtractorError(u'Invalid URL: %s' % url)
  416. self.report_extraction(video_id)
  417. # Start with something easy: JW Player in SWFObject
  418. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  419. if mobj is None:
  420. # Broaden the search a little bit
  421. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  422. if mobj is None:
  423. # Broaden the search a little bit: JWPlayer JS loader
  424. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  425. if mobj is None:
  426. # Try to find twitter cards info
  427. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  428. if mobj is None:
  429. # We look for Open Graph info:
  430. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  431. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  432. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  433. if m_video_type is not None:
  434. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  435. if mobj is None:
  436. raise ExtractorError(u'Invalid URL: %s' % url)
  437. # It's possible that one of the regexes
  438. # matched, but returned an empty group:
  439. if mobj.group(1) is None:
  440. raise ExtractorError(u'Invalid URL: %s' % url)
  441. video_url = compat_urllib_parse.unquote(mobj.group(1))
  442. video_id = os.path.basename(video_url)
  443. # here's a fun little line of code for you:
  444. video_extension = os.path.splitext(video_id)[1][1:]
  445. video_id = os.path.splitext(video_id)[0]
  446. # it's tempting to parse this further, but you would
  447. # have to take into account all the variations like
  448. # Video Title - Site Name
  449. # Site Name | Video Title
  450. # Video Title - Tagline | Site Name
  451. # and so on and so forth; it's just not practical
  452. video_title = self._html_search_regex(r'<title>(.*)</title>',
  453. webpage, u'video title')
  454. # video uploader is domain name
  455. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  456. url, u'video uploader')
  457. return [{
  458. 'id': video_id,
  459. 'url': video_url,
  460. 'uploader': video_uploader,
  461. 'upload_date': None,
  462. 'title': video_title,
  463. 'ext': video_extension,
  464. }]
  465. class YoutubeSearchIE(SearchInfoExtractor):
  466. """Information Extractor for YouTube search queries."""
  467. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  468. _MAX_RESULTS = 1000
  469. IE_NAME = u'youtube:search'
  470. _SEARCH_KEY = 'ytsearch'
  471. def report_download_page(self, query, pagenum):
  472. """Report attempt to download search page with given number."""
  473. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  474. def _get_n_results(self, query, n):
  475. """Get a specified number of results for a query"""
  476. video_ids = []
  477. pagenum = 0
  478. limit = n
  479. while (50 * pagenum) < limit:
  480. self.report_download_page(query, pagenum+1)
  481. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  482. request = compat_urllib_request.Request(result_url)
  483. try:
  484. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  485. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  486. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  487. api_response = json.loads(data)['data']
  488. if not 'items' in api_response:
  489. raise ExtractorError(u'[youtube] No video results')
  490. new_ids = list(video['id'] for video in api_response['items'])
  491. video_ids += new_ids
  492. limit = min(n, api_response['totalItems'])
  493. pagenum += 1
  494. if len(video_ids) > n:
  495. video_ids = video_ids[:n]
  496. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  497. return self.playlist_result(videos, query)
  498. class GoogleSearchIE(SearchInfoExtractor):
  499. """Information Extractor for Google Video search queries."""
  500. _MORE_PAGES_INDICATOR = r'id="pnnext" class="pn"'
  501. _MAX_RESULTS = 1000
  502. IE_NAME = u'video.google:search'
  503. _SEARCH_KEY = 'gvsearch'
  504. def _get_n_results(self, query, n):
  505. """Get a specified number of results for a query"""
  506. res = {
  507. '_type': 'playlist',
  508. 'id': query,
  509. 'entries': []
  510. }
  511. for pagenum in itertools.count(1):
  512. result_url = u'http://www.google.com/search?tbm=vid&q=%s&start=%s&hl=en' % (compat_urllib_parse.quote_plus(query), pagenum*10)
  513. webpage = self._download_webpage(result_url, u'gvsearch:' + query,
  514. note='Downloading result page ' + str(pagenum))
  515. for mobj in re.finditer(r'<h3 class="r"><a href="([^"]+)"', webpage):
  516. e = {
  517. '_type': 'url',
  518. 'url': mobj.group(1)
  519. }
  520. res['entries'].append(e)
  521. if (pagenum * 10 > n) or not re.search(self._MORE_PAGES_INDICATOR, webpage):
  522. return res
  523. class YahooSearchIE(SearchInfoExtractor):
  524. """Information Extractor for Yahoo! Video search queries."""
  525. _MAX_RESULTS = 1000
  526. IE_NAME = u'screen.yahoo:search'
  527. _SEARCH_KEY = 'yvsearch'
  528. def _get_n_results(self, query, n):
  529. """Get a specified number of results for a query"""
  530. res = {
  531. '_type': 'playlist',
  532. 'id': query,
  533. 'entries': []
  534. }
  535. for pagenum in itertools.count(0):
  536. result_url = u'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus(query), pagenum * 30)
  537. webpage = self._download_webpage(result_url, query,
  538. note='Downloading results page '+str(pagenum+1))
  539. info = json.loads(webpage)
  540. m = info[u'm']
  541. results = info[u'results']
  542. for (i, r) in enumerate(results):
  543. if (pagenum * 30) +i >= n:
  544. break
  545. mobj = re.search(r'(?P<url>screen\.yahoo\.com/.*?-\d*?\.html)"', r)
  546. e = self.url_result('http://' + mobj.group('url'), 'Yahoo')
  547. res['entries'].append(e)
  548. if (pagenum * 30 +i >= n) or (m[u'last'] >= (m[u'total'] -1 )):
  549. break
  550. return res
  551. class BlipTVUserIE(InfoExtractor):
  552. """Information Extractor for blip.tv users."""
  553. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  554. _PAGE_SIZE = 12
  555. IE_NAME = u'blip.tv:user'
  556. def _real_extract(self, url):
  557. # Extract username
  558. mobj = re.match(self._VALID_URL, url)
  559. if mobj is None:
  560. raise ExtractorError(u'Invalid URL: %s' % url)
  561. username = mobj.group(1)
  562. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  563. page = self._download_webpage(url, username, u'Downloading user page')
  564. mobj = re.search(r'data-users-id="([^"]+)"', page)
  565. page_base = page_base % mobj.group(1)
  566. # Download video ids using BlipTV Ajax calls. Result size per
  567. # query is limited (currently to 12 videos) so we need to query
  568. # page by page until there are no video ids - it means we got
  569. # all of them.
  570. video_ids = []
  571. pagenum = 1
  572. while True:
  573. url = page_base + "&page=" + str(pagenum)
  574. page = self._download_webpage(url, username,
  575. u'Downloading video ids from page %d' % pagenum)
  576. # Extract video identifiers
  577. ids_in_page = []
  578. for mobj in re.finditer(r'href="/([^"]+)"', page):
  579. if mobj.group(1) not in ids_in_page:
  580. ids_in_page.append(unescapeHTML(mobj.group(1)))
  581. video_ids.extend(ids_in_page)
  582. # A little optimization - if current page is not
  583. # "full", ie. does not contain PAGE_SIZE video ids then
  584. # we can assume that this page is the last one - there
  585. # are no more ids on further pages - no need to query
  586. # again.
  587. if len(ids_in_page) < self._PAGE_SIZE:
  588. break
  589. pagenum += 1
  590. urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
  591. url_entries = [self.url_result(url, 'BlipTV') for url in urls]
  592. return [self.playlist_result(url_entries, playlist_title = username)]
  593. class DepositFilesIE(InfoExtractor):
  594. """Information extractor for depositfiles.com"""
  595. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  596. def _real_extract(self, url):
  597. file_id = url.split('/')[-1]
  598. # Rebuild url in english locale
  599. url = 'http://depositfiles.com/en/files/' + file_id
  600. # Retrieve file webpage with 'Free download' button pressed
  601. free_download_indication = { 'gateway_result' : '1' }
  602. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  603. try:
  604. self.report_download_webpage(file_id)
  605. webpage = compat_urllib_request.urlopen(request).read()
  606. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  607. raise ExtractorError(u'Unable to retrieve file webpage: %s' % compat_str(err))
  608. # Search for the real file URL
  609. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  610. if (mobj is None) or (mobj.group(1) is None):
  611. # Try to figure out reason of the error.
  612. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  613. if (mobj is not None) and (mobj.group(1) is not None):
  614. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  615. raise ExtractorError(u'%s' % restriction_message)
  616. else:
  617. raise ExtractorError(u'Unable to extract download URL from: %s' % url)
  618. file_url = mobj.group(1)
  619. file_extension = os.path.splitext(file_url)[1][1:]
  620. # Search for file title
  621. file_title = self._search_regex(r'<b title="(.*?)">', webpage, u'title')
  622. return [{
  623. 'id': file_id.decode('utf-8'),
  624. 'url': file_url.decode('utf-8'),
  625. 'uploader': None,
  626. 'upload_date': None,
  627. 'title': file_title,
  628. 'ext': file_extension.decode('utf-8'),
  629. }]
  630. class FacebookIE(InfoExtractor):
  631. """Information Extractor for Facebook"""
  632. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  633. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  634. _NETRC_MACHINE = 'facebook'
  635. IE_NAME = u'facebook'
  636. def report_login(self):
  637. """Report attempt to log in."""
  638. self.to_screen(u'Logging in')
  639. def _real_initialize(self):
  640. if self._downloader is None:
  641. return
  642. useremail = None
  643. password = None
  644. downloader_params = self._downloader.params
  645. # Attempt to use provided username and password or .netrc data
  646. if downloader_params.get('username', None) is not None:
  647. useremail = downloader_params['username']
  648. password = downloader_params['password']
  649. elif downloader_params.get('usenetrc', False):
  650. try:
  651. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  652. if info is not None:
  653. useremail = info[0]
  654. password = info[2]
  655. else:
  656. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  657. except (IOError, netrc.NetrcParseError) as err:
  658. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  659. return
  660. if useremail is None:
  661. return
  662. # Log in
  663. login_form = {
  664. 'email': useremail,
  665. 'pass': password,
  666. 'login': 'Log+In'
  667. }
  668. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  669. try:
  670. self.report_login()
  671. login_results = compat_urllib_request.urlopen(request).read()
  672. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  673. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  674. return
  675. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  676. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  677. return
  678. def _real_extract(self, url):
  679. mobj = re.match(self._VALID_URL, url)
  680. if mobj is None:
  681. raise ExtractorError(u'Invalid URL: %s' % url)
  682. video_id = mobj.group('ID')
  683. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  684. webpage = self._download_webpage(url, video_id)
  685. BEFORE = '{swf.addParam(param[0], param[1]);});\n'
  686. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  687. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  688. if not m:
  689. raise ExtractorError(u'Cannot parse data')
  690. data = dict(json.loads(m.group(1)))
  691. params_raw = compat_urllib_parse.unquote(data['params'])
  692. params = json.loads(params_raw)
  693. video_data = params['video_data'][0]
  694. video_url = video_data.get('hd_src')
  695. if not video_url:
  696. video_url = video_data['sd_src']
  697. if not video_url:
  698. raise ExtractorError(u'Cannot find video URL')
  699. video_duration = int(video_data['video_duration'])
  700. thumbnail = video_data['thumbnail_src']
  701. video_title = self._html_search_regex('<h2 class="uiHeaderTitle">([^<]+)</h2>',
  702. webpage, u'title')
  703. info = {
  704. 'id': video_id,
  705. 'title': video_title,
  706. 'url': video_url,
  707. 'ext': 'mp4',
  708. 'duration': video_duration,
  709. 'thumbnail': thumbnail,
  710. }
  711. return [info]
  712. class BlipTVIE(InfoExtractor):
  713. """Information extractor for blip.tv"""
  714. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
  715. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  716. IE_NAME = u'blip.tv'
  717. def report_direct_download(self, title):
  718. """Report information extraction."""
  719. self.to_screen(u'%s: Direct download detected' % title)
  720. def _real_extract(self, url):
  721. mobj = re.match(self._VALID_URL, url)
  722. if mobj is None:
  723. raise ExtractorError(u'Invalid URL: %s' % url)
  724. # See https://github.com/rg3/youtube-dl/issues/857
  725. api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
  726. if api_mobj is not None:
  727. url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
  728. urlp = compat_urllib_parse_urlparse(url)
  729. if urlp.path.startswith('/play/'):
  730. request = compat_urllib_request.Request(url)
  731. response = compat_urllib_request.urlopen(request)
  732. redirecturl = response.geturl()
  733. rurlp = compat_urllib_parse_urlparse(redirecturl)
  734. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  735. url = 'http://blip.tv/a/a-' + file_id
  736. return self._real_extract(url)
  737. if '?' in url:
  738. cchar = '&'
  739. else:
  740. cchar = '?'
  741. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  742. request = compat_urllib_request.Request(json_url)
  743. request.add_header('User-Agent', 'iTunes/10.6.1')
  744. self.report_extraction(mobj.group(1))
  745. info = None
  746. try:
  747. urlh = compat_urllib_request.urlopen(request)
  748. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  749. basename = url.split('/')[-1]
  750. title,ext = os.path.splitext(basename)
  751. title = title.decode('UTF-8')
  752. ext = ext.replace('.', '')
  753. self.report_direct_download(title)
  754. info = {
  755. 'id': title,
  756. 'url': url,
  757. 'uploader': None,
  758. 'upload_date': None,
  759. 'title': title,
  760. 'ext': ext,
  761. 'urlhandle': urlh
  762. }
  763. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  764. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  765. if info is None: # Regular URL
  766. try:
  767. json_code_bytes = urlh.read()
  768. json_code = json_code_bytes.decode('utf-8')
  769. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  770. raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
  771. try:
  772. json_data = json.loads(json_code)
  773. if 'Post' in json_data:
  774. data = json_data['Post']
  775. else:
  776. data = json_data
  777. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  778. video_url = data['media']['url']
  779. umobj = re.match(self._URL_EXT, video_url)
  780. if umobj is None:
  781. raise ValueError('Can not determine filename extension')
  782. ext = umobj.group(1)
  783. info = {
  784. 'id': data['item_id'],
  785. 'url': video_url,
  786. 'uploader': data['display_name'],
  787. 'upload_date': upload_date,
  788. 'title': data['title'],
  789. 'ext': ext,
  790. 'format': data['media']['mimeType'],
  791. 'thumbnail': data['thumbnailUrl'],
  792. 'description': data['description'],
  793. 'player_url': data['embedUrl'],
  794. 'user_agent': 'iTunes/10.6.1',
  795. }
  796. except (ValueError,KeyError) as err:
  797. raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
  798. return [info]
  799. class MyVideoIE(InfoExtractor):
  800. """Information Extractor for myvideo.de."""
  801. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  802. IE_NAME = u'myvideo'
  803. # Original Code from: https://github.com/dersphere/plugin.video.myvideo_de.git
  804. # Released into the Public Domain by Tristan Fischer on 2013-05-19
  805. # https://github.com/rg3/youtube-dl/pull/842
  806. def __rc4crypt(self,data, key):
  807. x = 0
  808. box = list(range(256))
  809. for i in list(range(256)):
  810. x = (x + box[i] + compat_ord(key[i % len(key)])) % 256
  811. box[i], box[x] = box[x], box[i]
  812. x = 0
  813. y = 0
  814. out = ''
  815. for char in data:
  816. x = (x + 1) % 256
  817. y = (y + box[x]) % 256
  818. box[x], box[y] = box[y], box[x]
  819. out += chr(compat_ord(char) ^ box[(box[x] + box[y]) % 256])
  820. return out
  821. def __md5(self,s):
  822. return hashlib.md5(s).hexdigest().encode()
  823. def _real_extract(self,url):
  824. mobj = re.match(self._VALID_URL, url)
  825. if mobj is None:
  826. raise ExtractorError(u'invalid URL: %s' % url)
  827. video_id = mobj.group(1)
  828. GK = (
  829. b'WXpnME1EZGhNRGhpTTJNM01XVmhOREU0WldNNVpHTTJOakpt'
  830. b'TW1FMU5tVTBNR05pWkRaa05XRXhNVFJoWVRVd1ptSXhaVEV3'
  831. b'TnpsbA0KTVRkbU1tSTRNdz09'
  832. )
  833. # Get video webpage
  834. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  835. webpage = self._download_webpage(webpage_url, video_id)
  836. mobj = re.search('source src=\'(.+?)[.]([^.]+)\'', webpage)
  837. if mobj is not None:
  838. self.report_extraction(video_id)
  839. video_url = mobj.group(1) + '.flv'
  840. video_title = self._html_search_regex('<title>([^<]+)</title>',
  841. webpage, u'title')
  842. video_ext = self._search_regex('[.](.+?)$', video_url, u'extension')
  843. return [{
  844. 'id': video_id,
  845. 'url': video_url,
  846. 'uploader': None,
  847. 'upload_date': None,
  848. 'title': video_title,
  849. 'ext': u'flv',
  850. }]
  851. # try encxml
  852. mobj = re.search('var flashvars={(.+?)}', webpage)
  853. if mobj is None:
  854. raise ExtractorError(u'Unable to extract video')
  855. params = {}
  856. encxml = ''
  857. sec = mobj.group(1)
  858. for (a, b) in re.findall('(.+?):\'(.+?)\',?', sec):
  859. if not a == '_encxml':
  860. params[a] = b
  861. else:
  862. encxml = compat_urllib_parse.unquote(b)
  863. if not params.get('domain'):
  864. params['domain'] = 'www.myvideo.de'
  865. xmldata_url = '%s?%s' % (encxml, compat_urllib_parse.urlencode(params))
  866. if 'flash_playertype=MTV' in xmldata_url:
  867. self._downloader.report_warning(u'avoiding MTV player')
  868. xmldata_url = (
  869. 'http://www.myvideo.de/dynamic/get_player_video_xml.php'
  870. '?flash_playertype=D&ID=%s&_countlimit=4&autorun=yes'
  871. ) % video_id
  872. # get enc data
  873. enc_data = self._download_webpage(xmldata_url, video_id).split('=')[1]
  874. enc_data_b = binascii.unhexlify(enc_data)
  875. sk = self.__md5(
  876. base64.b64decode(base64.b64decode(GK)) +
  877. self.__md5(
  878. str(video_id).encode('utf-8')
  879. )
  880. )
  881. dec_data = self.__rc4crypt(enc_data_b, sk)
  882. # extracting infos
  883. self.report_extraction(video_id)
  884. video_url = None
  885. mobj = re.search('connectionurl=\'(.*?)\'', dec_data)
  886. if mobj:
  887. video_url = compat_urllib_parse.unquote(mobj.group(1))
  888. if 'myvideo2flash' in video_url:
  889. self._downloader.report_warning(u'forcing RTMPT ...')
  890. video_url = video_url.replace('rtmpe://', 'rtmpt://')
  891. if not video_url:
  892. # extract non rtmp videos
  893. mobj = re.search('path=\'(http.*?)\' source=\'(.*?)\'', dec_data)
  894. if mobj is None:
  895. raise ExtractorError(u'unable to extract url')
  896. video_url = compat_urllib_parse.unquote(mobj.group(1)) + compat_urllib_parse.unquote(mobj.group(2))
  897. video_file = self._search_regex('source=\'(.*?)\'', dec_data, u'video file')
  898. video_file = compat_urllib_parse.unquote(video_file)
  899. if not video_file.endswith('f4m'):
  900. ppath, prefix = video_file.split('.')
  901. video_playpath = '%s:%s' % (prefix, ppath)
  902. video_hls_playlist = ''
  903. else:
  904. video_playpath = ''
  905. video_hls_playlist = (
  906. video_filepath + video_file
  907. ).replace('.f4m', '.m3u8')
  908. video_swfobj = self._search_regex('swfobject.embedSWF\(\'(.+?)\'', webpage, u'swfobj')
  909. video_swfobj = compat_urllib_parse.unquote(video_swfobj)
  910. video_title = self._html_search_regex("<h1(?: class='globalHd')?>(.*?)</h1>",
  911. webpage, u'title')
  912. return [{
  913. 'id': video_id,
  914. 'url': video_url,
  915. 'tc_url': video_url,
  916. 'uploader': None,
  917. 'upload_date': None,
  918. 'title': video_title,
  919. 'ext': u'flv',
  920. 'play_path': video_playpath,
  921. 'video_file': video_file,
  922. 'video_hls_playlist': video_hls_playlist,
  923. 'player_url': video_swfobj,
  924. }]
  925. class ComedyCentralIE(InfoExtractor):
  926. """Information extractor for The Daily Show and Colbert Report """
  927. # urls can be abbreviations like :thedailyshow or :colbert
  928. # urls for episodes like:
  929. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  930. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  931. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  932. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  933. |(https?://)?(www\.)?
  934. (?P<showname>thedailyshow|colbertnation)\.com/
  935. (full-episodes/(?P<episode>.*)|
  936. (?P<clip>
  937. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  938. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  939. $"""
  940. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  941. _video_extensions = {
  942. '3500': 'mp4',
  943. '2200': 'mp4',
  944. '1700': 'mp4',
  945. '1200': 'mp4',
  946. '750': 'mp4',
  947. '400': 'mp4',
  948. }
  949. _video_dimensions = {
  950. '3500': '1280x720',
  951. '2200': '960x540',
  952. '1700': '768x432',
  953. '1200': '640x360',
  954. '750': '512x288',
  955. '400': '384x216',
  956. }
  957. @classmethod
  958. def suitable(cls, url):
  959. """Receives a URL and returns True if suitable for this IE."""
  960. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  961. def _print_formats(self, formats):
  962. print('Available formats:')
  963. for x in formats:
  964. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  965. def _real_extract(self, url):
  966. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  967. if mobj is None:
  968. raise ExtractorError(u'Invalid URL: %s' % url)
  969. if mobj.group('shortname'):
  970. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  971. url = u'http://www.thedailyshow.com/full-episodes/'
  972. else:
  973. url = u'http://www.colbertnation.com/full-episodes/'
  974. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  975. assert mobj is not None
  976. if mobj.group('clip'):
  977. if mobj.group('showname') == 'thedailyshow':
  978. epTitle = mobj.group('tdstitle')
  979. else:
  980. epTitle = mobj.group('cntitle')
  981. dlNewest = False
  982. else:
  983. dlNewest = not mobj.group('episode')
  984. if dlNewest:
  985. epTitle = mobj.group('showname')
  986. else:
  987. epTitle = mobj.group('episode')
  988. self.report_extraction(epTitle)
  989. webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
  990. if dlNewest:
  991. url = htmlHandle.geturl()
  992. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  993. if mobj is None:
  994. raise ExtractorError(u'Invalid redirected URL: ' + url)
  995. if mobj.group('episode') == '':
  996. raise ExtractorError(u'Redirected URL is still not specific: ' + url)
  997. epTitle = mobj.group('episode')
  998. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  999. if len(mMovieParams) == 0:
  1000. # The Colbert Report embeds the information in a without
  1001. # a URL prefix; so extract the alternate reference
  1002. # and then add the URL prefix manually.
  1003. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  1004. if len(altMovieParams) == 0:
  1005. raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
  1006. else:
  1007. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  1008. uri = mMovieParams[0][1]
  1009. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  1010. indexXml = self._download_webpage(indexUrl, epTitle,
  1011. u'Downloading show index',
  1012. u'unable to download episode index')
  1013. results = []
  1014. idoc = xml.etree.ElementTree.fromstring(indexXml)
  1015. itemEls = idoc.findall('.//item')
  1016. for partNum,itemEl in enumerate(itemEls):
  1017. mediaId = itemEl.findall('./guid')[0].text
  1018. shortMediaId = mediaId.split(':')[-1]
  1019. showId = mediaId.split(':')[-2].replace('.com', '')
  1020. officialTitle = itemEl.findall('./title')[0].text
  1021. officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
  1022. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  1023. compat_urllib_parse.urlencode({'uri': mediaId}))
  1024. configXml = self._download_webpage(configUrl, epTitle,
  1025. u'Downloading configuration for %s' % shortMediaId)
  1026. cdoc = xml.etree.ElementTree.fromstring(configXml)
  1027. turls = []
  1028. for rendition in cdoc.findall('.//rendition'):
  1029. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  1030. turls.append(finfo)
  1031. if len(turls) == 0:
  1032. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  1033. continue
  1034. if self._downloader.params.get('listformats', None):
  1035. self._print_formats([i[0] for i in turls])
  1036. return
  1037. # For now, just pick the highest bitrate
  1038. format,rtmp_video_url = turls[-1]
  1039. # Get the format arg from the arg stream
  1040. req_format = self._downloader.params.get('format', None)
  1041. # Select format if we can find one
  1042. for f,v in turls:
  1043. if f == req_format:
  1044. format, rtmp_video_url = f, v
  1045. break
  1046. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  1047. if not m:
  1048. raise ExtractorError(u'Cannot transform RTMP url')
  1049. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  1050. video_url = base + m.group('finalid')
  1051. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  1052. info = {
  1053. 'id': shortMediaId,
  1054. 'url': video_url,
  1055. 'uploader': showId,
  1056. 'upload_date': officialDate,
  1057. 'title': effTitle,
  1058. 'ext': 'mp4',
  1059. 'format': format,
  1060. 'thumbnail': None,
  1061. 'description': officialTitle,
  1062. }
  1063. results.append(info)
  1064. return results
  1065. class EscapistIE(InfoExtractor):
  1066. """Information extractor for The Escapist """
  1067. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  1068. IE_NAME = u'escapist'
  1069. def _real_extract(self, url):
  1070. mobj = re.match(self._VALID_URL, url)
  1071. if mobj is None:
  1072. raise ExtractorError(u'Invalid URL: %s' % url)
  1073. showName = mobj.group('showname')
  1074. videoId = mobj.group('episode')
  1075. self.report_extraction(videoId)
  1076. webpage = self._download_webpage(url, videoId)
  1077. videoDesc = self._html_search_regex('<meta name="description" content="([^"]*)"',
  1078. webpage, u'description', fatal=False)
  1079. imgUrl = self._html_search_regex('<meta property="og:image" content="([^"]*)"',
  1080. webpage, u'thumbnail', fatal=False)
  1081. playerUrl = self._html_search_regex('<meta property="og:video" content="([^"]*)"',
  1082. webpage, u'player url')
  1083. title = self._html_search_regex('<meta name="title" content="([^"]*)"',
  1084. webpage, u'player url').split(' : ')[-1]
  1085. configUrl = self._search_regex('config=(.*)$', playerUrl, u'config url')
  1086. configUrl = compat_urllib_parse.unquote(configUrl)
  1087. configJSON = self._download_webpage(configUrl, videoId,
  1088. u'Downloading configuration',
  1089. u'unable to download configuration')
  1090. # Technically, it's JavaScript, not JSON
  1091. configJSON = configJSON.replace("'", '"')
  1092. try:
  1093. config = json.loads(configJSON)
  1094. except (ValueError,) as err:
  1095. raise ExtractorError(u'Invalid JSON in configuration file: ' + compat_str(err))
  1096. playlist = config['playlist']
  1097. videoUrl = playlist[1]['url']
  1098. info = {
  1099. 'id': videoId,
  1100. 'url': videoUrl,
  1101. 'uploader': showName,
  1102. 'upload_date': None,
  1103. 'title': title,
  1104. 'ext': 'mp4',
  1105. 'thumbnail': imgUrl,
  1106. 'description': videoDesc,
  1107. 'player_url': playerUrl,
  1108. }
  1109. return [info]
  1110. class CollegeHumorIE(InfoExtractor):
  1111. """Information extractor for collegehumor.com"""
  1112. _WORKING = False
  1113. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  1114. IE_NAME = u'collegehumor'
  1115. def report_manifest(self, video_id):
  1116. """Report information extraction."""
  1117. self.to_screen(u'%s: Downloading XML manifest' % video_id)
  1118. def _real_extract(self, url):
  1119. mobj = re.match(self._VALID_URL, url)
  1120. if mobj is None:
  1121. raise ExtractorError(u'Invalid URL: %s' % url)
  1122. video_id = mobj.group('videoid')
  1123. info = {
  1124. 'id': video_id,
  1125. 'uploader': None,
  1126. 'upload_date': None,
  1127. }
  1128. self.report_extraction(video_id)
  1129. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  1130. try:
  1131. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  1132. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1133. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  1134. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  1135. try:
  1136. videoNode = mdoc.findall('./video')[0]
  1137. info['description'] = videoNode.findall('./description')[0].text
  1138. info['title'] = videoNode.findall('./caption')[0].text
  1139. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  1140. manifest_url = videoNode.findall('./file')[0].text
  1141. except IndexError:
  1142. raise ExtractorError(u'Invalid metadata XML file')
  1143. manifest_url += '?hdcore=2.10.3'
  1144. self.report_manifest(video_id)
  1145. try:
  1146. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  1147. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1148. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  1149. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  1150. try:
  1151. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  1152. node_id = media_node.attrib['url']
  1153. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  1154. except IndexError as err:
  1155. raise ExtractorError(u'Invalid manifest file')
  1156. url_pr = compat_urllib_parse_urlparse(manifest_url)
  1157. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  1158. info['url'] = url
  1159. info['ext'] = 'f4f'
  1160. return [info]
  1161. class XVideosIE(InfoExtractor):
  1162. """Information extractor for xvideos.com"""
  1163. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  1164. IE_NAME = u'xvideos'
  1165. def _real_extract(self, url):
  1166. mobj = re.match(self._VALID_URL, url)
  1167. if mobj is None:
  1168. raise ExtractorError(u'Invalid URL: %s' % url)
  1169. video_id = mobj.group(1)
  1170. webpage = self._download_webpage(url, video_id)
  1171. self.report_extraction(video_id)
  1172. # Extract video URL
  1173. video_url = compat_urllib_parse.unquote(self._search_regex(r'flv_url=(.+?)&',
  1174. webpage, u'video URL'))
  1175. # Extract title
  1176. video_title = self._html_search_regex(r'<title>(.*?)\s+-\s+XVID',
  1177. webpage, u'title')
  1178. # Extract video thumbnail
  1179. video_thumbnail = self._search_regex(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/([a-fA-F0-9.]+jpg)',
  1180. webpage, u'thumbnail', fatal=False)
  1181. info = {
  1182. 'id': video_id,
  1183. 'url': video_url,
  1184. 'uploader': None,
  1185. 'upload_date': None,
  1186. 'title': video_title,
  1187. 'ext': 'flv',
  1188. 'thumbnail': video_thumbnail,
  1189. 'description': None,
  1190. }
  1191. return [info]
  1192. class SoundcloudIE(InfoExtractor):
  1193. """Information extractor for soundcloud.com
  1194. To access the media, the uid of the song and a stream token
  1195. must be extracted from the page source and the script must make
  1196. a request to media.soundcloud.com/crossdomain.xml. Then
  1197. the media can be grabbed by requesting from an url composed
  1198. of the stream token and uid
  1199. """
  1200. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  1201. IE_NAME = u'soundcloud'
  1202. def report_resolve(self, video_id):
  1203. """Report information extraction."""
  1204. self.to_screen(u'%s: Resolving id' % video_id)
  1205. def _real_extract(self, url):
  1206. mobj = re.match(self._VALID_URL, url)
  1207. if mobj is None:
  1208. raise ExtractorError(u'Invalid URL: %s' % url)
  1209. # extract uploader (which is in the url)
  1210. uploader = mobj.group(1)
  1211. # extract simple title (uploader + slug of song title)
  1212. slug_title = mobj.group(2)
  1213. simple_title = uploader + u'-' + slug_title
  1214. full_title = '%s/%s' % (uploader, slug_title)
  1215. self.report_resolve(full_title)
  1216. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  1217. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  1218. info_json = self._download_webpage(resolv_url, full_title, u'Downloading info JSON')
  1219. info = json.loads(info_json)
  1220. video_id = info['id']
  1221. self.report_extraction(full_title)
  1222. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  1223. stream_json = self._download_webpage(streams_url, full_title,
  1224. u'Downloading stream definitions',
  1225. u'unable to download stream definitions')
  1226. streams = json.loads(stream_json)
  1227. mediaURL = streams['http_mp3_128_url']
  1228. upload_date = unified_strdate(info['created_at'])
  1229. return [{
  1230. 'id': info['id'],
  1231. 'url': mediaURL,
  1232. 'uploader': info['user']['username'],
  1233. 'upload_date': upload_date,
  1234. 'title': info['title'],
  1235. 'ext': u'mp3',
  1236. 'description': info['description'],
  1237. }]
  1238. class SoundcloudSetIE(InfoExtractor):
  1239. """Information extractor for soundcloud.com sets
  1240. To access the media, the uid of the song and a stream token
  1241. must be extracted from the page source and the script must make
  1242. a request to media.soundcloud.com/crossdomain.xml. Then
  1243. the media can be grabbed by requesting from an url composed
  1244. of the stream token and uid
  1245. """
  1246. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  1247. IE_NAME = u'soundcloud:set'
  1248. def report_resolve(self, video_id):
  1249. """Report information extraction."""
  1250. self.to_screen(u'%s: Resolving id' % video_id)
  1251. def _real_extract(self, url):
  1252. mobj = re.match(self._VALID_URL, url)
  1253. if mobj is None:
  1254. raise ExtractorError(u'Invalid URL: %s' % url)
  1255. # extract uploader (which is in the url)
  1256. uploader = mobj.group(1)
  1257. # extract simple title (uploader + slug of song title)
  1258. slug_title = mobj.group(2)
  1259. simple_title = uploader + u'-' + slug_title
  1260. full_title = '%s/sets/%s' % (uploader, slug_title)
  1261. self.report_resolve(full_title)
  1262. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  1263. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  1264. info_json = self._download_webpage(resolv_url, full_title)
  1265. videos = []
  1266. info = json.loads(info_json)
  1267. if 'errors' in info:
  1268. for err in info['errors']:
  1269. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  1270. return
  1271. self.report_extraction(full_title)
  1272. for track in info['tracks']:
  1273. video_id = track['id']
  1274. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  1275. stream_json = self._download_webpage(streams_url, video_id, u'Downloading track info JSON')
  1276. self.report_extraction(video_id)
  1277. streams = json.loads(stream_json)
  1278. mediaURL = streams['http_mp3_128_url']
  1279. videos.append({
  1280. 'id': video_id,
  1281. 'url': mediaURL,
  1282. 'uploader': track['user']['username'],
  1283. 'upload_date': unified_strdate(track['created_at']),
  1284. 'title': track['title'],
  1285. 'ext': u'mp3',
  1286. 'description': track['description'],
  1287. })
  1288. return videos
  1289. class InfoQIE(InfoExtractor):
  1290. """Information extractor for infoq.com"""
  1291. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  1292. def _real_extract(self, url):
  1293. mobj = re.match(self._VALID_URL, url)
  1294. if mobj is None:
  1295. raise ExtractorError(u'Invalid URL: %s' % url)
  1296. webpage = self._download_webpage(url, video_id=url)
  1297. self.report_extraction(url)
  1298. # Extract video URL
  1299. mobj = re.search(r"jsclassref ?= ?'([^']*)'", webpage)
  1300. if mobj is None:
  1301. raise ExtractorError(u'Unable to extract video url')
  1302. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  1303. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  1304. # Extract title
  1305. video_title = self._search_regex(r'contentTitle = "(.*?)";',
  1306. webpage, u'title')
  1307. # Extract description
  1308. video_description = self._html_search_regex(r'<meta name="description" content="(.*)"(?:\s*/)?>',
  1309. webpage, u'description', fatal=False)
  1310. video_filename = video_url.split('/')[-1]
  1311. video_id, extension = video_filename.split('.')
  1312. info = {
  1313. 'id': video_id,
  1314. 'url': video_url,
  1315. 'uploader': None,
  1316. 'upload_date': None,
  1317. 'title': video_title,
  1318. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  1319. 'thumbnail': None,
  1320. 'description': video_description,
  1321. }
  1322. return [info]
  1323. class MixcloudIE(InfoExtractor):
  1324. """Information extractor for www.mixcloud.com"""
  1325. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  1326. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  1327. IE_NAME = u'mixcloud'
  1328. def report_download_json(self, file_id):
  1329. """Report JSON download."""
  1330. self.to_screen(u'Downloading json')
  1331. def get_urls(self, jsonData, fmt, bitrate='best'):
  1332. """Get urls from 'audio_formats' section in json"""
  1333. file_url = None
  1334. try:
  1335. bitrate_list = jsonData[fmt]
  1336. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  1337. bitrate = max(bitrate_list) # select highest
  1338. url_list = jsonData[fmt][bitrate]
  1339. except TypeError: # we have no bitrate info.
  1340. url_list = jsonData[fmt]
  1341. return url_list
  1342. def check_urls(self, url_list):
  1343. """Returns 1st active url from list"""
  1344. for url in url_list:
  1345. try:
  1346. compat_urllib_request.urlopen(url)
  1347. return url
  1348. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1349. url = None
  1350. return None
  1351. def _print_formats(self, formats):
  1352. print('Available formats:')
  1353. for fmt in formats.keys():
  1354. for b in formats[fmt]:
  1355. try:
  1356. ext = formats[fmt][b][0]
  1357. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  1358. except TypeError: # we have no bitrate info
  1359. ext = formats[fmt][0]
  1360. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  1361. break
  1362. def _real_extract(self, url):
  1363. mobj = re.match(self._VALID_URL, url)
  1364. if mobj is None:
  1365. raise ExtractorError(u'Invalid URL: %s' % url)
  1366. # extract uploader & filename from url
  1367. uploader = mobj.group(1).decode('utf-8')
  1368. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  1369. # construct API request
  1370. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  1371. # retrieve .json file with links to files
  1372. request = compat_urllib_request.Request(file_url)
  1373. try:
  1374. self.report_download_json(file_url)
  1375. jsonData = compat_urllib_request.urlopen(request).read()
  1376. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1377. raise ExtractorError(u'Unable to retrieve file: %s' % compat_str(err))
  1378. # parse JSON
  1379. json_data = json.loads(jsonData)
  1380. player_url = json_data['player_swf_url']
  1381. formats = dict(json_data['audio_formats'])
  1382. req_format = self._downloader.params.get('format', None)
  1383. bitrate = None
  1384. if self._downloader.params.get('listformats', None):
  1385. self._print_formats(formats)
  1386. return
  1387. if req_format is None or req_format == 'best':
  1388. for format_param in formats.keys():
  1389. url_list = self.get_urls(formats, format_param)
  1390. # check urls
  1391. file_url = self.check_urls(url_list)
  1392. if file_url is not None:
  1393. break # got it!
  1394. else:
  1395. if req_format not in formats:
  1396. raise ExtractorError(u'Format is not available')
  1397. url_list = self.get_urls(formats, req_format)
  1398. file_url = self.check_urls(url_list)
  1399. format_param = req_format
  1400. return [{
  1401. 'id': file_id.decode('utf-8'),
  1402. 'url': file_url.decode('utf-8'),
  1403. 'uploader': uploader.decode('utf-8'),
  1404. 'upload_date': None,
  1405. 'title': json_data['name'],
  1406. 'ext': file_url.split('.')[-1].decode('utf-8'),
  1407. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1408. 'thumbnail': json_data['thumbnail_url'],
  1409. 'description': json_data['description'],
  1410. 'player_url': player_url.decode('utf-8'),
  1411. }]
  1412. class StanfordOpenClassroomIE(InfoExtractor):
  1413. """Information extractor for Stanford's Open ClassRoom"""
  1414. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  1415. IE_NAME = u'stanfordoc'
  1416. def _real_extract(self, url):
  1417. mobj = re.match(self._VALID_URL, url)
  1418. if mobj is None:
  1419. raise ExtractorError(u'Invalid URL: %s' % url)
  1420. if mobj.group('course') and mobj.group('video'): # A specific video
  1421. course = mobj.group('course')
  1422. video = mobj.group('video')
  1423. info = {
  1424. 'id': course + '_' + video,
  1425. 'uploader': None,
  1426. 'upload_date': None,
  1427. }
  1428. self.report_extraction(info['id'])
  1429. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  1430. xmlUrl = baseUrl + video + '.xml'
  1431. try:
  1432. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  1433. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1434. raise ExtractorError(u'Unable to download video info XML: %s' % compat_str(err))
  1435. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  1436. try:
  1437. info['title'] = mdoc.findall('./title')[0].text
  1438. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  1439. except IndexError:
  1440. raise ExtractorError(u'Invalid metadata XML file')
  1441. info['ext'] = info['url'].rpartition('.')[2]
  1442. return [info]
  1443. elif mobj.group('course'): # A course page
  1444. course = mobj.group('course')
  1445. info = {
  1446. 'id': course,
  1447. 'type': 'playlist',
  1448. 'uploader': None,
  1449. 'upload_date': None,
  1450. }
  1451. coursepage = self._download_webpage(url, info['id'],
  1452. note='Downloading course info page',
  1453. errnote='Unable to download course info page')
  1454. info['title'] = self._html_search_regex('<h1>([^<]+)</h1>', coursepage, 'title', default=info['id'])
  1455. info['description'] = self._html_search_regex('<description>([^<]+)</description>',
  1456. coursepage, u'description', fatal=False)
  1457. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  1458. info['list'] = [
  1459. {
  1460. 'type': 'reference',
  1461. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  1462. }
  1463. for vpage in links]
  1464. results = []
  1465. for entry in info['list']:
  1466. assert entry['type'] == 'reference'
  1467. results += self.extract(entry['url'])
  1468. return results
  1469. else: # Root page
  1470. info = {
  1471. 'id': 'Stanford OpenClassroom',
  1472. 'type': 'playlist',
  1473. 'uploader': None,
  1474. 'upload_date': None,
  1475. }
  1476. self.report_download_webpage(info['id'])
  1477. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  1478. try:
  1479. rootpage = compat_urllib_request.urlopen(rootURL).read()
  1480. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1481. raise ExtractorError(u'Unable to download course info page: ' + compat_str(err))
  1482. info['title'] = info['id']
  1483. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  1484. info['list'] = [
  1485. {
  1486. 'type': 'reference',
  1487. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  1488. }
  1489. for cpage in links]
  1490. results = []
  1491. for entry in info['list']:
  1492. assert entry['type'] == 'reference'
  1493. results += self.extract(entry['url'])
  1494. return results
  1495. class MTVIE(InfoExtractor):
  1496. """Information extractor for MTV.com"""
  1497. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  1498. IE_NAME = u'mtv'
  1499. def _real_extract(self, url):
  1500. mobj = re.match(self._VALID_URL, url)
  1501. if mobj is None:
  1502. raise ExtractorError(u'Invalid URL: %s' % url)
  1503. if not mobj.group('proto'):
  1504. url = 'http://' + url
  1505. video_id = mobj.group('videoid')
  1506. webpage = self._download_webpage(url, video_id)
  1507. song_name = self._html_search_regex(r'<meta name="mtv_vt" content="([^"]+)"/>',
  1508. webpage, u'song name', fatal=False)
  1509. video_title = self._html_search_regex(r'<meta name="mtv_an" content="([^"]+)"/>',
  1510. webpage, u'title')
  1511. mtvn_uri = self._html_search_regex(r'<meta name="mtvn_uri" content="([^"]+)"/>',
  1512. webpage, u'mtvn_uri', fatal=False)
  1513. content_id = self._search_regex(r'MTVN.Player.defaultPlaylistId = ([0-9]+);',
  1514. webpage, u'content id', fatal=False)
  1515. 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
  1516. self.report_extraction(video_id)
  1517. request = compat_urllib_request.Request(videogen_url)
  1518. try:
  1519. metadataXml = compat_urllib_request.urlopen(request).read()
  1520. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1521. raise ExtractorError(u'Unable to download video metadata: %s' % compat_str(err))
  1522. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  1523. renditions = mdoc.findall('.//rendition')
  1524. # For now, always pick the highest quality.
  1525. rendition = renditions[-1]
  1526. try:
  1527. _,_,ext = rendition.attrib['type'].partition('/')
  1528. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  1529. video_url = rendition.find('./src').text
  1530. except KeyError:
  1531. raise ExtractorError('Invalid rendition field.')
  1532. info = {
  1533. 'id': video_id,
  1534. 'url': video_url,
  1535. 'uploader': performer,
  1536. 'upload_date': None,
  1537. 'title': video_title,
  1538. 'ext': ext,
  1539. 'format': format,
  1540. }
  1541. return [info]
  1542. class YoukuIE(InfoExtractor):
  1543. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  1544. def _gen_sid(self):
  1545. nowTime = int(time.time() * 1000)
  1546. random1 = random.randint(1000,1998)
  1547. random2 = random.randint(1000,9999)
  1548. return "%d%d%d" %(nowTime,random1,random2)
  1549. def _get_file_ID_mix_string(self, seed):
  1550. mixed = []
  1551. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  1552. seed = float(seed)
  1553. for i in range(len(source)):
  1554. seed = (seed * 211 + 30031 ) % 65536
  1555. index = math.floor(seed / 65536 * len(source) )
  1556. mixed.append(source[int(index)])
  1557. source.remove(source[int(index)])
  1558. #return ''.join(mixed)
  1559. return mixed
  1560. def _get_file_id(self, fileId, seed):
  1561. mixed = self._get_file_ID_mix_string(seed)
  1562. ids = fileId.split('*')
  1563. realId = []
  1564. for ch in ids:
  1565. if ch:
  1566. realId.append(mixed[int(ch)])
  1567. return ''.join(realId)
  1568. def _real_extract(self, url):
  1569. mobj = re.match(self._VALID_URL, url)
  1570. if mobj is None:
  1571. raise ExtractorError(u'Invalid URL: %s' % url)
  1572. video_id = mobj.group('ID')
  1573. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  1574. jsondata = self._download_webpage(info_url, video_id)
  1575. self.report_extraction(video_id)
  1576. try:
  1577. config = json.loads(jsondata)
  1578. video_title = config['data'][0]['title']
  1579. seed = config['data'][0]['seed']
  1580. format = self._downloader.params.get('format', None)
  1581. supported_format = list(config['data'][0]['streamfileids'].keys())
  1582. if format is None or format == 'best':
  1583. if 'hd2' in supported_format:
  1584. format = 'hd2'
  1585. else:
  1586. format = 'flv'
  1587. ext = u'flv'
  1588. elif format == 'worst':
  1589. format = 'mp4'
  1590. ext = u'mp4'
  1591. else:
  1592. format = 'flv'
  1593. ext = u'flv'
  1594. fileid = config['data'][0]['streamfileids'][format]
  1595. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  1596. except (UnicodeDecodeError, ValueError, KeyError):
  1597. raise ExtractorError(u'Unable to extract info section')
  1598. files_info=[]
  1599. sid = self._gen_sid()
  1600. fileid = self._get_file_id(fileid, seed)
  1601. #column 8,9 of fileid represent the segment number
  1602. #fileid[7:9] should be changed
  1603. for index, key in enumerate(keys):
  1604. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  1605. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  1606. info = {
  1607. 'id': '%s_part%02d' % (video_id, index),
  1608. 'url': download_url,
  1609. 'uploader': None,
  1610. 'upload_date': None,
  1611. 'title': video_title,
  1612. 'ext': ext,
  1613. }
  1614. files_info.append(info)
  1615. return files_info
  1616. class XNXXIE(InfoExtractor):
  1617. """Information extractor for xnxx.com"""
  1618. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  1619. IE_NAME = u'xnxx'
  1620. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  1621. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  1622. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  1623. def _real_extract(self, url):
  1624. mobj = re.match(self._VALID_URL, url)
  1625. if mobj is None:
  1626. raise ExtractorError(u'Invalid URL: %s' % url)
  1627. video_id = mobj.group(1)
  1628. # Get webpage content
  1629. webpage = self._download_webpage(url, video_id)
  1630. video_url = self._search_regex(self.VIDEO_URL_RE,
  1631. webpage, u'video URL')
  1632. video_url = compat_urllib_parse.unquote(video_url)
  1633. video_title = self._html_search_regex(self.VIDEO_TITLE_RE,
  1634. webpage, u'title')
  1635. video_thumbnail = self._search_regex(self.VIDEO_THUMB_RE,
  1636. webpage, u'thumbnail', fatal=False)
  1637. return [{
  1638. 'id': video_id,
  1639. 'url': video_url,
  1640. 'uploader': None,
  1641. 'upload_date': None,
  1642. 'title': video_title,
  1643. 'ext': 'flv',
  1644. 'thumbnail': video_thumbnail,
  1645. 'description': None,
  1646. }]
  1647. class GooglePlusIE(InfoExtractor):
  1648. """Information extractor for plus.google.com."""
  1649. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  1650. IE_NAME = u'plus.google'
  1651. def _real_extract(self, url):
  1652. # Extract id from URL
  1653. mobj = re.match(self._VALID_URL, url)
  1654. if mobj is None:
  1655. raise ExtractorError(u'Invalid URL: %s' % url)
  1656. post_url = mobj.group(0)
  1657. video_id = mobj.group(1)
  1658. video_extension = 'flv'
  1659. # Step 1, Retrieve post webpage to extract further information
  1660. webpage = self._download_webpage(post_url, video_id, u'Downloading entry webpage')
  1661. self.report_extraction(video_id)
  1662. # Extract update date
  1663. upload_date = self._html_search_regex('title="Timestamp">(.*?)</a>',
  1664. webpage, u'upload date', fatal=False)
  1665. if upload_date:
  1666. # Convert timestring to a format suitable for filename
  1667. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  1668. upload_date = upload_date.strftime('%Y%m%d')
  1669. # Extract uploader
  1670. uploader = self._html_search_regex(r'rel\="author".*?>(.*?)</a>',
  1671. webpage, u'uploader', fatal=False)
  1672. # Extract title
  1673. # Get the first line for title
  1674. video_title = self._html_search_regex(r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]',
  1675. webpage, 'title', default=u'NA')
  1676. # Step 2, Stimulate clicking the image box to launch video
  1677. video_page = self._search_regex('"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]',
  1678. webpage, u'video page URL')
  1679. webpage = self._download_webpage(video_page, video_id, u'Downloading video page')
  1680. # Extract video links on video page
  1681. """Extract video links of all sizes"""
  1682. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  1683. mobj = re.findall(pattern, webpage)
  1684. if len(mobj) == 0:
  1685. raise ExtractorError(u'Unable to extract video links')
  1686. # Sort in resolution
  1687. links = sorted(mobj)
  1688. # Choose the lowest of the sort, i.e. highest resolution
  1689. video_url = links[-1]
  1690. # Only get the url. The resolution part in the tuple has no use anymore
  1691. video_url = video_url[-1]
  1692. # Treat escaped \u0026 style hex
  1693. try:
  1694. video_url = video_url.decode("unicode_escape")
  1695. except AttributeError: # Python 3
  1696. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  1697. return [{
  1698. 'id': video_id,
  1699. 'url': video_url,
  1700. 'uploader': uploader,
  1701. 'upload_date': upload_date,
  1702. 'title': video_title,
  1703. 'ext': video_extension,
  1704. }]
  1705. class NBAIE(InfoExtractor):
  1706. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*?)(?:/index\.html)?(?:\?.*)?$'
  1707. IE_NAME = u'nba'
  1708. def _real_extract(self, url):
  1709. mobj = re.match(self._VALID_URL, url)
  1710. if mobj is None:
  1711. raise ExtractorError(u'Invalid URL: %s' % url)
  1712. video_id = mobj.group(1)
  1713. webpage = self._download_webpage(url, video_id)
  1714. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  1715. shortened_video_id = video_id.rpartition('/')[2]
  1716. title = self._html_search_regex(r'<meta property="og:title" content="(.*?)"',
  1717. webpage, 'title', default=shortened_video_id).replace('NBA.com: ', '')
  1718. # It isn't there in the HTML it returns to us
  1719. # uploader_date = self._html_search_regex(r'<b>Date:</b> (.*?)</div>', webpage, 'upload_date', fatal=False)
  1720. description = self._html_search_regex(r'<meta name="description" (?:content|value)="(.*?)" />', webpage, 'description', fatal=False)
  1721. info = {
  1722. 'id': shortened_video_id,
  1723. 'url': video_url,
  1724. 'ext': 'mp4',
  1725. 'title': title,
  1726. # 'uploader_date': uploader_date,
  1727. 'description': description,
  1728. }
  1729. return [info]
  1730. class JustinTVIE(InfoExtractor):
  1731. """Information extractor for justin.tv and twitch.tv"""
  1732. # TODO: One broadcast may be split into multiple videos. The key
  1733. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  1734. # starts at 1 and increases. Can we treat all parts as one video?
  1735. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  1736. (?:
  1737. (?P<channelid>[^/]+)|
  1738. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  1739. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  1740. )
  1741. /?(?:\#.*)?$
  1742. """
  1743. _JUSTIN_PAGE_LIMIT = 100
  1744. IE_NAME = u'justin.tv'
  1745. def report_download_page(self, channel, offset):
  1746. """Report attempt to download a single page of videos."""
  1747. self.to_screen(u'%s: Downloading video information from %d to %d' %
  1748. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  1749. # Return count of items, list of *valid* items
  1750. def _parse_page(self, url, video_id):
  1751. webpage = self._download_webpage(url, video_id,
  1752. u'Downloading video info JSON',
  1753. u'unable to download video info JSON')
  1754. response = json.loads(webpage)
  1755. if type(response) != list:
  1756. error_text = response.get('error', 'unknown error')
  1757. raise ExtractorError(u'Justin.tv API: %s' % error_text)
  1758. info = []
  1759. for clip in response:
  1760. video_url = clip['video_file_url']
  1761. if video_url:
  1762. video_extension = os.path.splitext(video_url)[1][1:]
  1763. video_date = re.sub('-', '', clip['start_time'][:10])
  1764. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  1765. video_id = clip['id']
  1766. video_title = clip.get('title', video_id)
  1767. info.append({
  1768. 'id': video_id,
  1769. 'url': video_url,
  1770. 'title': video_title,
  1771. 'uploader': clip.get('channel_name', video_uploader_id),
  1772. 'uploader_id': video_uploader_id,
  1773. 'upload_date': video_date,
  1774. 'ext': video_extension,
  1775. })
  1776. return (len(response), info)
  1777. def _real_extract(self, url):
  1778. mobj = re.match(self._VALID_URL, url)
  1779. if mobj is None:
  1780. raise ExtractorError(u'invalid URL: %s' % url)
  1781. api_base = 'http://api.justin.tv'
  1782. paged = False
  1783. if mobj.group('channelid'):
  1784. paged = True
  1785. video_id = mobj.group('channelid')
  1786. api = api_base + '/channel/archives/%s.json' % video_id
  1787. elif mobj.group('chapterid'):
  1788. chapter_id = mobj.group('chapterid')
  1789. webpage = self._download_webpage(url, chapter_id)
  1790. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  1791. if not m:
  1792. raise ExtractorError(u'Cannot find archive of a chapter')
  1793. archive_id = m.group(1)
  1794. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  1795. chapter_info_xml = self._download_webpage(api, chapter_id,
  1796. note=u'Downloading chapter information',
  1797. errnote=u'Chapter information download failed')
  1798. doc = xml.etree.ElementTree.fromstring(chapter_info_xml)
  1799. for a in doc.findall('.//archive'):
  1800. if archive_id == a.find('./id').text:
  1801. break
  1802. else:
  1803. raise ExtractorError(u'Could not find chapter in chapter information')
  1804. video_url = a.find('./video_file_url').text
  1805. video_ext = video_url.rpartition('.')[2] or u'flv'
  1806. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  1807. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  1808. note='Downloading chapter metadata',
  1809. errnote='Download of chapter metadata failed')
  1810. chapter_info = json.loads(chapter_info_json)
  1811. bracket_start = int(doc.find('.//bracket_start').text)
  1812. bracket_end = int(doc.find('.//bracket_end').text)
  1813. # TODO determine start (and probably fix up file)
  1814. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  1815. #video_url += u'?start=' + TODO:start_timestamp
  1816. # bracket_start is 13290, but we want 51670615
  1817. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  1818. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  1819. info = {
  1820. 'id': u'c' + chapter_id,
  1821. 'url': video_url,
  1822. 'ext': video_ext,
  1823. 'title': chapter_info['title'],
  1824. 'thumbnail': chapter_info['preview'],
  1825. 'description': chapter_info['description'],
  1826. 'uploader': chapter_info['channel']['display_name'],
  1827. 'uploader_id': chapter_info['channel']['name'],
  1828. }
  1829. return [info]
  1830. else:
  1831. video_id = mobj.group('videoid')
  1832. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  1833. self.report_extraction(video_id)
  1834. info = []
  1835. offset = 0
  1836. limit = self._JUSTIN_PAGE_LIMIT
  1837. while True:
  1838. if paged:
  1839. self.report_download_page(video_id, offset)
  1840. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  1841. page_count, page_info = self._parse_page(page_url, video_id)
  1842. info.extend(page_info)
  1843. if not paged or page_count != limit:
  1844. break
  1845. offset += limit
  1846. return info
  1847. class FunnyOrDieIE(InfoExtractor):
  1848. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  1849. def _real_extract(self, url):
  1850. mobj = re.match(self._VALID_URL, url)
  1851. if mobj is None:
  1852. raise ExtractorError(u'invalid URL: %s' % url)
  1853. video_id = mobj.group('id')
  1854. webpage = self._download_webpage(url, video_id)
  1855. video_url = self._html_search_regex(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"',
  1856. webpage, u'video URL', flags=re.DOTALL)
  1857. title = self._html_search_regex((r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>",
  1858. r'<title>(?P<title>[^<]+?)</title>'), webpage, 'title', flags=re.DOTALL)
  1859. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  1860. webpage, u'description', fatal=False, flags=re.DOTALL)
  1861. info = {
  1862. 'id': video_id,
  1863. 'url': video_url,
  1864. 'ext': 'mp4',
  1865. 'title': title,
  1866. 'description': video_description,
  1867. }
  1868. return [info]
  1869. class SteamIE(InfoExtractor):
  1870. _VALID_URL = r"""http://store\.steampowered\.com/
  1871. (agecheck/)?
  1872. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  1873. (?P<gameID>\d+)/?
  1874. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  1875. """
  1876. _VIDEO_PAGE_TEMPLATE = 'http://store.steampowered.com/video/%s/'
  1877. _AGECHECK_TEMPLATE = 'http://store.steampowered.com/agecheck/video/%s/?snr=1_agecheck_agecheck__age-gate&ageDay=1&ageMonth=January&ageYear=1970'
  1878. @classmethod
  1879. def suitable(cls, url):
  1880. """Receives a URL and returns True if suitable for this IE."""
  1881. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1882. def _real_extract(self, url):
  1883. m = re.match(self._VALID_URL, url, re.VERBOSE)
  1884. gameID = m.group('gameID')
  1885. videourl = self._VIDEO_PAGE_TEMPLATE % gameID
  1886. webpage = self._download_webpage(videourl, gameID)
  1887. if re.search('<h2>Please enter your birth date to continue:</h2>', webpage) is not None:
  1888. videourl = self._AGECHECK_TEMPLATE % gameID
  1889. self.report_age_confirmation()
  1890. webpage = self._download_webpage(videourl, gameID)
  1891. self.report_extraction(gameID)
  1892. game_title = self._html_search_regex(r'<h2 class="pageheader">(.*?)</h2>',
  1893. webpage, 'game title')
  1894. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  1895. mweb = re.finditer(urlRE, webpage)
  1896. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  1897. titles = re.finditer(namesRE, webpage)
  1898. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  1899. thumbs = re.finditer(thumbsRE, webpage)
  1900. videos = []
  1901. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  1902. video_id = vid.group('videoID')
  1903. title = vtitle.group('videoName')
  1904. video_url = vid.group('videoURL')
  1905. video_thumb = thumb.group('thumbnail')
  1906. if not video_url:
  1907. raise ExtractorError(u'Cannot find video url for %s' % video_id)
  1908. info = {
  1909. 'id':video_id,
  1910. 'url':video_url,
  1911. 'ext': 'flv',
  1912. 'title': unescapeHTML(title),
  1913. 'thumbnail': video_thumb
  1914. }
  1915. videos.append(info)
  1916. return [self.playlist_result(videos, gameID, game_title)]
  1917. class UstreamIE(InfoExtractor):
  1918. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  1919. IE_NAME = u'ustream'
  1920. def _real_extract(self, url):
  1921. m = re.match(self._VALID_URL, url)
  1922. video_id = m.group('videoID')
  1923. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  1924. webpage = self._download_webpage(url, video_id)
  1925. self.report_extraction(video_id)
  1926. video_title = self._html_search_regex(r'data-title="(?P<title>.+)"',
  1927. webpage, u'title')
  1928. uploader = self._html_search_regex(r'data-content-type="channel".*?>(?P<uploader>.*?)</a>',
  1929. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  1930. thumbnail = self._html_search_regex(r'<link rel="image_src" href="(?P<thumb>.*?)"',
  1931. webpage, u'thumbnail', fatal=False)
  1932. info = {
  1933. 'id': video_id,
  1934. 'url': video_url,
  1935. 'ext': 'flv',
  1936. 'title': video_title,
  1937. 'uploader': uploader,
  1938. 'thumbnail': thumbnail,
  1939. }
  1940. return info
  1941. class WorldStarHipHopIE(InfoExtractor):
  1942. _VALID_URL = r'https?://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  1943. IE_NAME = u'WorldStarHipHop'
  1944. def _real_extract(self, url):
  1945. m = re.match(self._VALID_URL, url)
  1946. video_id = m.group('id')
  1947. webpage_src = self._download_webpage(url, video_id)
  1948. video_url = self._search_regex(r'so\.addVariable\("file","(.*?)"\)',
  1949. webpage_src, u'video URL')
  1950. if 'mp4' in video_url:
  1951. ext = 'mp4'
  1952. else:
  1953. ext = 'flv'
  1954. video_title = self._html_search_regex(r"<title>(.*)</title>",
  1955. webpage_src, u'title')
  1956. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  1957. thumbnail = self._html_search_regex(r'rel="image_src" href="(.*)" />',
  1958. webpage_src, u'thumbnail', fatal=False)
  1959. if not thumbnail:
  1960. _title = r"""candytitles.*>(.*)</span>"""
  1961. mobj = re.search(_title, webpage_src)
  1962. if mobj is not None:
  1963. video_title = mobj.group(1)
  1964. results = [{
  1965. 'id': video_id,
  1966. 'url' : video_url,
  1967. 'title' : video_title,
  1968. 'thumbnail' : thumbnail,
  1969. 'ext' : ext,
  1970. }]
  1971. return results
  1972. class RBMARadioIE(InfoExtractor):
  1973. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  1974. def _real_extract(self, url):
  1975. m = re.match(self._VALID_URL, url)
  1976. video_id = m.group('videoID')
  1977. webpage = self._download_webpage(url, video_id)
  1978. json_data = self._search_regex(r'window\.gon.*?gon\.show=(.+?);$',
  1979. webpage, u'json data', flags=re.MULTILINE)
  1980. try:
  1981. data = json.loads(json_data)
  1982. except ValueError as e:
  1983. raise ExtractorError(u'Invalid JSON: ' + str(e))
  1984. video_url = data['akamai_url'] + '&cbr=256'
  1985. url_parts = compat_urllib_parse_urlparse(video_url)
  1986. video_ext = url_parts.path.rpartition('.')[2]
  1987. info = {
  1988. 'id': video_id,
  1989. 'url': video_url,
  1990. 'ext': video_ext,
  1991. 'title': data['title'],
  1992. 'description': data.get('teaser_text'),
  1993. 'location': data.get('country_of_origin'),
  1994. 'uploader': data.get('host', {}).get('name'),
  1995. 'uploader_id': data.get('host', {}).get('slug'),
  1996. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  1997. 'duration': data.get('duration'),
  1998. }
  1999. return [info]
  2000. class YouPornIE(InfoExtractor):
  2001. """Information extractor for youporn.com."""
  2002. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  2003. def _print_formats(self, formats):
  2004. """Print all available formats"""
  2005. print(u'Available formats:')
  2006. print(u'ext\t\tformat')
  2007. print(u'---------------------------------')
  2008. for format in formats:
  2009. print(u'%s\t\t%s' % (format['ext'], format['format']))
  2010. def _specific(self, req_format, formats):
  2011. for x in formats:
  2012. if(x["format"]==req_format):
  2013. return x
  2014. return None
  2015. def _real_extract(self, url):
  2016. mobj = re.match(self._VALID_URL, url)
  2017. if mobj is None:
  2018. raise ExtractorError(u'Invalid URL: %s' % url)
  2019. video_id = mobj.group('videoid')
  2020. req = compat_urllib_request.Request(url)
  2021. req.add_header('Cookie', 'age_verified=1')
  2022. webpage = self._download_webpage(req, video_id)
  2023. # Get JSON parameters
  2024. json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
  2025. try:
  2026. params = json.loads(json_params)
  2027. except:
  2028. raise ExtractorError(u'Invalid JSON')
  2029. self.report_extraction(video_id)
  2030. try:
  2031. video_title = params['title']
  2032. upload_date = unified_strdate(params['release_date_f'])
  2033. video_description = params['description']
  2034. video_uploader = params['submitted_by']
  2035. thumbnail = params['thumbnails'][0]['image']
  2036. except KeyError:
  2037. raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
  2038. # Get all of the formats available
  2039. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  2040. download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
  2041. webpage, u'download list').strip()
  2042. # Get all of the links from the page
  2043. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  2044. links = re.findall(LINK_RE, download_list_html)
  2045. if(len(links) == 0):
  2046. raise ExtractorError(u'ERROR: no known formats available for video')
  2047. self.to_screen(u'Links found: %d' % len(links))
  2048. formats = []
  2049. for link in links:
  2050. # A link looks like this:
  2051. # 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
  2052. # A path looks like this:
  2053. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  2054. video_url = unescapeHTML( link )
  2055. path = compat_urllib_parse_urlparse( video_url ).path
  2056. extension = os.path.splitext( path )[1][1:]
  2057. format = path.split('/')[4].split('_')[:2]
  2058. size = format[0]
  2059. bitrate = format[1]
  2060. format = "-".join( format )
  2061. # title = u'%s-%s-%s' % (video_title, size, bitrate)
  2062. formats.append({
  2063. 'id': video_id,
  2064. 'url': video_url,
  2065. 'uploader': video_uploader,
  2066. 'upload_date': upload_date,
  2067. 'title': video_title,
  2068. 'ext': extension,
  2069. 'format': format,
  2070. 'thumbnail': thumbnail,
  2071. 'description': video_description
  2072. })
  2073. if self._downloader.params.get('listformats', None):
  2074. self._print_formats(formats)
  2075. return
  2076. req_format = self._downloader.params.get('format', None)
  2077. self.to_screen(u'Format: %s' % req_format)
  2078. if req_format is None or req_format == 'best':
  2079. return [formats[0]]
  2080. elif req_format == 'worst':
  2081. return [formats[-1]]
  2082. elif req_format in ('-1', 'all'):
  2083. return formats
  2084. else:
  2085. format = self._specific( req_format, formats )
  2086. if result is None:
  2087. raise ExtractorError(u'Requested format not available')
  2088. return [format]
  2089. class PornotubeIE(InfoExtractor):
  2090. """Information extractor for pornotube.com."""
  2091. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  2092. def _real_extract(self, url):
  2093. mobj = re.match(self._VALID_URL, url)
  2094. if mobj is None:
  2095. raise ExtractorError(u'Invalid URL: %s' % url)
  2096. video_id = mobj.group('videoid')
  2097. video_title = mobj.group('title')
  2098. # Get webpage content
  2099. webpage = self._download_webpage(url, video_id)
  2100. # Get the video URL
  2101. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  2102. video_url = self._search_regex(VIDEO_URL_RE, webpage, u'video url')
  2103. video_url = compat_urllib_parse.unquote(video_url)
  2104. #Get the uploaded date
  2105. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  2106. upload_date = self._html_search_regex(VIDEO_UPLOADED_RE, webpage, u'upload date', fatal=False)
  2107. if upload_date: upload_date = unified_strdate(upload_date)
  2108. info = {'id': video_id,
  2109. 'url': video_url,
  2110. 'uploader': None,
  2111. 'upload_date': upload_date,
  2112. 'title': video_title,
  2113. 'ext': 'flv',
  2114. 'format': 'flv'}
  2115. return [info]
  2116. class YouJizzIE(InfoExtractor):
  2117. """Information extractor for youjizz.com."""
  2118. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  2119. def _real_extract(self, url):
  2120. mobj = re.match(self._VALID_URL, url)
  2121. if mobj is None:
  2122. raise ExtractorError(u'Invalid URL: %s' % url)
  2123. video_id = mobj.group('videoid')
  2124. # Get webpage content
  2125. webpage = self._download_webpage(url, video_id)
  2126. # Get the video title
  2127. video_title = self._html_search_regex(r'<title>(?P<title>.*)</title>',
  2128. webpage, u'title').strip()
  2129. # Get the embed page
  2130. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  2131. if result is None:
  2132. raise ExtractorError(u'ERROR: unable to extract embed page')
  2133. embed_page_url = result.group(0).strip()
  2134. video_id = result.group('videoid')
  2135. webpage = self._download_webpage(embed_page_url, video_id)
  2136. # Get the video URL
  2137. video_url = self._search_regex(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);',
  2138. webpage, u'video URL')
  2139. info = {'id': video_id,
  2140. 'url': video_url,
  2141. 'title': video_title,
  2142. 'ext': 'flv',
  2143. 'format': 'flv',
  2144. 'player_url': embed_page_url}
  2145. return [info]
  2146. class EightTracksIE(InfoExtractor):
  2147. IE_NAME = '8tracks'
  2148. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  2149. def _real_extract(self, url):
  2150. mobj = re.match(self._VALID_URL, url)
  2151. if mobj is None:
  2152. raise ExtractorError(u'Invalid URL: %s' % url)
  2153. playlist_id = mobj.group('id')
  2154. webpage = self._download_webpage(url, playlist_id)
  2155. json_like = self._search_regex(r"PAGE.mix = (.*?);\n", webpage, u'trax information', flags=re.DOTALL)
  2156. data = json.loads(json_like)
  2157. session = str(random.randint(0, 1000000000))
  2158. mix_id = data['id']
  2159. track_count = data['tracks_count']
  2160. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  2161. next_url = first_url
  2162. res = []
  2163. for i in itertools.count():
  2164. api_json = self._download_webpage(next_url, playlist_id,
  2165. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  2166. errnote=u'Failed to download song information')
  2167. api_data = json.loads(api_json)
  2168. track_data = api_data[u'set']['track']
  2169. info = {
  2170. 'id': track_data['id'],
  2171. 'url': track_data['track_file_stream_url'],
  2172. 'title': track_data['performer'] + u' - ' + track_data['name'],
  2173. 'raw_title': track_data['name'],
  2174. 'uploader_id': data['user']['login'],
  2175. 'ext': 'm4a',
  2176. }
  2177. res.append(info)
  2178. if api_data['set']['at_last_track']:
  2179. break
  2180. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  2181. return res
  2182. class KeekIE(InfoExtractor):
  2183. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  2184. IE_NAME = u'keek'
  2185. def _real_extract(self, url):
  2186. m = re.match(self._VALID_URL, url)
  2187. video_id = m.group('videoID')
  2188. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  2189. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  2190. webpage = self._download_webpage(url, video_id)
  2191. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  2192. webpage, u'title')
  2193. uploader = self._html_search_regex(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>',
  2194. webpage, u'uploader', fatal=False)
  2195. info = {
  2196. 'id': video_id,
  2197. 'url': video_url,
  2198. 'ext': 'mp4',
  2199. 'title': video_title,
  2200. 'thumbnail': thumbnail,
  2201. 'uploader': uploader
  2202. }
  2203. return [info]
  2204. class TEDIE(InfoExtractor):
  2205. _VALID_URL=r'''http://www\.ted\.com/
  2206. (
  2207. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  2208. |
  2209. ((?P<type_talk>talks)) # We have a simple talk
  2210. )
  2211. (/lang/(.*?))? # The url may contain the language
  2212. /(?P<name>\w+) # Here goes the name and then ".html"
  2213. '''
  2214. @classmethod
  2215. def suitable(cls, url):
  2216. """Receives a URL and returns True if suitable for this IE."""
  2217. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  2218. def _real_extract(self, url):
  2219. m=re.match(self._VALID_URL, url, re.VERBOSE)
  2220. if m.group('type_talk'):
  2221. return [self._talk_info(url)]
  2222. else :
  2223. playlist_id=m.group('playlist_id')
  2224. name=m.group('name')
  2225. self.to_screen(u'Getting info of playlist %s: "%s"' % (playlist_id,name))
  2226. return [self._playlist_videos_info(url,name,playlist_id)]
  2227. def _playlist_videos_info(self,url,name,playlist_id=0):
  2228. '''Returns the videos of the playlist'''
  2229. video_RE=r'''
  2230. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  2231. ([.\s]*?)data-playlist_item_id="(\d+)"
  2232. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  2233. '''
  2234. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  2235. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  2236. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  2237. m_names=re.finditer(video_name_RE,webpage)
  2238. playlist_title = self._html_search_regex(r'div class="headline">\s*?<h1>\s*?<span>(.*?)</span>',
  2239. webpage, 'playlist title')
  2240. playlist_entries = []
  2241. for m_video, m_name in zip(m_videos,m_names):
  2242. video_id=m_video.group('video_id')
  2243. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  2244. playlist_entries.append(self.url_result(talk_url, 'TED'))
  2245. return self.playlist_result(playlist_entries, playlist_id = playlist_id, playlist_title = playlist_title)
  2246. def _talk_info(self, url, video_id=0):
  2247. """Return the video for the talk in the url"""
  2248. m = re.match(self._VALID_URL, url,re.VERBOSE)
  2249. video_name = m.group('name')
  2250. webpage = self._download_webpage(url, video_id, 'Downloading \"%s\" page' % video_name)
  2251. self.report_extraction(video_name)
  2252. # If the url includes the language we get the title translated
  2253. title = self._html_search_regex(r'<span id="altHeadline" >(?P<title>.*)</span>',
  2254. webpage, 'title')
  2255. json_data = self._search_regex(r'<script.*?>var talkDetails = ({.*?})</script>',
  2256. webpage, 'json data')
  2257. info = json.loads(json_data)
  2258. desc = self._html_search_regex(r'<div class="talk-intro">.*?<p.*?>(.*?)</p>',
  2259. webpage, 'description', flags = re.DOTALL)
  2260. thumbnail = self._search_regex(r'</span>[\s.]*</div>[\s.]*<img src="(.*?)"',
  2261. webpage, 'thumbnail')
  2262. info = {
  2263. 'id': info['id'],
  2264. 'url': info['htmlStreams'][-1]['file'],
  2265. 'ext': 'mp4',
  2266. 'title': title,
  2267. 'thumbnail': thumbnail,
  2268. 'description': desc,
  2269. }
  2270. return info
  2271. class MySpassIE(InfoExtractor):
  2272. _VALID_URL = r'http://www.myspass.de/.*'
  2273. def _real_extract(self, url):
  2274. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  2275. # video id is the last path element of the URL
  2276. # usually there is a trailing slash, so also try the second but last
  2277. url_path = compat_urllib_parse_urlparse(url).path
  2278. url_parent_path, video_id = os.path.split(url_path)
  2279. if not video_id:
  2280. _, video_id = os.path.split(url_parent_path)
  2281. # get metadata
  2282. metadata_url = META_DATA_URL_TEMPLATE % video_id
  2283. metadata_text = self._download_webpage(metadata_url, video_id)
  2284. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  2285. # extract values from metadata
  2286. url_flv_el = metadata.find('url_flv')
  2287. if url_flv_el is None:
  2288. raise ExtractorError(u'Unable to extract download url')
  2289. video_url = url_flv_el.text
  2290. extension = os.path.splitext(video_url)[1][1:]
  2291. title_el = metadata.find('title')
  2292. if title_el is None:
  2293. raise ExtractorError(u'Unable to extract title')
  2294. title = title_el.text
  2295. format_id_el = metadata.find('format_id')
  2296. if format_id_el is None:
  2297. format = ext
  2298. else:
  2299. format = format_id_el.text
  2300. description_el = metadata.find('description')
  2301. if description_el is not None:
  2302. description = description_el.text
  2303. else:
  2304. description = None
  2305. imagePreview_el = metadata.find('imagePreview')
  2306. if imagePreview_el is not None:
  2307. thumbnail = imagePreview_el.text
  2308. else:
  2309. thumbnail = None
  2310. info = {
  2311. 'id': video_id,
  2312. 'url': video_url,
  2313. 'title': title,
  2314. 'ext': extension,
  2315. 'format': format,
  2316. 'thumbnail': thumbnail,
  2317. 'description': description
  2318. }
  2319. return [info]
  2320. class SpiegelIE(InfoExtractor):
  2321. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  2322. def _real_extract(self, url):
  2323. m = re.match(self._VALID_URL, url)
  2324. video_id = m.group('videoID')
  2325. webpage = self._download_webpage(url, video_id)
  2326. video_title = self._html_search_regex(r'<div class="module-title">(.*?)</div>',
  2327. webpage, u'title')
  2328. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  2329. xml_code = self._download_webpage(xml_url, video_id,
  2330. note=u'Downloading XML', errnote=u'Failed to download XML')
  2331. idoc = xml.etree.ElementTree.fromstring(xml_code)
  2332. last_type = idoc[-1]
  2333. filename = last_type.findall('./filename')[0].text
  2334. duration = float(last_type.findall('./duration')[0].text)
  2335. video_url = 'http://video2.spiegel.de/flash/' + filename
  2336. video_ext = filename.rpartition('.')[2]
  2337. info = {
  2338. 'id': video_id,
  2339. 'url': video_url,
  2340. 'ext': video_ext,
  2341. 'title': video_title,
  2342. 'duration': duration,
  2343. }
  2344. return [info]
  2345. class LiveLeakIE(InfoExtractor):
  2346. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  2347. IE_NAME = u'liveleak'
  2348. def _real_extract(self, url):
  2349. mobj = re.match(self._VALID_URL, url)
  2350. if mobj is None:
  2351. raise ExtractorError(u'Invalid URL: %s' % url)
  2352. video_id = mobj.group('video_id')
  2353. webpage = self._download_webpage(url, video_id)
  2354. video_url = self._search_regex(r'file: "(.*?)",',
  2355. webpage, u'video URL')
  2356. video_title = self._html_search_regex(r'<meta property="og:title" content="(?P<title>.*?)"',
  2357. webpage, u'title').replace('LiveLeak.com -', '').strip()
  2358. video_description = self._html_search_regex(r'<meta property="og:description" content="(?P<desc>.*?)"',
  2359. webpage, u'description', fatal=False)
  2360. video_uploader = self._html_search_regex(r'By:.*?(\w+)</a>',
  2361. webpage, u'uploader', fatal=False)
  2362. info = {
  2363. 'id': video_id,
  2364. 'url': video_url,
  2365. 'ext': 'mp4',
  2366. 'title': video_title,
  2367. 'description': video_description,
  2368. 'uploader': video_uploader
  2369. }
  2370. return [info]
  2371. class ARDIE(InfoExtractor):
  2372. _VALID_URL = r'^(?:https?://)?(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[^/\?]+)(?:\?.*)?'
  2373. _TITLE = r'<h1(?: class="boxTopHeadline")?>(?P<title>.*)</h1>'
  2374. _MEDIA_STREAM = r'mediaCollection\.addMediaStream\((?P<media_type>\d+), (?P<quality>\d+), "(?P<rtmp_url>[^"]*)", "(?P<video_url>[^"]*)", "[^"]*"\)'
  2375. def _real_extract(self, url):
  2376. # determine video id from url
  2377. m = re.match(self._VALID_URL, url)
  2378. numid = re.search(r'documentId=([0-9]+)', url)
  2379. if numid:
  2380. video_id = numid.group(1)
  2381. else:
  2382. video_id = m.group('video_id')
  2383. # determine title and media streams from webpage
  2384. html = self._download_webpage(url, video_id)
  2385. title = re.search(self._TITLE, html).group('title')
  2386. streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
  2387. if not streams:
  2388. assert '"fsk"' in html
  2389. raise ExtractorError(u'This video is only available after 8:00 pm')
  2390. # choose default media type and highest quality for now
  2391. stream = max([s for s in streams if int(s["media_type"]) == 0],
  2392. key=lambda s: int(s["quality"]))
  2393. # there's two possibilities: RTMP stream or HTTP download
  2394. info = {'id': video_id, 'title': title, 'ext': 'mp4'}
  2395. if stream['rtmp_url']:
  2396. self.to_screen(u'RTMP download detected')
  2397. assert stream['video_url'].startswith('mp4:')
  2398. info["url"] = stream["rtmp_url"]
  2399. info["play_path"] = stream['video_url']
  2400. else:
  2401. assert stream["video_url"].endswith('.mp4')
  2402. info["url"] = stream["video_url"]
  2403. return [info]
  2404. class ZDFIE(InfoExtractor):
  2405. _VALID_URL = r'^http://www\.zdf\.de\/ZDFmediathek\/(.*beitrag\/video\/)(?P<video_id>[^/\?]+)(?:\?.*)?'
  2406. _TITLE = r'<h1(?: class="beitragHeadline")?>(?P<title>.*)</h1>'
  2407. _MEDIA_STREAM = r'<a href="(?P<video_url>.+(?P<media_type>.streaming).+/zdf/(?P<quality>[^\/]+)/[^"]*)".+class="play".+>'
  2408. _MMS_STREAM = r'href="(?P<video_url>mms://[^"]*)"'
  2409. _RTSP_STREAM = r'(?P<video_url>rtsp://[^"]*.mp4)'
  2410. def _real_extract(self, url):
  2411. mobj = re.match(self._VALID_URL, url)
  2412. if mobj is None:
  2413. raise ExtractorError(u'Invalid URL: %s' % url)
  2414. video_id = mobj.group('video_id')
  2415. html = self._download_webpage(url, video_id)
  2416. streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
  2417. if streams is None:
  2418. raise ExtractorError(u'No media url found.')
  2419. # s['media_type'] == 'wstreaming' -> use 'Windows Media Player' and mms url
  2420. # s['media_type'] == 'hstreaming' -> use 'Quicktime' and rtsp url
  2421. # choose first/default media type and highest quality for now
  2422. for s in streams: #find 300 - dsl1000mbit
  2423. if s['quality'] == '300' and s['media_type'] == 'wstreaming':
  2424. stream_=s
  2425. break
  2426. for s in streams: #find veryhigh - dsl2000mbit
  2427. if s['quality'] == 'veryhigh' and s['media_type'] == 'wstreaming': # 'hstreaming' - rtsp is not working
  2428. stream_=s
  2429. break
  2430. if stream_ is None:
  2431. raise ExtractorError(u'No stream found.')
  2432. media_link = self._download_webpage(stream_['video_url'], video_id,'Get stream URL')
  2433. self.report_extraction(video_id)
  2434. mobj = re.search(self._TITLE, html)
  2435. if mobj is None:
  2436. raise ExtractorError(u'Cannot extract title')
  2437. title = unescapeHTML(mobj.group('title'))
  2438. mobj = re.search(self._MMS_STREAM, media_link)
  2439. if mobj is None:
  2440. mobj = re.search(self._RTSP_STREAM, media_link)
  2441. if mobj is None:
  2442. raise ExtractorError(u'Cannot extract mms:// or rtsp:// URL')
  2443. mms_url = mobj.group('video_url')
  2444. mobj = re.search('(.*)[.](?P<ext>[^.]+)', mms_url)
  2445. if mobj is None:
  2446. raise ExtractorError(u'Cannot extract extention')
  2447. ext = mobj.group('ext')
  2448. return [{'id': video_id,
  2449. 'url': mms_url,
  2450. 'title': title,
  2451. 'ext': ext
  2452. }]
  2453. class TumblrIE(InfoExtractor):
  2454. _VALID_URL = r'http://(?P<blog_name>.*?)\.tumblr\.com/((post)|(video))/(?P<id>\d*)/(.*?)'
  2455. def _real_extract(self, url):
  2456. m_url = re.match(self._VALID_URL, url)
  2457. video_id = m_url.group('id')
  2458. blog = m_url.group('blog_name')
  2459. url = 'http://%s.tumblr.com/post/%s/' % (blog, video_id)
  2460. webpage = self._download_webpage(url, video_id)
  2461. re_video = r'src=\\x22(?P<video_url>http://%s\.tumblr\.com/video_file/%s/(.*?))\\x22 type=\\x22video/(?P<ext>.*?)\\x22' % (blog, video_id)
  2462. video = re.search(re_video, webpage)
  2463. if video is None:
  2464. raise ExtractorError(u'Unable to extract video')
  2465. video_url = video.group('video_url')
  2466. ext = video.group('ext')
  2467. video_thumbnail = self._search_regex(r'posters(.*?)\[\\x22(?P<thumb>.*?)\\x22',
  2468. webpage, u'thumbnail', fatal=False) # We pick the first poster
  2469. if video_thumbnail: video_thumbnail = video_thumbnail.replace('\\', '')
  2470. # The only place where you can get a title, it's not complete,
  2471. # but searching in other places doesn't work for all videos
  2472. video_title = self._html_search_regex(r'<title>(?P<title>.*?)</title>',
  2473. webpage, u'title', flags=re.DOTALL)
  2474. return [{'id': video_id,
  2475. 'url': video_url,
  2476. 'title': video_title,
  2477. 'thumbnail': video_thumbnail,
  2478. 'ext': ext
  2479. }]
  2480. class BandcampIE(InfoExtractor):
  2481. _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
  2482. def _real_extract(self, url):
  2483. mobj = re.match(self._VALID_URL, url)
  2484. title = mobj.group('title')
  2485. webpage = self._download_webpage(url, title)
  2486. # We get the link to the free download page
  2487. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  2488. if m_download is None:
  2489. raise ExtractorError(u'No free songs found')
  2490. download_link = m_download.group(1)
  2491. id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
  2492. webpage, re.MULTILINE|re.DOTALL).group('id')
  2493. download_webpage = self._download_webpage(download_link, id,
  2494. 'Downloading free downloads page')
  2495. # We get the dictionary of the track from some javascrip code
  2496. info = re.search(r'items: (.*?),$',
  2497. download_webpage, re.MULTILINE).group(1)
  2498. info = json.loads(info)[0]
  2499. # We pick mp3-320 for now, until format selection can be easily implemented.
  2500. mp3_info = info[u'downloads'][u'mp3-320']
  2501. # If we try to use this url it says the link has expired
  2502. initial_url = mp3_info[u'url']
  2503. re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
  2504. m_url = re.match(re_url, initial_url)
  2505. #We build the url we will use to get the final track url
  2506. # This url is build in Bandcamp in the script download_bunde_*.js
  2507. request_url = '%s/statdownload/track?enc=mp3-320&fsig=%s&id=%s&ts=%s&.rand=665028774616&.vrs=1' % (m_url.group('server'), m_url.group('fsig'), id, m_url.group('ts'))
  2508. final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
  2509. # If we could correctly generate the .rand field the url would be
  2510. #in the "download_url" key
  2511. final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
  2512. track_info = {'id':id,
  2513. 'title' : info[u'title'],
  2514. 'ext' : 'mp3',
  2515. 'url' : final_url,
  2516. 'thumbnail' : info[u'thumb_url'],
  2517. 'uploader' : info[u'artist']
  2518. }
  2519. return [track_info]
  2520. class RedTubeIE(InfoExtractor):
  2521. """Information Extractor for redtube"""
  2522. _VALID_URL = r'(?:http://)?(?:www\.)?redtube\.com/(?P<id>[0-9]+)'
  2523. def _real_extract(self,url):
  2524. mobj = re.match(self._VALID_URL, url)
  2525. if mobj is None:
  2526. raise ExtractorError(u'Invalid URL: %s' % url)
  2527. video_id = mobj.group('id')
  2528. video_extension = 'mp4'
  2529. webpage = self._download_webpage(url, video_id)
  2530. self.report_extraction(video_id)
  2531. video_url = self._html_search_regex(r'<source src="(.+?)" type="video/mp4">',
  2532. webpage, u'video URL')
  2533. video_title = self._html_search_regex('<h1 class="videoTitle slidePanelMovable">(.+?)</h1>',
  2534. webpage, u'title')
  2535. return [{
  2536. 'id': video_id,
  2537. 'url': video_url,
  2538. 'ext': video_extension,
  2539. 'title': video_title,
  2540. }]
  2541. class InaIE(InfoExtractor):
  2542. """Information Extractor for Ina.fr"""
  2543. _VALID_URL = r'(?:http://)?(?:www\.)?ina\.fr/video/(?P<id>I[0-9]+)/.*'
  2544. def _real_extract(self,url):
  2545. mobj = re.match(self._VALID_URL, url)
  2546. video_id = mobj.group('id')
  2547. mrss_url='http://player.ina.fr/notices/%s.mrss' % video_id
  2548. video_extension = 'mp4'
  2549. webpage = self._download_webpage(mrss_url, video_id)
  2550. self.report_extraction(video_id)
  2551. video_url = self._html_search_regex(r'<media:player url="(?P<mp4url>http://mp4.ina.fr/[^"]+\.mp4)',
  2552. webpage, u'video URL')
  2553. video_title = self._search_regex(r'<title><!\[CDATA\[(?P<titre>.*?)]]></title>',
  2554. webpage, u'title')
  2555. return [{
  2556. 'id': video_id,
  2557. 'url': video_url,
  2558. 'ext': video_extension,
  2559. 'title': video_title,
  2560. }]
  2561. class HowcastIE(InfoExtractor):
  2562. """Information Extractor for Howcast.com"""
  2563. _VALID_URL = r'(?:https?://)?(?:www\.)?howcast\.com/videos/(?P<id>\d+)'
  2564. def _real_extract(self, url):
  2565. mobj = re.match(self._VALID_URL, url)
  2566. video_id = mobj.group('id')
  2567. webpage_url = 'http://www.howcast.com/videos/' + video_id
  2568. webpage = self._download_webpage(webpage_url, video_id)
  2569. self.report_extraction(video_id)
  2570. video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)',
  2571. webpage, u'video URL')
  2572. video_title = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') property=\'og:title\'',
  2573. webpage, u'title')
  2574. video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'',
  2575. webpage, u'description', fatal=False)
  2576. thumbnail = self._html_search_regex(r'<meta content=\'(.+?)\' property=\'og:image\'',
  2577. webpage, u'thumbnail', fatal=False)
  2578. return [{
  2579. 'id': video_id,
  2580. 'url': video_url,
  2581. 'ext': 'mp4',
  2582. 'title': video_title,
  2583. 'description': video_description,
  2584. 'thumbnail': thumbnail,
  2585. }]
  2586. class VineIE(InfoExtractor):
  2587. """Information Extractor for Vine.co"""
  2588. _VALID_URL = r'(?:https?://)?(?:www\.)?vine\.co/v/(?P<id>\w+)'
  2589. def _real_extract(self, url):
  2590. mobj = re.match(self._VALID_URL, url)
  2591. video_id = mobj.group('id')
  2592. webpage_url = 'https://vine.co/v/' + video_id
  2593. webpage = self._download_webpage(webpage_url, video_id)
  2594. self.report_extraction(video_id)
  2595. video_url = self._html_search_regex(r'<meta property="twitter:player:stream" content="(.+?)"',
  2596. webpage, u'video URL')
  2597. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  2598. webpage, u'title')
  2599. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)(\?.*?)?"',
  2600. webpage, u'thumbnail', fatal=False)
  2601. uploader = self._html_search_regex(r'<div class="user">.*?<h2>(.+?)</h2>',
  2602. webpage, u'uploader', fatal=False, flags=re.DOTALL)
  2603. return [{
  2604. 'id': video_id,
  2605. 'url': video_url,
  2606. 'ext': 'mp4',
  2607. 'title': video_title,
  2608. 'thumbnail': thumbnail,
  2609. 'uploader': uploader,
  2610. }]
  2611. class FlickrIE(InfoExtractor):
  2612. """Information Extractor for Flickr videos"""
  2613. _VALID_URL = r'(?:https?://)?(?:www\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
  2614. def _real_extract(self, url):
  2615. mobj = re.match(self._VALID_URL, url)
  2616. video_id = mobj.group('id')
  2617. video_uploader_id = mobj.group('uploader_id')
  2618. webpage_url = 'http://www.flickr.com/photos/' + video_uploader_id + '/' + video_id
  2619. webpage = self._download_webpage(webpage_url, video_id)
  2620. secret = self._search_regex(r"photo_secret: '(\w+)'", webpage, u'secret')
  2621. first_url = 'https://secure.flickr.com/apps/video/video_mtl_xml.gne?v=x&photo_id=' + video_id + '&secret=' + secret + '&bitrate=700&target=_self'
  2622. first_xml = self._download_webpage(first_url, video_id, 'Downloading first data webpage')
  2623. node_id = self._html_search_regex(r'<Item id="id">(\d+-\d+)</Item>',
  2624. first_xml, u'node_id')
  2625. second_url = 'https://secure.flickr.com/video_playlist.gne?node_id=' + node_id + '&tech=flash&mode=playlist&bitrate=700&secret=' + secret + '&rd=video.yahoo.com&noad=1'
  2626. second_xml = self._download_webpage(second_url, video_id, 'Downloading second data webpage')
  2627. self.report_extraction(video_id)
  2628. mobj = re.search(r'<STREAM APP="(.+?)" FULLPATH="(.+?)"', second_xml)
  2629. if mobj is None:
  2630. raise ExtractorError(u'Unable to extract video url')
  2631. video_url = mobj.group(1) + unescapeHTML(mobj.group(2))
  2632. video_title = self._html_search_regex(r'<meta property="og:title" content=(?:"([^"]+)"|\'([^\']+)\')',
  2633. webpage, u'video title')
  2634. video_description = self._html_search_regex(r'<meta property="og:description" content=(?:"([^"]+)"|\'([^\']+)\')',
  2635. webpage, u'description', fatal=False)
  2636. thumbnail = self._html_search_regex(r'<meta property="og:image" content=(?:"([^"]+)"|\'([^\']+)\')',
  2637. webpage, u'thumbnail', fatal=False)
  2638. return [{
  2639. 'id': video_id,
  2640. 'url': video_url,
  2641. 'ext': 'mp4',
  2642. 'title': video_title,
  2643. 'description': video_description,
  2644. 'thumbnail': thumbnail,
  2645. 'uploader_id': video_uploader_id,
  2646. }]
  2647. class TeamcocoIE(InfoExtractor):
  2648. _VALID_URL = r'http://teamcoco\.com/video/(?P<url_title>.*)'
  2649. def _real_extract(self, url):
  2650. mobj = re.match(self._VALID_URL, url)
  2651. if mobj is None:
  2652. raise ExtractorError(u'Invalid URL: %s' % url)
  2653. url_title = mobj.group('url_title')
  2654. webpage = self._download_webpage(url, url_title)
  2655. video_id = self._html_search_regex(r'<article class="video" data-id="(\d+?)"',
  2656. webpage, u'video id')
  2657. self.report_extraction(video_id)
  2658. video_title = self._html_search_regex(r'<meta property="og:title" content="(.+?)"',
  2659. webpage, u'title')
  2660. thumbnail = self._html_search_regex(r'<meta property="og:image" content="(.+?)"',
  2661. webpage, u'thumbnail', fatal=False)
  2662. video_description = self._html_search_regex(r'<meta property="og:description" content="(.*?)"',
  2663. webpage, u'description', fatal=False)
  2664. data_url = 'http://teamcoco.com/cvp/2.0/%s.xml' % video_id
  2665. data = self._download_webpage(data_url, video_id, 'Downloading data webpage')
  2666. video_url = self._html_search_regex(r'<file type="high".*?>(.*?)</file>',
  2667. data, u'video URL')
  2668. return [{
  2669. 'id': video_id,
  2670. 'url': video_url,
  2671. 'ext': 'mp4',
  2672. 'title': video_title,
  2673. 'thumbnail': thumbnail,
  2674. 'description': video_description,
  2675. }]
  2676. class XHamsterIE(InfoExtractor):
  2677. """Information Extractor for xHamster"""
  2678. _VALID_URL = r'(?:http://)?(?:www.)?xhamster\.com/movies/(?P<id>[0-9]+)/.*\.html'
  2679. def _real_extract(self,url):
  2680. mobj = re.match(self._VALID_URL, url)
  2681. video_id = mobj.group('id')
  2682. mrss_url = 'http://xhamster.com/movies/%s/.html' % video_id
  2683. webpage = self._download_webpage(mrss_url, video_id)
  2684. mobj = re.search(r'\'srv\': \'(?P<server>[^\']*)\',\s*\'file\': \'(?P<file>[^\']+)\',', webpage)
  2685. if mobj is None:
  2686. raise ExtractorError(u'Unable to extract media URL')
  2687. if len(mobj.group('server')) == 0:
  2688. video_url = compat_urllib_parse.unquote(mobj.group('file'))
  2689. else:
  2690. video_url = mobj.group('server')+'/key='+mobj.group('file')
  2691. video_extension = video_url.split('.')[-1]
  2692. video_title = self._html_search_regex(r'<title>(?P<title>.+?) - xHamster\.com</title>',
  2693. webpage, u'title')
  2694. # Can't see the description anywhere in the UI
  2695. # video_description = self._html_search_regex(r'<span>Description: </span>(?P<description>[^<]+)',
  2696. # webpage, u'description', fatal=False)
  2697. # if video_description: video_description = unescapeHTML(video_description)
  2698. mobj = re.search(r'hint=\'(?P<upload_date_Y>[0-9]{4})-(?P<upload_date_m>[0-9]{2})-(?P<upload_date_d>[0-9]{2}) [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Z]{3,4}\'', webpage)
  2699. if mobj:
  2700. video_upload_date = mobj.group('upload_date_Y')+mobj.group('upload_date_m')+mobj.group('upload_date_d')
  2701. else:
  2702. video_upload_date = None
  2703. self._downloader.report_warning(u'Unable to extract upload date')
  2704. video_uploader_id = self._html_search_regex(r'<a href=\'/user/[^>]+>(?P<uploader_id>[^<]+)',
  2705. webpage, u'uploader id', default=u'anonymous')
  2706. video_thumbnail = self._search_regex(r'\'image\':\'(?P<thumbnail>[^\']+)\'',
  2707. webpage, u'thumbnail', fatal=False)
  2708. return [{
  2709. 'id': video_id,
  2710. 'url': video_url,
  2711. 'ext': video_extension,
  2712. 'title': video_title,
  2713. # 'description': video_description,
  2714. 'upload_date': video_upload_date,
  2715. 'uploader_id': video_uploader_id,
  2716. 'thumbnail': video_thumbnail
  2717. }]
  2718. class HypemIE(InfoExtractor):
  2719. """Information Extractor for hypem"""
  2720. _VALID_URL = r'(?:http://)?(?:www\.)?hypem\.com/track/([^/]+)/([^/]+)'
  2721. def _real_extract(self, url):
  2722. mobj = re.match(self._VALID_URL, url)
  2723. if mobj is None:
  2724. raise ExtractorError(u'Invalid URL: %s' % url)
  2725. track_id = mobj.group(1)
  2726. data = { 'ax': 1, 'ts': time.time() }
  2727. data_encoded = compat_urllib_parse.urlencode(data)
  2728. complete_url = url + "?" + data_encoded
  2729. request = compat_urllib_request.Request(complete_url)
  2730. response, urlh = self._download_webpage_handle(request, track_id, u'Downloading webpage with the url')
  2731. cookie = urlh.headers.get('Set-Cookie', '')
  2732. self.report_extraction(track_id)
  2733. html_tracks = self._html_search_regex(r'<script type="application/json" id="displayList-data">(.*?)</script>',
  2734. response, u'tracks', flags=re.MULTILINE|re.DOTALL).strip()
  2735. try:
  2736. track_list = json.loads(html_tracks)
  2737. track = track_list[u'tracks'][0]
  2738. except ValueError:
  2739. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  2740. key = track[u"key"]
  2741. track_id = track[u"id"]
  2742. artist = track[u"artist"]
  2743. title = track[u"song"]
  2744. serve_url = "http://hypem.com/serve/source/%s/%s" % (compat_str(track_id), compat_str(key))
  2745. request = compat_urllib_request.Request(serve_url, "" , {'Content-Type': 'application/json'})
  2746. request.add_header('cookie', cookie)
  2747. song_data_json = self._download_webpage(request, track_id, u'Downloading metadata')
  2748. try:
  2749. song_data = json.loads(song_data_json)
  2750. except ValueError:
  2751. raise ExtractorError(u'Hypemachine contained invalid JSON.')
  2752. final_url = song_data[u"url"]
  2753. return [{
  2754. 'id': track_id,
  2755. 'url': final_url,
  2756. 'ext': "mp3",
  2757. 'title': title,
  2758. 'artist': artist,
  2759. }]
  2760. class Vbox7IE(InfoExtractor):
  2761. """Information Extractor for Vbox7"""
  2762. _VALID_URL = r'(?:http://)?(?:www\.)?vbox7\.com/play:([^/]+)'
  2763. def _real_extract(self,url):
  2764. mobj = re.match(self._VALID_URL, url)
  2765. if mobj is None:
  2766. raise ExtractorError(u'Invalid URL: %s' % url)
  2767. video_id = mobj.group(1)
  2768. redirect_page, urlh = self._download_webpage_handle(url, video_id)
  2769. new_location = self._search_regex(r'window\.location = \'(.*)\';', redirect_page, u'redirect location')
  2770. redirect_url = urlh.geturl() + new_location
  2771. webpage = self._download_webpage(redirect_url, video_id, u'Downloading redirect page')
  2772. title = self._html_search_regex(r'<title>(.*)</title>',
  2773. webpage, u'title').split('/')[0].strip()
  2774. ext = "flv"
  2775. info_url = "http://vbox7.com/play/magare.do"
  2776. data = compat_urllib_parse.urlencode({'as3':'1','vid':video_id})
  2777. info_request = compat_urllib_request.Request(info_url, data)
  2778. info_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  2779. info_response = self._download_webpage(info_request, video_id, u'Downloading info webpage')
  2780. if info_response is None:
  2781. raise ExtractorError(u'Unable to extract the media url')
  2782. (final_url, thumbnail_url) = map(lambda x: x.split('=')[1], info_response.split('&'))
  2783. return [{
  2784. 'id': video_id,
  2785. 'url': final_url,
  2786. 'ext': ext,
  2787. 'title': title,
  2788. 'thumbnail': thumbnail_url,
  2789. }]
  2790. class GametrailersIE(InfoExtractor):
  2791. _VALID_URL = r'http://www.gametrailers.com/(?P<type>videos|reviews|full-episodes)/(?P<id>.*?)/(?P<title>.*)'
  2792. def _real_extract(self, url):
  2793. mobj = re.match(self._VALID_URL, url)
  2794. if mobj is None:
  2795. raise ExtractorError(u'Invalid URL: %s' % url)
  2796. video_id = mobj.group('id')
  2797. video_type = mobj.group('type')
  2798. webpage = self._download_webpage(url, video_id)
  2799. if video_type == 'full-episodes':
  2800. mgid_re = r'data-video="(?P<mgid>mgid:.*?)"'
  2801. else:
  2802. mgid_re = r'data-contentId=\'(?P<mgid>mgid:.*?)\''
  2803. mgid = self._search_regex(mgid_re, webpage, u'mgid')
  2804. data = compat_urllib_parse.urlencode({'uri': mgid, 'acceptMethods': 'fms'})
  2805. info_page = self._download_webpage('http://www.gametrailers.com/feeds/mrss?' + data,
  2806. video_id, u'Downloading video info')
  2807. links_webpage = self._download_webpage('http://www.gametrailers.com/feeds/mediagen/?' + data,
  2808. video_id, u'Downloading video urls info')
  2809. self.report_extraction(video_id)
  2810. info_re = r'''<title><!\[CDATA\[(?P<title>.*?)\]\]></title>.*
  2811. <description><!\[CDATA\[(?P<description>.*?)\]\]></description>.*
  2812. <image>.*
  2813. <url>(?P<thumb>.*?)</url>.*
  2814. </image>'''
  2815. m_info = re.search(info_re, info_page, re.VERBOSE|re.DOTALL)
  2816. if m_info is None:
  2817. raise ExtractorError(u'Unable to extract video info')
  2818. video_title = m_info.group('title')
  2819. video_description = m_info.group('description')
  2820. video_thumb = m_info.group('thumb')
  2821. m_urls = list(re.finditer(r'<src>(?P<url>.*)</src>', links_webpage))
  2822. if m_urls is None or len(m_urls) == 0:
  2823. raise ExtractError(u'Unable to extrat video url')
  2824. # They are sorted from worst to best quality
  2825. video_url = m_urls[-1].group('url')
  2826. return {'url': video_url,
  2827. 'id': video_id,
  2828. 'title': video_title,
  2829. # Videos are actually flv not mp4
  2830. 'ext': 'flv',
  2831. 'thumbnail': video_thumb,
  2832. 'description': video_description,
  2833. }
  2834. def gen_extractors():
  2835. """ Return a list of an instance of every supported extractor.
  2836. The order does matter; the first extractor matched is the one handling the URL.
  2837. """
  2838. return [
  2839. YoutubePlaylistIE(),
  2840. YoutubeChannelIE(),
  2841. YoutubeUserIE(),
  2842. YoutubeSearchIE(),
  2843. YoutubeIE(),
  2844. MetacafeIE(),
  2845. DailymotionIE(),
  2846. GoogleSearchIE(),
  2847. PhotobucketIE(),
  2848. YahooIE(),
  2849. YahooSearchIE(),
  2850. DepositFilesIE(),
  2851. FacebookIE(),
  2852. BlipTVIE(),
  2853. BlipTVUserIE(),
  2854. VimeoIE(),
  2855. MyVideoIE(),
  2856. ComedyCentralIE(),
  2857. EscapistIE(),
  2858. CollegeHumorIE(),
  2859. XVideosIE(),
  2860. SoundcloudSetIE(),
  2861. SoundcloudIE(),
  2862. InfoQIE(),
  2863. MixcloudIE(),
  2864. StanfordOpenClassroomIE(),
  2865. MTVIE(),
  2866. YoukuIE(),
  2867. XNXXIE(),
  2868. YouJizzIE(),
  2869. PornotubeIE(),
  2870. YouPornIE(),
  2871. GooglePlusIE(),
  2872. ArteTvIE(),
  2873. NBAIE(),
  2874. WorldStarHipHopIE(),
  2875. JustinTVIE(),
  2876. FunnyOrDieIE(),
  2877. SteamIE(),
  2878. UstreamIE(),
  2879. RBMARadioIE(),
  2880. EightTracksIE(),
  2881. KeekIE(),
  2882. TEDIE(),
  2883. MySpassIE(),
  2884. SpiegelIE(),
  2885. LiveLeakIE(),
  2886. ARDIE(),
  2887. ZDFIE(),
  2888. TumblrIE(),
  2889. BandcampIE(),
  2890. RedTubeIE(),
  2891. InaIE(),
  2892. HowcastIE(),
  2893. VineIE(),
  2894. FlickrIE(),
  2895. TeamcocoIE(),
  2896. XHamsterIE(),
  2897. HypemIE(),
  2898. Vbox7IE(),
  2899. GametrailersIE(),
  2900. StatigramIE(),
  2901. GenericIE()
  2902. ]
  2903. def get_info_extractor(ie_name):
  2904. """Returns the info extractor class with the given ie_name"""
  2905. return globals()[ie_name+'IE']