InfoExtractors.py 147 KB

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