InfoExtractors.py 137 KB

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