forked from streamlink/streamlink
/
bbciplayer.py
235 lines (210 loc) · 8.5 KB
/
bbciplayer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""
$description Live TV channels and video on-demand service from the BBC, a British public, state-owned broadcaster.
$url bbc.co.uk/iplayer
$type live, vod
$region United Kingdom
"""
import base64
import logging
import re
from collections import defaultdict
from hashlib import sha1
from streamlink.compat import urlparse, urlunparse
from streamlink.plugin import Plugin, PluginError, pluginargument, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.dash import DASHStream
from streamlink.stream.hls import HLSStream
from streamlink.utils.parse import parse_json
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(r"""
https?://(?:www\.)?bbc\.co\.uk/iplayer/
(
episode/(?P<episode_id>\w+)
|
live/(?P<channel_name>\w+)
)
""", re.VERBOSE))
@pluginargument(
"username",
requires=["password"],
metavar="USERNAME",
help="The username used to register with bbc.co.uk.",
)
@pluginargument(
"password",
prompt="Enter bbc.co.uk account password",
sensitive=True,
metavar="PASSWORD",
help="A bbc.co.uk account password to use with --bbciplayer-username.",
)
@pluginargument(
"hd",
action="store_true",
help="Prefer HD streams over local SD streams, some live programmes may not be broadcast in HD.",
)
class BBCiPlayer(Plugin):
"""
Allows streaming of live channels from bbc.co.uk/iplayer/live/* and of iPlayer programmes from
bbc.co.uk/iplayer/episode/*
"""
mediator_re = re.compile(
r'window\.__IPLAYER_REDUX_STATE__\s*=\s*({.*?});', re.DOTALL)
state_re = re.compile(r'window.__IPLAYER_REDUX_STATE__\s*=\s*({.*?});</script>')
account_locals_re = re.compile(r'window.bbcAccount.locals\s*=\s*({.*?});')
hash = base64.b64decode(b"N2RmZjc2NzFkMGM2OTdmZWRiMWQ5MDVkOWExMjE3MTk5MzhiOTJiZg==")
api_url = "https://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/" \
"{platform}/vpid/{vpid}/format/json/atk/{vpid_hash}/asn/1/"
platforms = ("pc", "iptv-all")
session_url = "https://session.bbc.com/session"
auth_url = "https://account.bbc.com/signin"
mediator_schema = validate.Schema(
{
"versions": [{"id": validate.text}]
},
validate.get("versions"), validate.get(0),
validate.get("id")
)
mediaselector_schema = validate.Schema(
validate.parse_json(),
{"media": [
{"connection":
validate.all([{
validate.optional("href"): validate.url(),
validate.optional("transferFormat"): validate.text
}], validate.filter(lambda c: c.get("href"))),
"kind": validate.text}
]},
validate.get("media"),
validate.filter(lambda x: x["kind"] == "video")
)
def __init__(self, *args, **kwargs):
super(BBCiPlayer, self).__init__(*args, **kwargs)
self.url = urlunparse(urlparse(self.url)._replace(scheme="https"))
@classmethod
def _hash_vpid(cls, vpid):
return sha1(cls.hash + str(vpid).encode("utf8")).hexdigest()
def find_vpid(self, url, res=None):
"""
Find the Video Packet ID in the HTML for the provided URL
:param url: URL to download, if res is not provided.
:param res: Provide a cached version of the HTTP response to search
:type url: string
:type res: requests.Response
:return: Video Packet ID for a Programme in iPlayer
:rtype: string
"""
log.debug("Looking for vpid on {0}", url)
# Use pre-fetched page if available
res = res or self.session.http.get(url)
m = self.mediator_re.search(res.text)
vpid = m and parse_json(m.group(1), schema=self.mediator_schema)
return vpid
def find_tvip(self, url, master=False):
log.debug("Looking for {0} tvip on {1}".format("master" if master else "", url))
res = self.session.http.get(url)
m = self.state_re.search(res.text)
data = m and parse_json(m.group(1))
if data:
channel = data.get("channel")
if master:
return channel.get("masterBrand")
return channel.get("id")
def mediaselector(self, vpid):
urls = defaultdict(set)
for platform in self.platforms:
url = self.api_url.format(vpid=vpid, vpid_hash=self._hash_vpid(vpid),
platform=platform)
log.debug("Info API request: {0}", url)
medias = self.session.http.get(url, schema=self.mediaselector_schema)
for media in medias:
for connection in media["connection"]:
urls[connection.get("transferFormat")].add(connection["href"])
for stream_type, urls in urls.items():
log.debug("{0} {1} streams", len(urls), stream_type)
for url in list(urls):
try:
if stream_type == "hls":
for s in HLSStream.parse_variant_playlist(self.session,
url).items():
yield s
if stream_type == "dash":
for s in DASHStream.parse_manifest(self.session,
url).items():
yield s
log.debug(" OK: {0}", url)
except Exception:
log.debug(" FAIL: {0}", url)
def login(self, ptrt_url):
"""
Create session using BBC ID. See https://www.bbc.co.uk/usingthebbc/account/
:param ptrt_url: The snapback URL to redirect to after successful authentication
:type ptrt_url: string
:return: Whether authentication was successful
:rtype: bool
"""
def auth_check(res):
return ptrt_url in ([h.url for h in res.history] + [res.url])
# make the session request to get the correct cookies
session_res = self.session.http.get(
self.session_url,
params=dict(ptrt=ptrt_url)
)
if auth_check(session_res):
log.debug("Already authenticated, skipping authentication")
return True
res = self.session.http.post(
self.auth_url,
params=urlparse(session_res.url).query,
data=dict(
jsEnabled=True,
username=self.get_option("username"),
password=self.get_option('password'),
attempts=0
),
headers={"Referer": self.url})
return auth_check(res)
def _get_streams(self):
if not self.get_option("username"):
log.error(
"BBC iPlayer requires an account you must login using "
"--bbciplayer-username and --bbciplayer-password")
return
log.info(
"A TV License is required to watch BBC iPlayer streams, see the BBC website for more "
"information: https://www.bbc.co.uk/iplayer/help/tvlicence")
if not self.login(self.url):
log.error(
"Could not authenticate, check your username and password")
return
episode_id = self.match.group("episode_id")
channel_name = self.match.group("channel_name")
if episode_id:
log.debug("Loading streams for episode: {0}", episode_id)
vpid = self.find_vpid(self.url)
if vpid:
log.debug("Found VPID: {0}", vpid)
for s in self.mediaselector(vpid):
yield s
else:
log.error("Could not find VPID for episode {0}",
episode_id)
elif channel_name:
log.debug("Loading stream for live channel: {0}", channel_name)
if self.get_option("hd"):
tvip = self.find_tvip(self.url, master=True) + "_hd"
if tvip:
log.debug("Trying HD stream {0}...", tvip)
try:
for s in self.mediaselector(tvip):
yield s
except PluginError:
log.error(
"Failed to get HD streams, falling back to SD")
else:
return
tvip = self.find_tvip(self.url)
if tvip:
log.debug("Found TVIP: {0}", tvip)
for s in self.mediaselector(tvip):
yield s
__plugin__ = BBCiPlayer