InfoExtractors.py 119 KB

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