InfoExtractors.py 142 KB

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