repo
stringclasses 856
values | pull_number
int64 3
127k
| instance_id
stringlengths 12
58
| issue_numbers
sequencelengths 1
5
| base_commit
stringlengths 40
40
| patch
stringlengths 67
1.54M
| test_patch
stringlengths 0
107M
| problem_statement
stringlengths 3
307k
| hints_text
stringlengths 0
908k
| created_at
timestamp[s] |
---|---|---|---|---|---|---|---|---|---|
streamlink/streamlink | 1,618 | streamlink__streamlink-1618 | [
"1615"
] | f53c03faf1611f4a0ef7d3ee996d7d772ee6d8c7 | diff --git a/src/streamlink/plugins/brittv.py b/src/streamlink/plugins/brittv.py
--- a/src/streamlink/plugins/brittv.py
+++ b/src/streamlink/plugins/brittv.py
@@ -10,7 +10,7 @@
class BritTV(Plugin):
url_re = re.compile(r"https?://(?:www\.)?brittv\.co.uk/watch/")
js_re = re.compile(r"""/js/brittv\.player\.js\.php\?key=([^'"]+)['"]""")
- player_re = re.compile(r"file: '(http://[^']+)'")
+ player_re = re.compile(r'''src\s*:\s*(?P<quote>['"])(https?://.+?)(?P=quote)''')
@classmethod
def can_handle_url(cls, url):
@@ -24,6 +24,7 @@ def _get_streams(self):
js_url = m.group(0)
res = http.get(urljoin(self.url, js_url))
+ self.logger.debug("Looking for stream URL...")
for url in self.player_re.findall(res.text):
if "adblock" not in url:
yield "live", HLSStream(self.session, url)
| BritTV in need of password ?
- [x] I have read the contribution guidelines.
Brit TV won't open for me any more, could it be it needs One's credentials ?
How would that look ? --brittv-username=xxxx --brittv-password=xxxx ?
(Tested of course).
```
C:\Users\Ordval>call streamlink.exe "http://brittv.co.uk/watch/?channel=1" best
[cli][info] Found matching plugin brittv for URL http://brittv.co.uk/watch/?channel=1
[cli][info] Waiting for streams, retrying every 1.0 second(s)
```
```
C:\Users\Ordval>call streamlink.exe -l debug --http-header User-Agent=Chrome/54.0.2840.59 "https://brittv.co.uk/watch/?channel=1" best
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.11.0
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin brittv for URL https://brittv.co.uk/watch/?channel=1
[plugin.brittv][debug] Found js key: aHR0cDovL2IxYTJmODdjLmFyY2guYmx1d2FyZS50di9kYWcxLm0zdTg/c2lkPWV6ZCZjaWQ9YmJjMSZhdXRoPWMzUnBiV1U5TVRVeU5EUXlNVEEzTnlaMllXeHBaR2wwZVQwekptRm5iajB3Sm1OdmJtWTlkVEFtYzJsbmJqMDBZVEk1WVdFeE4yRmtNamswWWpWaFpqWXlaR1JpWkRnek5qZGtObUl6Wmc9PQ==
error: No playable streams found on this URL: https://brittv.co.uk/watch/?channel=1
```
Opens on website. The temporary:
`call streamlink.exe hls://"http://b1a2f87c.arch.bluware.tv/dag1.m3u8?sid=ezd&cid=bbc1&auth=c3RpbWU9MTUyNDQwMzQ5OCZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj00ZWY4NTExMjNmODBlOGU5MmVjZWE1ZWUzZDc4YzQ0Mg==" best `
will play.
| 2018-04-23T11:30:47 |
||
streamlink/streamlink | 1,620 | streamlink__streamlink-1620 | [
"1575"
] | 7018fc8260f47cc1cb2e7a05dee9e6e58244e5b1 | diff --git a/src/streamlink/plugins/filmon.py b/src/streamlink/plugins/filmon.py
--- a/src/streamlink/plugins/filmon.py
+++ b/src/streamlink/plugins/filmon.py
@@ -89,16 +89,17 @@ def vod(self, vod_id):
class Filmon(Plugin):
url_re = re.compile(r"""https?://(?:\w+\.)?filmon.(?:tv|com)/
(?:
- (tv|channel)/(?P<channel>[^/]+)|
+ tv/|
+ channel/(?P<channel>\d+)|
vod/view/(?P<vod_id>\d+)-|
group/
)
""", re.VERBOSE)
- _channel_id_re = re.compile(r'channel_id\s*?=\s*"(\d+)"')
+ _channel_id_re = re.compile(r"""channel_id\s*=\s*(?P<quote>['"]?)(?P<value>\d+)(?P=quote)""")
_channel_id_schema = validate.Schema(
validate.transform(_channel_id_re.search),
- validate.any(None, validate.get(1))
+ validate.any(None, validate.get("value"))
)
quality_weights = {
@@ -136,6 +137,7 @@ def _get_streams(self):
else:
if not channel:
channel = http.get(self.url, schema=self._channel_id_schema)
+ self.logger.debug("Found channel ID: {0}", channel)
data = self.api.channel(channel)
for stream in data["streams"]:
yield stream["quality"], FilmOnHLS(self.session, channel=channel, quality=stream["quality"])
| FILMON HLS Problem with Sat1
- [x] This is a bug report.
### Description
The Channel Sat1 on Filmon can not be played with Streamlink
### Expected / Actual behavior
Normally all streams from FilmOn can be played via the streamlink. The channel Sat1 is played via the HLS protocol
### Reproduction steps / Explicit stream URLs to test
http://www.filmon.com/tv/sat-1-schweiz
### Logs
```
127.0.0.1 - - [25/Mar/2018 21:23:39] "GET /http://www.filmon.com/tv/rts-deux HTTP/1.1" 200 -
127.0.0.1 - - [25/Mar/2018 21:23:39] URL: http://www.filmon.com/tv/rts-deux Quality: best
[streamlinksrv][info] Streams:
[u'low', u'high', 'worst', 'best']
127.0.0.1 - - [25/Mar/2018 21:23:45] "GET /http://www.filmon.com/tv/sat-1-schweiz HTTP/1.1" 200 -
127.0.0.1 - - [25/Mar/2018 21:23:45] URL: http://www.filmon.com/tv/sat-1-schweiz Quality: best
[streamlinksrv][error] Plugin error: Unable to open URL: http://www.filmon.com/api-v2/channel/sat-1-schweiz?protocol=hls (404 Client Error: Not Found for url: http://www.filmon.com/api-v2/channel/sat-1-schweiz?protocol=hls)
[streamlinksrv][info] Closing currently open stream...
[streamlinksrv][error] Got exception: End Of Data!
```
| 2018-04-25T16:18:21 |
||
streamlink/streamlink | 1,623 | streamlink__streamlink-1623 | [
"1622"
] | 7018fc8260f47cc1cb2e7a05dee9e6e58244e5b1 | diff --git a/src/streamlink/plugins/itvplayer.py b/src/streamlink/plugins/itvplayer.py
--- a/src/streamlink/plugins/itvplayer.py
+++ b/src/streamlink/plugins/itvplayer.py
@@ -38,7 +38,7 @@ def channel_id(self):
def production_id(self):
if self._stream not in CHANNEL_MAP:
res = http.get(self.url, verify=False)
- production_id_match = re.findall(r"&productionId=(.*?)['&\"]", res.text, flags=re.DOTALL)
+ production_id_match = re.findall(r'data-video-production-id="(.+?)"', res.text)
if production_id_match:
return unquote(production_id_match[0])
else:
@@ -53,14 +53,14 @@ def _get_streams(self):
headers = {'Content-Length': '{0:d}'.format(len(soap_message)),
'Content-Type': 'text/xml; charset=utf-8',
- 'Host': 'mercury.itv.com',
+ 'Host': 'secure-mercury.itv.com',
'Origin': 'http://www.itv.com',
'Referer': 'http://www.itv.com/Mercury/Mercury_VideoPlayer.swf?v=null',
'SOAPAction': "http://tempuri.org/PlaylistService/GetPlaylist",
'User-Agent': ITV_PLAYER_USER_AGENT,
"X-Requested-With": "ShockwaveFlash/16.0.0.305"}
- res = http.post("http://mercury.itv.com/PlaylistService.svc?wsdl",
+ res = http.post("https://secure-mercury.itv.com/PlaylistService.svc?wsdl",
headers=headers,
data=soap_message)
| itvplayer error
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
streamlink was opening itvplayer on all channels until the other day. i have updated to the latest version 0.11.0. this is on ubuntu 14.04
computer is located in the uk so should work uk
### Expected / Actual behavior
actual behavior error is
[cli][info] streamlink is running as root! Be careful!
[cli][info] Found matching plugin itvplayer for URL www.itv.com/hub/itv2
error: Unable to open URL: http://mercury.itv.com/PlaylistService.svc?wsdl (403 Client Error: Forbidden for url: http://mercury.itv.com/PlaylistService.svc?wsdl)
...
### Reproduction steps / Explicit stream URLs to test
1. ...www.itv.com/hub/itv2
2. ...
3. ...
### Logs
_Logs are always required for a bug report, use `-l debug` [(help)](https://streamlink.github.io/cli.html#cmdoption-l)
Make sure to **remove username and password**
You can upload your logs to https://gist.github.com/ or_
```
REPLACE THIS TEXT WITH YOUR LOG
```
### Comments, screenshots, etc.
...
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-04-25T21:23:00 |
||
streamlink/streamlink | 1,625 | streamlink__streamlink-1625 | [
"1615"
] | 26f1bdde050d981e4629a6fe56e4611c03e85646 | diff --git a/src/streamlink/plugins/brittv.py b/src/streamlink/plugins/brittv.py
--- a/src/streamlink/plugins/brittv.py
+++ b/src/streamlink/plugins/brittv.py
@@ -17,15 +17,16 @@ def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
def _get_streams(self):
- res = http.get(self.url, headers={"User-Agent": useragents.CHROME})
+ http.headers.update({"User-Agent": useragents.CHROME})
+ res = http.get(self.url)
m = self.js_re.search(res.text)
if m:
self.logger.debug("Found js key: {0}", m.group(1))
js_url = m.group(0)
- res = http.get(urljoin(self.url, js_url))
+ res = http.get(urljoin(self.url, js_url), headers={"Referer": self.url})
self.logger.debug("Looking for stream URL...")
- for url in self.player_re.findall(res.text):
+ for _, url in self.player_re.findall(res.text):
if "adblock" not in url:
yield "live", HLSStream(self.session, url)
| BritTV in need of password ?
- [x] I have read the contribution guidelines.
Brit TV won't open for me any more, could it be it needs One's credentials ?
How would that look ? --brittv-username=xxxx --brittv-password=xxxx ?
(Tested of course).
```
C:\Users\Ordval>call streamlink.exe "http://brittv.co.uk/watch/?channel=1" best
[cli][info] Found matching plugin brittv for URL http://brittv.co.uk/watch/?channel=1
[cli][info] Waiting for streams, retrying every 1.0 second(s)
```
```
C:\Users\Ordval>call streamlink.exe -l debug --http-header User-Agent=Chrome/54.0.2840.59 "https://brittv.co.uk/watch/?channel=1" best
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.11.0
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin brittv for URL https://brittv.co.uk/watch/?channel=1
[plugin.brittv][debug] Found js key: aHR0cDovL2IxYTJmODdjLmFyY2guYmx1d2FyZS50di9kYWcxLm0zdTg/c2lkPWV6ZCZjaWQ9YmJjMSZhdXRoPWMzUnBiV1U5TVRVeU5EUXlNVEEzTnlaMllXeHBaR2wwZVQwekptRm5iajB3Sm1OdmJtWTlkVEFtYzJsbmJqMDBZVEk1WVdFeE4yRmtNamswWWpWaFpqWXlaR1JpWkRnek5qZGtObUl6Wmc9PQ==
error: No playable streams found on this URL: https://brittv.co.uk/watch/?channel=1
```
Opens on website. The temporary:
`call streamlink.exe hls://"http://b1a2f87c.arch.bluware.tv/dag1.m3u8?sid=ezd&cid=bbc1&auth=c3RpbWU9MTUyNDQwMzQ5OCZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj00ZWY4NTExMjNmODBlOGU5MmVjZWE1ZWUzZDc4YzQ0Mg==" best `
will play.
| A closing of the thread might suggest everything's been fixed,
I uninstalled the latest (because that is what we're still supposed to do ?)
and (re-)installed the very [streamlink-latest.exe] I could find, but it's the same thing.
(My action not being enough ?).
Although it's been “merged”, when will we see it come into effect ?
This depends on the time the next build was scheduled. You can see all builds here:
https://travis-ci.org/streamlink/streamlink/builds
The ones tagged with [`cron`](https://en.wikipedia.org/wiki/Cron) are the ones which build the Windows installers on a daily basis. Looks like you've missed it by a couple of minutes...
You can also install Streamlink from the master branch of the git repo via pip
```bash
pip install git+https://github.com/streamlink/streamlink.git
```
or by cloning the repo and installing it manually
```bash
git clone https://github.com/streamlink/streamlink.git
cd streamlink
python setup.py install
```
https://streamlink.github.io/install.html#source-code
Luckily for me your group updates the Nightly (every day?),
but there must still be something wrong in the script.
E4:
```
File reading failed:
VLC could not open the file "C:\Users\Ordval\Documents\Spellistor\(''," (No such file or directory).
Your input can't be opened:
VLC is unable to open the MRL 'file:///C:/Users/Ordval/Documents/Spellistor/%28%27%27%2C'. Check the log for details.
Your input can't be opened:
VLC is unable to open the MRL ''http://b1a2f87c.arch.bluware.tv/dag1.m3u8?sid=ezd&cid=e4uk&auth=c3RpbWU9MTUyNDUyNjY4MSZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj0wY2IzZTY2NTM2ZjY0NjE3ZDNhZTZkN2Q3ZjUxNjU4MQ==')'. Check the log for details.
Your input can't be opened:
VLC is unable to open the MRL ''http://b1a2f87c.arch.bluware.tv/dag1.m3u8?sid=ezd&cid=e4uk&auth=c3RpbWU9MTUyNDUyNjY4MSZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj0wY2IzZTY2NTM2ZjY0NjE3ZDNhZTZkN2Q3ZjUxNjU4MQ==')'. Check the log for details.
```
In the VLC playlist:
```
Title
('',
dag1.m3u8?sid=ezd&cid=e4uk&auth=c3RpbWU9MTUyNDUyNjY4MSZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj0wY2IzZTY2NTM2ZjY0NjE3ZDNhZTZkN2Q3ZjUxNjU4MQ==')
```
SMPlayer will only give an “Oops,.....”.
cmd:
```
Please wait while loading BBC One (13, BritTv)...
[cli][info] Found matching plugin brittv for URL https://brittv.co.uk/watch/?channel=1
[cli][info] Available streams: live_alt, live (worst, best)
[cli][info] Starting player: "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"
[cli][info] Got HTTP request from VLC/2.2.4 LibVLC/2.2.4
[cli][info] Opening stream: live (hls)
[cli][error] Could not open stream: Unable to open URL: ('"', 'http://b1a2f87c.arch.bluware.tv/dag1.m3u8?sid=ezd&cid=bbc1&auth=c3RpbWU9MTUyNDUyODE2MCZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj1lNWQzOTM1MjU5Y2M5NDIyZWIwODJlOGQzMGRkN2VmMg==') (No connection adapters were found for '('"', 'http://b1a2f87c.arch.bluware.tv/dag1.m3u8?sid=ezd&cid=bbc1&auth=c3RpbWU9MTUyNDUyODE2MCZ2YWxpZGl0eT0zJmFnbj0wJmNvbmY9dTAmc2lnbj1lNWQzOTM1MjU5Y2M5NDIyZWIwODJlOGQzMGRkN2VmMg==')')
[cli][info] Opening stream: live (hls)
```
Inserting the given temporary MRL (http://b1a2f87c...) in the VLC (stream?) field will play it for a while.
(Do we still need to completely uninstall before upgrading ? taken the pip option into account)
(I'm always very grateful for all of your effort).
@Ordval are you using a wrapper script to launch streamlink?
@ **beardypig** Using a "Darby_Crash" batch that loosely looks like this:
```
@echo off
color f4
:BACK
mode con:cols=117 lines=110
title %title% Alla Kanaler
echo (13) = BBC 1 (67) = Encyclo/ Science (121)= M 6/ Marco Polo (175) = S4C/ la 6 it.
cls
(here missing further commands)
:13
cls
echo.
echo Please wait while loading BBC One (13, BritTv)...
call streamlink.exe --http-header X-Forwarded-For=193.36.34.11 --http-header User-Agent=Chrome/54.0.2840.59 --player-continuous- --retry-streams 1 --retry-open 86400 "https://brittv.co.uk/watch/?channel=1" best
goto BACK
:0
cls
mode con:cols=34 lines=5
echo.
echo Til næste gang, Hver gang !
echo.
ping localhost -n 3 >nul
exit /b
```
to launch the channels, but that was possibly not what you were asking for ?
Haven't installed the latest Nightly yet, maybe it's already been solved ?
@Ordval, please try the latest nightly, and try to launch it without a wrapper script - incase it is interfering with streamlink :)
https://github.com/streamlink/streamlink/blob/7018fc8260f47cc1cb2e7a05dee9e6e58244e5b1/src/streamlink/plugins/brittv.py#L28
https://github.com/streamlink/streamlink/blob/7018fc8260f47cc1cb2e7a05dee9e6e58244e5b1/src/streamlink/plugins/brittv.py#L13
the stream doesn't work because `findall` uses the quote group as an url
```
[cli][error] Try 1/1: Could not open stream <HLSStream('(\'"\', \'http://
```
Yerp, that's my bad .... | 2018-04-26T12:28:35 |
|
streamlink/streamlink | 1,629 | streamlink__streamlink-1629 | [
"1628"
] | 856fbaae978d50c6c088b5b7386a4731768c2d71 | diff --git a/src/streamlink/plugins/raiplay.py b/src/streamlink/plugins/raiplay.py
--- a/src/streamlink/plugins/raiplay.py
+++ b/src/streamlink/plugins/raiplay.py
@@ -2,7 +2,7 @@
import re
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
+from streamlink.plugin.api import http, useragents
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
@@ -29,7 +29,7 @@ def _get_streams(self):
self.logger.debug("Found channel: {0}", channel)
stream_url = http.get(self.url, schema=self.stream_schema)
if stream_url:
- return HLSStream.parse_variant_playlist(self.session, stream_url)
+ return HLSStream.parse_variant_playlist(self.session, stream_url, headers={"User-Agent": useragents.CHROME})
__plugin__ = RaiPlay
| raiplay.it error: Forbidden for url
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
When I'm trying to stream any raiplay.it live TV station I always get a "Forbidden for url" error. However, when I'm using Firefox to visit a Rai TV stream, the stream is opened up correctly.
### Reproduction steps / Explicit stream URLs to test
Link / command to test: streamlink https://www.raiplay.it/dirette/rai2
### Logs
[cli][debug] OS: Linux-4.13.0-38-generic-x86_64-with-Ubuntu-17.10-artful
[cli][debug] Python: 3.6.3
[cli][debug] Streamlink: 0.11.0
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin raiplay for URL https://www.raiplay.it/dirette/rai2
[plugin.raiplay][debug] Found channel: rai2
error: Unable to open URL: http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=180116 (403 Client Error: Forbidden for url: http://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=180116)
### Comments, screenshots, etc.
In order to access the RAI streaming channels you need an Italian IP address. However there is one channel which is also accessible outside of Italy which is RaiNews24: https://www.raiplay.it/dirette/rainews24
If you use this channel you get the same error / behavior.
| 2018-04-30T09:27:39 |
||
streamlink/streamlink | 1,660 | streamlink__streamlink-1660 | [
"1659"
] | e2a55461decc6856912325e8103cefb359027811 | diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py
--- a/src/streamlink/plugins/tf1.py
+++ b/src/streamlink/plugins/tf1.py
@@ -9,13 +9,20 @@
class TF1(Plugin):
- url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(tf1|tmc|tfx|tf1-series-films)/direct|(lci).fr/direct)/?")
+ url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/([\w-]+)/direct|(lci).fr/direct)/?")
embed_url = "http://www.wat.tv/embedframe/live{0}"
embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE)
api_url = "http://www.wat.tv/get/{0}/591997"
swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf"
- hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci", "tfx" : "nt1live", "tf1-series-films" : "hd1live" }
- hls_channel_remap = {"lci": "LCI", "tf1": "V4", "tfx" : "nt1", "tf1-series-films" : "hd1" }
+ hds_channel_remap = {"tf1": "androidliveconnect",
+ "lci": "androidlivelci",
+ "tfx": "nt1live",
+ "hd1": "hd1live", # renamed to tfx
+ "tf1-series-films": "hd1live"}
+ hls_channel_remap = {"lci": "LCI",
+ "tf1": "V4",
+ "tfx": "nt1",
+ "tf1-series-films": "hd1"}
@classmethod
def can_handle_url(cls, url):
@@ -23,6 +30,7 @@ def can_handle_url(cls, url):
def _get_hds_streams(self, channel):
channel = self.hds_channel_remap.get(channel, "{0}live".format(channel))
+ self.logger.debug("Using HDS channel name: {0}".format(channel))
manifest_url = http.get(self.api_url.format(channel),
params={"getURL": 1},
headers={"User-Agent": useragents.FIREFOX}).text
| diff --git a/tests/test_plugin_tf1.py b/tests/test_plugin_tf1.py
--- a/tests/test_plugin_tf1.py
+++ b/tests/test_plugin_tf1.py
@@ -12,11 +12,11 @@ def test_can_handle_url(self):
self.assertTrue(TF1.can_handle_url("http://lci.fr/direct"))
self.assertTrue(TF1.can_handle_url("http://www.lci.fr/direct"))
self.assertTrue(TF1.can_handle_url("http://tf1.fr/tmc/direct"))
+ self.assertTrue(TF1.can_handle_url("http://tf1.fr/lci/direct"))
+ def test_can_handle_url_negative(self):
# shouldn't match
self.assertFalse(TF1.can_handle_url("http://tf1.fr/direct"))
-# self.assertFalse(TF1.can_handle_url("http://tf1.fr/nt1/direct")) NOTE : TF1 redirect old channel names to new ones (for now).
-# self.assertFalse(TF1.can_handle_url("http://tf1.fr/hd1/direct"))
self.assertFalse(TF1.can_handle_url("http://www.tf1.fr/direct"))
self.assertFalse(TF1.can_handle_url("http://www.tvcatchup.com/"))
self.assertFalse(TF1.can_handle_url("http://www.youtube.com/"))
| LCI not covered by TF1 home page anymore
### Checklist
- [ ] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
I pointed out since a while that tf1 plugin doesn't cover anymore LCI from tf1.fr home website. It did before.
### Expected / Actual behavior
Here I point out result with older tf1 plugin :
```
streamlink "https://www.tf1.fr/lci/direct"
[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct
error: Unable to open URL: http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@30158
5/manifest.f4m?hdnea=st=1526479986~exp=1526481786~acl=/*~hmac=207f41547435bb3422
e9f51af166cae855bdbb387ac875524827deb528999d9e (403 Client Error: Forbidden for
url: http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=s
t=1526479986~exp=1526481786~acl=/*~hmac=207f41547435bb3422e9f51af166cae855bdbb38
7ac875524827deb528999d9e&g=DSCLJVQYJHGR&hdcore=3.1.0)
```
The latest tf1 plugin gives such result :
```
streamlink "https://www.tf1.fr/lci/direct"
[cli][info] Found matching plugin resolve for URL https://www.tf1.fr/lci/direct
[plugin.resolve][info] Found iframes:
Traceback (most recent call last):
File "C:\Program Files\Python27\Scripts\streamlink-script.py", line 11, in <mo
dule>
load_entry_point('streamlink==0.12.1+8.ge2a5546', 'console_scripts', 'stream
link')()
File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin
e 1113, in main
handle_url()
File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin
e 505, in handle_url
streams = fetch_streams(plugin)
File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin
e 402, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "c:\program files\python27\lib\site-packages\streamlink\plugin\plugin.py"
, line 385, in get_streams
return self.streams(*args, **kwargs)
File "c:\program files\python27\lib\site-packages\streamlink\plugin\plugin.py"
, line 288, in streams
ostreams = self._get_streams()
File "c:\program files\python27\lib\site-packages\streamlink\plugins\resolve.p
y", line 480, in _get_streams
IndexError: list index out of range
```
### Reproduction steps / Explicit stream URLs to test
1. ` streamlink "https://www.tf1.fr/lci/direct"`
### Logs
```
streamlink -l debug
[cli][debug] OS: Windows 7
[cli][debug] Python: 2.7.13
[cli][debug] Streamlink: 0.12.1+8.ge2a5546
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.46.0)
```
Both tests were made with the latest streamlink build, I just replaced newer tf1 plugin with older.
Thanks for up.
| The url is hard coded in
https://github.com/streamlink/streamlink/blob/b340b1e3dbb5b8dca59fcd01c224fc31f80f7402/src/streamlink/plugins/tf1.py#L12
it can't find the `lci` part
Ref https://github.com/streamlink/streamlink/pull/1457
---
and you should use the path `%APPDATA%\streamlink\plugins` for any custom plugins.
https://streamlink.github.io/cli.html#sideloading-plugins | 2018-05-16T14:48:22 |
streamlink/streamlink | 1,663 | streamlink__streamlink-1663 | [
"1662"
] | 9e366c89f4266e3ff5a5001caf59d449998fe242 | diff --git a/src/streamlink/plugins/ine.py b/src/streamlink/plugins/ine.py
--- a/src/streamlink/plugins/ine.py
+++ b/src/streamlink/plugins/ine.py
@@ -6,7 +6,8 @@
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api import validate
-from streamlink.stream import HLSStream
+from streamlink.stream import HLSStream, HTTPStream
+from streamlink.utils import update_scheme
class INE(Plugin):
@@ -23,10 +24,8 @@ class INE(Plugin):
validate.all(
validate.get(1),
validate.transform(json.loads),
- {"playlist": [
- {"sources": [{"file": validate.text,
- "type": validate.text}]}
- ]}
+ {"playlist": str},
+ validate.get("playlist")
)
)
)
@@ -46,10 +45,15 @@ def _get_streams(self):
self.logger.debug("Loading player JS: {0}", js_url)
res = http.get(js_url)
- data = self.setup_schema.validate(res.text)
+ metadata_url = update_scheme(self.url, self.setup_schema.validate(res.text))
+ data = http.json(http.get(metadata_url))
+
for source in data["playlist"][0]["sources"]:
- if source["type"] == "hls":
- return HLSStream.parse_variant_playlist(self.session, "https:" + source["file"])
+ if source["type"] == "application/vnd.apple.mpegurl":
+ for s in HLSStream.parse_variant_playlist(self.session, source["file"]).items():
+ yield s
+ elif source["type"] == "video/mp4":
+ yield "{0}p".format(source["height"]), HTTPStream(self.session, source["file"])
__plugin__ = INE
| Unable to validate result: <_sre.SRE_Match object; ... should be 'list' but is 'str'
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
Hi, something's failing when trying to fetch a video from INE, mac OS 10.12.6:
```
$ streamlink -o ./streamlink.mp4 https://streaming.ine.com/play/97c49b6f-5cda-4e66-859d-627ba2e9e26e/lab-setup 720p --loglevel debug --http-cookie laravel_session=<removed>
[cli][debug] OS: macOS 10.12.6
[cli][debug] Python: 3.5.5
[cli][debug] Streamlink: 0.12.1
[cli][debug] Requests(2.18.1), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin ine for URL https://streaming.ine.com/play/97c49b6f-5cda-4e66-859d-627ba2e9e26e/lab-setup
[plugin.ine][debug] Found video ID: 97c49b6f-5cda-4e66-859d-627ba2e9e26e
[plugin.ine][debug] Loading player JS: https://content.jwplatform.com/players/gdH3hfpy-p4NBeNN0.js?exp=1527771621&sig=<removed>
error: Unable to validate result: <_sre.SRE_Match object; span=(100223, 101420), match='jwConfig = {\n "aspectratio": "16:9",\n "autost> does not equal None or Unable to validate key 'playlist': Type of '//content.jwplatform.com/v2/media/gdH3hfpy?token=<removed>' should be 'list' but is 'str'
$
$ python --version
Python 3.5.5
$ streamlink --version-check
[cli][info] Your Streamlink version (0.12.1) is up to date!
$
```
Any ideas? Thanks!
| 2018-05-17T13:55:15 |
||
streamlink/streamlink | 1,670 | streamlink__streamlink-1670 | [
"1669"
] | 1bf90e845f6165eafe04716f5e8cb4b3c1579e2d | diff --git a/src/streamlink/plugins/vidio.py b/src/streamlink/plugins/vidio.py
--- a/src/streamlink/plugins/vidio.py
+++ b/src/streamlink/plugins/vidio.py
@@ -1,36 +1,61 @@
-'''
+"""
Plugin for vidio.com
- https://www.vidio.com/live/5075-dw-tv-stream
- https://www.vidio.com/watch/766861-5-rekor-fantastis-zidane-bersama-real-madrid
-'''
+"""
import re
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
+from streamlink.plugin.api import http, useragents, validate
from streamlink.stream import HLSStream
-
-_url_re = re.compile(r"https?://(?:www\.)?vidio\.com/(?:en/)?(?P<type>live|watch)/(?P<id>\d+)-(?P<name>[^/?#&]+)")
-_playlist_re = re.compile(r'''hls-url=["'](?P<url>[^"']+)["']''')
+from streamlink.utils import parse_json
class Vidio(Plugin):
+ _url_re = re.compile(r"https?://(?:www\.)?vidio\.com/(?:en/)?(?P<type>live|watch)/(?P<id>\d+)-(?P<name>[^/?#&]+)")
+ _playlist_re = re.compile(r'''hls-url=["'](?P<url>[^"']+)["']''')
+ _data_id_re = re.compile(r'''meta\s+data-id=["'](?P<id>[^"']+)["']''')
+
+ csrf_tokens_url = "https://www.vidio.com/csrf_tokens"
+ tokens_url = "https://www.vidio.com/live/{id}/tokens"
+ token_schema = validate.Schema(validate.transform(parse_json),
+ {"token": str},
+ validate.get("token"))
+
@classmethod
def can_handle_url(cls, url):
- return _url_re.match(url)
+ return cls._url_re.match(url)
+
+ def get_csrf_tokens(self):
+ return http.get(self.csrf_tokens_url,
+ schema=self.token_schema)
+
+ def get_url_tokens(self, stream_id):
+ self.logger.debug("Getting stream tokens")
+ csrf_token = self.get_csrf_tokens()
+ return http.post(self.tokens_url.format(id=stream_id),
+ files={"authenticity_token": (None, csrf_token)},
+ headers={"User-Agent": useragents.CHROME,
+ "Referer": self.url},
+ schema=self.token_schema)
def _get_streams(self):
res = http.get(self.url)
- match = _playlist_re.search(res.text)
- if match is None:
- return
+ plmatch = self._playlist_re.search(res.text)
+ idmatch = self._data_id_re.search(res.text)
+
+ hls_url = plmatch and plmatch.group("url")
+ stream_id = idmatch and idmatch.group("id")
- url = match.group('url')
+ tokens = self.get_url_tokens(stream_id)
- if url:
- self.logger.debug('HLS URL: {0}'.format(url))
- for s in HLSStream.parse_variant_playlist(self.session, url).items():
- yield s
+ if hls_url:
+ self.logger.debug("HLS URL: {0}".format(hls_url))
+ self.logger.debug("Tokens: {0}".format(tokens))
+ return HLSStream.parse_variant_playlist(self.session, hls_url+"?"+tokens,
+ headers={"User-Agent": useragents.CHROME,
+ "Referer": self.url})
__plugin__ = Vidio
| [plugin issue] plugin.vidio.com / can't handle stream URLs anymore
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
plugin handling of https://www.vidio.com/live URls not working anymore due to changes at provided stream structure
### Expected / Actual behavior
streamlink -l debug www.vidio.com/live/665-rcti-tv-stream
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.12.1
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin vidio for URL www.vidio.com/live/665-rcti-tv-stream
[plugin.vidio][debug] HLS URL: https://kmklive-lh.akamaihd.net/i/rcti_ta_regular@94478/master.m3u8
error: Unable to open URL: https://kmklive-lh.akamaihd.net/i/rcti_ta_regular@94478/master.m3u8 (403 Client Error: Forbidden for url: https://kmklive-lh.akamaihd.net/i/rcti_ta_regular@94478/master.m3u8)
| Looks like there are some extra steps required to get the actual stream url. Seems pretty straightforward though :) | 2018-05-19T17:19:24 |
|
streamlink/streamlink | 1,677 | streamlink__streamlink-1677 | [
"1033"
] | 6cab9d25271781a9e2a91043f648288436773e62 | diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -2,8 +2,10 @@
import base64
import re
+from collections import defaultdict
from hashlib import sha1
+from streamlink import PluginError
from streamlink.compat import parse_qsl, urlparse
from streamlink.plugin import Plugin, PluginOptions
from streamlink.plugin.api import http
@@ -25,7 +27,8 @@ class BBCiPlayer(Plugin):
)
""", re.VERBOSE)
mediator_re = re.compile(r'window\.mediatorDefer\s*=\s*page\([^,]*,\s*({.*?})\);', re.DOTALL)
- tvip_re = re.compile(r'event_master_brand=(\w+?)&')
+ tvip_re = re.compile(r'channel"\s*:\s*{\s*"id"\s*:\s*"(\w+?)"')
+ tvip_master_re = re.compile(r'event_master_brand=(\w+?)&')
account_locals_re = re.compile(r'window.bbcAccount.locals\s*=\s*({.*?});')
swf_url = "http://emp.bbci.co.uk/emp/SMPf/1.18.3/StandardMediaPlayerChromelessFlash.swf"
hash = base64.b64decode(b"N2RmZjc2NzFkMGM2OTdmZWRiMWQ5MDVkOWExMjE3MTk5MzhiOTJiZg==")
@@ -110,25 +113,35 @@ def find_vpid(self, url, res=None):
vpid = m and parse_json(m.group(1), schema=self.mediator_schema)
return vpid
- def find_tvip(self, url):
- self.logger.debug("Looking for tvip on {0}", url)
+ def find_tvip(self, url, master=False):
+ self.logger.debug("Looking for {0} tvip on {1}", "master" if master else "", url)
res = http.get(url)
- m = self.tvip_re.search(res.text)
+ if master:
+ m = self.tvip_master_re.search(res.text)
+ else:
+ m = self.tvip_re.search(res.text)
return m and m.group(1)
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)
self.logger.debug("Info API request: {0}", url)
- stream_urls = http.get(url, schema=self.mediaselector_schema)
- for media in stream_urls:
+ medias = http.get(url, schema=self.mediaselector_schema)
+ for media in medias:
for connection in media["connection"]:
- if connection.get("transferFormat") == "hds":
- for s in HDSStream.parse_manifest(self.session, connection["href"]).items():
- yield s
- if connection.get("transferFormat") == "hls":
- for s in HLSStream.parse_variant_playlist(self.session, connection["href"]).items():
- yield s
+ urls[connection.get("transferFormat")].add(connection["href"])
+
+ for stream_type, urls in urls.items():
+ self.logger.debug("{0} {1} streams", len(urls), stream_type)
+ for url in list(urls):
+ self.logger.debug(" {0}", url)
+ if stream_type == "hds":
+ for s in HDSStream.parse_manifest(self.session, url).items():
+ yield s
+ if stream_type == "hls":
+ for s in HLSStream.parse_variant_playlist(self.session, url).items():
+ yield s
def login(self, ptrt_url):
"""
@@ -188,6 +201,17 @@ def _get_streams(self):
self.logger.error("Could not find VPID for episode {0}", episode_id)
elif channel_name:
self.logger.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:
+ self.logger.debug("Trying HD stream {0}...", tvip)
+ try:
+ for s in self.mediaselector(tvip):
+ yield s
+ except PluginError:
+ self.logger.error("Failed to get HD streams, falling back to SD")
+ else:
+ return
tvip = self.find_tvip(self.url)
if tvip:
self.logger.debug("Found TVIP: {0}", tvip)
diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py
--- a/src/streamlink_cli/argparser.py
+++ b/src/streamlink_cli/argparser.py
@@ -1353,6 +1353,13 @@ def hours_minutes_seconds(value):
A bbc.co.uk account password to use with --bbciplayer-username.
"""
)
+plugin.add_argument(
+ "--bbciplayer-hd",
+ action="store_true",
+ help="""
+ Prefer HD streams over local SD streams, some live programmes may not be broadcast in HD.
+ """
+)
plugin.add_argument(
"--zattoo-email",
metavar="EMAIL",
diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py
--- a/src/streamlink_cli/main.py
+++ b/src/streamlink_cli/main.py
@@ -955,6 +955,9 @@ def setup_plugin_options():
if bbciplayer_password:
streamlink.set_plugin_option("bbciplayer", "password", bbciplayer_password)
+ if args.bbciplayer_hd:
+ streamlink.set_plugin_option("bbciplayer", "hd", True)
+
if args.zattoo_email:
streamlink.set_plugin_option("zattoo", "email", args.zattoo_email)
if args.zattoo_email and not args.zattoo_password:
| BBC iPlayer Live TV
When streaming live channels from iplayer e.g. http://www.bbc.co.uk/iplayer/live/bbcone (geoip restricted to UK) it defaults to 960x540 25fps video.
```
Streamlink:
[cli][info] Available streams: 544k_alt, 1700k_alt, 1700k_alt2, 544k_alt2, 352k_alt2, 942k_alt2, 540p_alt, 288p_alt, 942k_alt, 540p_alt2, 396p_alt2, 288p_alt2, 396p_alt, 352k_alt, 352k (worst), 544k, 288p, 942k, 396p, 540p, 1700k (best)
[cli][info] Opening stream: 1700k (hds)
```
get_iplayer had a streaming option which allows streaming up to 720p 50fps [info](https://github.com/get-iplayer/get_iplayer/wiki/modesref#tv-modes). Unfortunately the developer removed the streaming feature from new versions.
```
get_iplayer:
INFO: hvfhd1,hvfhd2,hvfhd3,hvfhd4,hvfsd1,hvfsd2,hvfsd3,hvfsd4,hvfvhigh1,hvfvhigh2,hvfvhigh3,hvfvhigh4,hvfhigh1,hvfhigh2,hvfhigh3,hvfhigh4,hvfstd1,hvfstd2,hvfstd3,hvfstd4,hvflow1,hvflow2,hvflow3,hvflow4 modes will be tried for version default
INFO: Trying hvfhd1 mode to stream livetv: BBC One - live
(+) Video --vid=1 (h264 1280x720 50.000fps)
(+) Audio --aid=1 (aac 2ch 48000Hz)
```
Is it possible to force mpegdash/hls 720p 50fps stream with streamlink or would a new feature be needed to enable it?
| It would require some development work, how much work I don't know. Unless someone else does it, I'll take a look at it at some point in the next couple of weeks.
@h633537 wrote:
> Is it possible to force mpegdash/hls 720p 50fps stream with streamlink
I'm not sure whether streamlink currently supports MPEG-DASH streams; youtube-dl does, but only for VOD, not live streams (dynamic manifests).
If you are willing to do some manual labour, then you can grab yourself the AdobeHDS manifests and/or AppleHLS playlists and feed those to streamlink directly...
E.g. for BBC One (London), one can sniff the mediaselector URL to the streams:
`http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/bbc_one_london/atk/78ca5063d64bb5b308d1d87f737b610aa2db0f3f/asn/1/`
and the hds manifest for the Akamai CDN is
`http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/ak/bbc_one_london.f4m`
If you substitute `bbc_one_london.f4m` with `bbc_one_hd.f4m`, then
`streamlink -o BBCOneLive.flv "hds://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/ak/bbc_one_hd.f4m" best` =>
```
[cli][info] Found matching plugin stream for URL hds://a.files.bbci.co.uk/media/
live/manifesto/audio_video/simulcast/hds/uk/pc/ak/bbc_one_hd.f4m
[cli][info] Available streams: 352k (worst), 544k, 942k, 1700k, 2908k, 5166k (be
st)
[cli][info] Opening stream: 5166k (hds)
[download][BBCOneLive.flv] Written 312.3 KB (1s @ 213.9 KB/s)
```
If you prefer AppleHLS streams, then for
`http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/bbc_one_hd`
one gets (Akamai CDN):
`http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_hdtv/ak/bbc_one_hd.m3u8`
so
`streamlink -o BBCOneLive.ts "hlsvariant://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_hdtv/ak/bbc_one_hd.m3u8" best` =>
```
[cli][info] Found matching plugin stream for URL hlsvariant://a.files.bbci.co.uk
/media/live/manifesto/audio_video/simulcast/hls/uk/abr_hdtv/ak/bbc_one_hd.m3u8
[cli][info] Available streams: 396p (worst), 540p, 720p (best)
[cli][info] Opening stream: 720p (hls)
[download][BBCOneLive.ts] Written 372.6 KB (0s @ 402.4 KB/s)
```
NB: Both the `mediaselector` URLs and the HDS/HLS streams themselves are geo-filtered to the UK only
(and the BBC have a nasty habit of blocking many commercial VPS/VPN/Proxy providers...).
If you can grab a previous get_iplayer version with live TV support, then you can extract the AppleHLS playlists via the `--streaminfo` switch:
`perl get_iplayer-297.pl --type=livetv --pid=bbc_one_hd -i --streaminfo`
Search under the `hvfhd*` livetvmodes for `streamurl` URLs...
Alternatively, you can use an online service
`http://bbclive.herokuapp.com/`
Select the _Generated Playlists_ section for TV (it's hosted on an overseas server, so _Mediaselector API_ won't work for TV...).
@MickelCL
Please take your spamming activities elsewhere; this issue (and whole tracker) IS NOT THE PLACE to promote commercial VPN solutions; be advised the iPlayer team are on a constant hunt for UK VPN services that advertise overseas access; of course they can't block every VPN out there, but once you "advertise" one the more likely it is to be blocked sooner or later...
It looks as though you subscribed into GitHub just two weeks ago; if your sole intention was to promote spam, then think again; I am really tempted to hit that "Report abuse" button; you've been warned!
I have edited the above comment by @MickelCL to remove a direct link to a VPN provider as it has been linked here as well as #1197
Yet another spamming intervention by github user @MickelCL [here](https://github.com/streamlink/streamlink/issues/1198#issuecomment-329156080); @gravyboat, will you edit again, warn again or simply block?
@Vangelis66 Good catch, edited that out. In addition I have blocked them from the organization (so they can't spam any more), and reported them to GitHub. Thanks!
@gravyboat
Look again [here](https://github.com/streamlink/streamlink/issues/1198#issuecomment-329157619), in the same issue; _probably the same person under a similar GitHub username_...
It's just that I am allergic to spam in general, nothing personal with them or their company/service...
If anyone's in need of the service they provide, they're free to use the search engine of their choice...
... Come to think of it, this infringing GitHub user may not be directly related to that company, but such companies (especially the new ones in the field) have a nasty habit of promising free accounts to hopefuls that promote their product in prominent internet locations...
@Vangelis66 I totally agree with you, I'll modify the comment and ban them as well, thanks for looking out! I don't tolerate that spam either.
Some problems with live BBC:
BBC One
C:\WINDOWS\system32>streamlink https://www.bbc.co.uk/iplayer/live/bbcone
[cli][info] Found matching plugin bbciplayer for URL https://www.bbc.co.uk/iplayer/live/bbcone
[plugin.bbciplayer][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
error: Unable to open URL: http://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/pc/vpid/bbc_one/format/json/atk/a3c61c990404b5a1dea9578af356ca3187cb3c2d/asn/1/ (404 Client Error: Not Found for url: http://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/pc/vpid/bbc_one/format/json/atk/a3c61c990404b5a1dea9578af356ca3187cb3c2d/asn/1/)
the same error with BBC Two
C:\WINDOWS\system32>streamlink https://www.bbc.co.uk/iplayer/live/bbctwo
but working alright with
BBC News
C:\WINDOWS\system32>streamlink https://www.bbc.co.uk/iplayer/live/bbcnews
[cli][info] Found matching plugin bbciplayer for URL https://www.bbc.co.uk/iplayer/live/bbcnews
[plugin.bbciplayer][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
[cli][info] Available streams: 352k_alt2 (worst), 352k_alt, 352k, 544k_alt2, 544k_alt, 544k, 942k_alt2, 942k_alt, 942k, 396p_alt2, 396p_alt, 396p, 540p_alt2, 540p_alt, 540p, 1700k_alt2, 1700k_alt, 1700k, 720p_alt2, 720p_alt, 720p, 2908k_alt2, 2908k_alt, 2908k, 5166k_alt2, 5166k_alt, 5166k (best)
[cli][info] Opening stream: 5166k (hds)
[cli][info] Starting player: "C:\mpv_64-20171225\mpv.exe" --cache=5000
and BBC Four and BBC Parliament
streamlink https://www.bbc.co.uk/iplayer/live/bbcfour
streamlink https://www.bbc.co.uk/iplayer/live/bbcparliament
EDIT:
I can watch live BBC One and BBC Two with the following commands:
C:\WINDOWS\system32>streamlink http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_hdtv/ak/bbc_one_hd.m3u8
and
C:\WINDOWS\system32>streamlink http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_hdtv/ak/bbc_two_hd.m3u8
Seeing the same issues
The original issue at the top is about **dash** it might work with #1637
---
about the other two issue above this comment
it's unclear which version is used and a debug log would help
https://streamlink.github.io/cli.html#cmdoption-l
DASH support would be possible with #1637, I have a branch ready to go. The other two issues are likely fixed already, there were a couple of fixes merged but I can’t find the PRs right now.
Vangelis66 commented on 24 Jun 2017:
http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/ak/bbc_one_london.f4m
You, sir, have been extremely helpful.
I can now also stream BBC2 using: streamlink http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/ak/bbc_two_hd.f4m --default-stream 1700k with the CPU on my 11 year-old Vista laptop stable at approx 25%.
I don't ask much from life! Now, how to get the ITV streams working in a similar manner?
Many thanks.
| 2018-05-21T22:56:05 |
|
streamlink/streamlink | 1,680 | streamlink__streamlink-1680 | [
"1678"
] | 38d340b3fdd1ff0fe09420456e1e73bf83c64394 | diff --git a/src/streamlink/plugins/goodgame.py b/src/streamlink/plugins/goodgame.py
--- a/src/streamlink/plugins/goodgame.py
+++ b/src/streamlink/plugins/goodgame.py
@@ -3,6 +3,7 @@
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.stream import HLSStream
+from streamlink.utils import parse_json
HLS_URL_FORMAT = "https://hls.goodgame.ru/hls/{0}{1}.m3u8"
QUALITIES = {
@@ -13,7 +14,7 @@
}
_url_re = re.compile(r"https?://(?:www\.)?goodgame.ru/channel/(?P<user>[^/]+)")
-_stream_re = re.compile(r'var src = "([^"]+)";')
+_apidata_re = re.compile(r'var\s+ApiData\s*=\s*({.*?})\s*;', re.MULTILINE)
_ddos_re = re.compile(r'document.cookie="(__DDOS_[^;]+)')
@@ -35,17 +36,19 @@ def _get_streams(self):
match = _ddos_re.search(res.text)
if match:
+ self.logger.debug("Anti-DDOS bypass...")
headers["Cookie"] = match.group(1)
res = http.get(self.url, headers=headers)
- match = _stream_re.search(res.text)
+ match = _apidata_re.search(res.text)
if not match:
return
- stream_id = match.group(1)
+ stream_data = parse_json(match.group(1))
+ self.logger.debug("Found channel info for {channel_key}", **stream_data)
streams = {}
for name, url_suffix in QUALITIES.items():
- url = HLS_URL_FORMAT.format(stream_id, url_suffix)
+ url = HLS_URL_FORMAT.format(stream_data["channel_id"], url_suffix)
if not self._check_stream(url):
continue
| Goodgame plugin stopped working
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
Goodgame plugin is unable to find any playable qualities when specified channel link. Began about 2 days ago, previously was working as usual.
### Expected / Actual behavior
Should locate and print list of available qualities (or start playing in vlc if quality was specified as parameter).
### Reproduction steps / Explicit stream URLs to test
streamlink -l debug https://goodgame.ru/channel/Foggy
### Logs
[cli][debug] OS: macOS 10.11.6
[cli][debug] Python: 3.6.1
[cli][debug] Streamlink: 0.12.1
[cli][debug] Requests(2.18.1), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin goodgame for URL https://goodgame.ru/channel/Foggy
error: No playable streams found on this URL: https://goodgame.ru/channel/Foggy
| I can confirm.
I do not know if it will be useful, but it works with such a plug-in in the livestreamer:
```python
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http
from livestreamer.stream import HLSStream
HLS_URL_FORMAT = "http://hls.goodgame.ru/hls/{0}{1}.m3u8"
API_URL_FORMAT = "http://api2.goodgame.ru/streams/{0}"
QUALITIES = {
"1080p": "",
"720p": "_720",
"480p": "_480",
"240p": "_240"
}
_url_re = re.compile("https?://(?:www\.)?goodgame.ru/channel/(?P<user>\w+)")
_stream_re = re.compile(
"\"gg_player_src\":\"(\w+)\""
)
class GoodGame(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _check_stream(self, url):
res = http.get(url, acceptable_status=(200, 404))
if res.status_code == 200:
return True
def _get_streams(self):
match = _url_re.search(self.url)
id = match.group(1)
url = API_URL_FORMAT.format(id)
res = http.get(url)
match = _stream_re.search(res.text)
if not match:
return
stream_id = match.group(1)
streams = {}
for name, url_suffix in QUALITIES.items():
url = HLS_URL_FORMAT.format(stream_id, url_suffix)
if not self._check_stream(url):
continue
streams[name] = HLSStream(self.session, url)
return streams
__plugin__ = GoodGame
```
https://github.com/chrippa/livestreamer/issues/1518
https://yadi.sk/d/-MA5GdyrxbmN7 - my plugin for livestreamer
Streamlink is a fork of the dead Livestreamer project. Anything that's included in Livestreamer is outdated and not really worth mentioning. If the modifications here are causing a plugin to not work again, then it's probably caused by something else.
Your suggested plugin code is from 1699e4159f6ba2049d29c4e25f1a60c6cb7f33b0, which has seen a lot of changes since then:
https://github.com/streamlink/streamlink/commits/master/src/streamlink/plugins/goodgame.py
https://github.com/streamlink/streamlink/blame/master/src/streamlink/plugins/goodgame.py
If you have further improvement suggestions, please open a pull request instead of linking external code, so it can be properly reviewed and possibly even merged. Thanks | 2018-05-22T17:36:07 |
|
streamlink/streamlink | 1,686 | streamlink__streamlink-1686 | [
"1678"
] | 2d7aae7acc281bb8aae444a71aa3e3bb8d3c18f1 | diff --git a/src/streamlink/plugins/goodgame.py b/src/streamlink/plugins/goodgame.py
--- a/src/streamlink/plugins/goodgame.py
+++ b/src/streamlink/plugins/goodgame.py
@@ -14,7 +14,7 @@
}
_url_re = re.compile(r"https?://(?:www\.)?goodgame.ru/channel/(?P<user>[^/]+)")
-_apidata_re = re.compile(r'var\s+ApiData\s*=\s*({.*?})\s*;', re.MULTILINE)
+_apidata_re = re.compile(r'''(?P<quote>["']?)channel(?P=quote)\s*:\s*(?P<data>{.*?})\s*,''')
_ddos_re = re.compile(r'document.cookie="(__DDOS_[^;]+)')
@@ -41,14 +41,19 @@ def _get_streams(self):
res = http.get(self.url, headers=headers)
match = _apidata_re.search(res.text)
- if not match:
+ channel_info = match and parse_json(match.group("data"))
+ if not channel_info:
+ self.logger.error("Could not find channel info")
return
- stream_data = parse_json(match.group(1))
- self.logger.debug("Found channel info for {channel_key}", **stream_data)
+ self.logger.debug("Found channel info: channelkey={channelkey} pid={streamkey} online={status}",
+ **channel_info)
+ if not channel_info['status']:
+ self.logger.debug("Channel appears to be offline")
+
streams = {}
for name, url_suffix in QUALITIES.items():
- url = HLS_URL_FORMAT.format(stream_data["channel_id"], url_suffix)
+ url = HLS_URL_FORMAT.format(channel_info['streamkey'], url_suffix)
if not self._check_stream(url):
continue
| Goodgame plugin stopped working
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
Goodgame plugin is unable to find any playable qualities when specified channel link. Began about 2 days ago, previously was working as usual.
### Expected / Actual behavior
Should locate and print list of available qualities (or start playing in vlc if quality was specified as parameter).
### Reproduction steps / Explicit stream URLs to test
streamlink -l debug https://goodgame.ru/channel/Foggy
### Logs
[cli][debug] OS: macOS 10.11.6
[cli][debug] Python: 3.6.1
[cli][debug] Streamlink: 0.12.1
[cli][debug] Requests(2.18.1), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin goodgame for URL https://goodgame.ru/channel/Foggy
error: No playable streams found on this URL: https://goodgame.ru/channel/Foggy
| I can confirm.
I do not know if it will be useful, but it works with such a plug-in in the livestreamer:
```python
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http
from livestreamer.stream import HLSStream
HLS_URL_FORMAT = "http://hls.goodgame.ru/hls/{0}{1}.m3u8"
API_URL_FORMAT = "http://api2.goodgame.ru/streams/{0}"
QUALITIES = {
"1080p": "",
"720p": "_720",
"480p": "_480",
"240p": "_240"
}
_url_re = re.compile("https?://(?:www\.)?goodgame.ru/channel/(?P<user>\w+)")
_stream_re = re.compile(
"\"gg_player_src\":\"(\w+)\""
)
class GoodGame(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _check_stream(self, url):
res = http.get(url, acceptable_status=(200, 404))
if res.status_code == 200:
return True
def _get_streams(self):
match = _url_re.search(self.url)
id = match.group(1)
url = API_URL_FORMAT.format(id)
res = http.get(url)
match = _stream_re.search(res.text)
if not match:
return
stream_id = match.group(1)
streams = {}
for name, url_suffix in QUALITIES.items():
url = HLS_URL_FORMAT.format(stream_id, url_suffix)
if not self._check_stream(url):
continue
streams[name] = HLSStream(self.session, url)
return streams
__plugin__ = GoodGame
```
https://github.com/chrippa/livestreamer/issues/1518
https://yadi.sk/d/-MA5GdyrxbmN7 - my plugin for livestreamer
Streamlink is a fork of the dead Livestreamer project. Anything that's included in Livestreamer is outdated and not really worth mentioning. If the modifications here are causing a plugin to not work again, then it's probably caused by something else.
Your suggested plugin code is from 1699e4159f6ba2049d29c4e25f1a60c6cb7f33b0, which has seen a lot of changes since then:
https://github.com/streamlink/streamlink/commits/master/src/streamlink/plugins/goodgame.py
https://github.com/streamlink/streamlink/blame/master/src/streamlink/plugins/goodgame.py
If you have further improvement suggestions, please open a pull request instead of linking external code, so it can be properly reviewed and possibly even merged. Thanks | 2018-05-23T22:31:52 |
|
streamlink/streamlink | 1,696 | streamlink__streamlink-1696 | [
"1695"
] | 8029d10153b51e76a83a7d6d29c7d7bb83256feb | diff --git a/src/streamlink/plugins/tvcatchup.py b/src/streamlink/plugins/tvcatchup.py
--- a/src/streamlink/plugins/tvcatchup.py
+++ b/src/streamlink/plugins/tvcatchup.py
@@ -5,7 +5,7 @@
from streamlink.stream import HLSStream
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
-_url_re = re.compile(r"http://(?:www\.)?tvcatchup.com/watch/\w+")
+_url_re = re.compile(r"https?://(?:www\.)?tvcatchup.com/watch/\w+")
_stream_re = re.compile(r'''source.*?(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''')
| diff --git a/tests/test_plugin_tvcatchup.py b/tests/test_plugin_tvcatchup.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_tvcatchup.py
@@ -0,0 +1,16 @@
+import unittest
+
+from streamlink.plugins.tvcatchup import TVCatchup
+
+
+class TestPluginTVCatchup(unittest.TestCase):
+ def test_can_handle_url(self):
+ # should match
+ self.assertTrue(TVCatchup.can_handle_url("http://tvcatchup.com/watch/bbcone"))
+ self.assertTrue(TVCatchup.can_handle_url("http://www.tvcatchup.com/watch/five"))
+ self.assertTrue(TVCatchup.can_handle_url("https://www.tvcatchup.com/watch/bbctwo"))
+
+ # shouldn't match
+ self.assertFalse(TVCatchup.can_handle_url("http://www.tvplayer.com/"))
+ self.assertFalse(TVCatchup.can_handle_url("http://www.tvcatchup.com/"))
+ self.assertFalse(TVCatchup.can_handle_url("http://www.youtube.com/"))
\ No newline at end of file
| [patch] Support https on tvcatchup.com
The problem:
```
tmp (lonefox): streamlink https://tvcatchup.com/watch/bbcone best
error: No plugin can handle URL: https://tvcatchup.com/watch/bbcone
```
The solution:
```
diff -bur streamlink-0.12.1-orig/src/streamlink/plugins/tvcatchup.py streamlink-0.12.1/src/streamlink/plugins/tvcatchup.py
--- streamlink-0.12.1-orig/src/streamlink/plugins/tvcatchup.py 2018-05-07 18:01:30.000000000 +0300
+++ streamlink-0.12.1/src/streamlink/plugins/tvcatchup.py 2018-05-26 08:54:47.000000000 +0300
@@ -5,7 +5,7 @@
from streamlink.stream import HLSStream
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
-_url_re = re.compile(r"http://(?:www\.)?tvcatchup.com/watch/\w+")
+_url_re = re.compile(r"https?://(?:www\.)?tvcatchup.com/watch/\w+")
_stream_re = re.compile(r'''source.*?(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''')
```
| 2018-05-26T08:30:49 |
|
streamlink/streamlink | 1,705 | streamlink__streamlink-1705 | [
"911"
] | c408ec6deec0abd28d98a2f64f674a77c4807ff9 | diff --git a/src/streamlink/plugins/ustvnow.py b/src/streamlink/plugins/ustvnow.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/ustvnow.py
@@ -0,0 +1,96 @@
+import re
+
+from streamlink.plugin import Plugin, PluginArguments, PluginArgument
+from streamlink.plugin.api import http, useragents
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
+
+
+class USTVNow(Plugin):
+ _url_re = re.compile(r"https?://(?:watch\.)?ustvnow\.com(?:/(?:watch|guide)/(?P<scode>\w+))?")
+ _token_re = re.compile(r'''var\s+token\s*=\s*"(.*?)";''')
+ _login_url = "https://watch.ustvnow.com/account/login"
+ _signin_url = "https://watch.ustvnow.com/account/signin"
+ _guide_url = "http://m.ustvnow.com/gtv/1/live/channelguidehtml"
+ _stream_url = "http://m.ustvnow.com/stream/1/live/view"
+
+ arguments = PluginArguments(
+ PluginArgument(
+ "username",
+ metavar="USERNAME",
+ required=True,
+ help="Your USTV Now account username"
+ ),
+ PluginArgument(
+ "password",
+ sensitive=True,
+ metavar="PASSWORD",
+ required=True,
+ help="Your USTV Now account password",
+ prompt="Enter USTV Now account password"
+ ),
+ PluginArgument(
+ "station-code",
+ metavar="CODE",
+ help="USTV Now station code"
+ ),
+ )
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def login(self, username, password):
+ r = http.get(self._signin_url)
+ csrf = None
+
+ for input in itertags(r.text, "input"):
+ if input.attributes['name'] == "csrf_ustvnow":
+ csrf = input.attributes['value']
+
+ self.logger.debug("CSRF: {0}", csrf)
+
+ r = http.post(self._login_url, data={'csrf_ustvnow': csrf,
+ 'signin_email': username,
+ 'signin_password': password,
+ 'signin_remember': '1'})
+ m = self._token_re.search(r.text)
+ return m and m.group(1)
+
+ def _get_streams(self):
+ """
+ Finds the streams from tvcatchup.com.
+ """
+ token = self.login(self.get_option("username"), self.get_option("password"))
+ m = self._url_re.match(self.url)
+ scode = m and m.group("scode") or self.get_option("station_code")
+
+ res = http.get(self._guide_url)
+
+ channels = {}
+ for t in itertags(res.text, "a"):
+ if t.attributes.get('cs'):
+ channels[t.attributes.get('cs').lower()] = t.attributes.get('title').replace("Watch ", "")
+
+ if not scode:
+ self.logger.error("Station code not provided, use --ustvnow-station-code.")
+ self.logger.error("Available stations are: {0}", ", ".join(channels.keys()))
+ return
+
+ if scode in channels:
+ self.logger.debug("Finding streams for: {0}", channels.get(scode))
+
+ r = http.get(self._stream_url, params={"scode": scode,
+ "token": token,
+ "br_n": "Firefox",
+ "br_v": "52",
+ "br_d": "desktop"},
+ headers={"User-Agent": useragents.FIREFOX})
+
+ data = http.json(r)
+ return HLSStream.parse_variant_playlist(self.session, data["stream"])
+ else:
+ self.logger.error("Invalid station-code: {0}", scode)
+
+
+__plugin__ = USTVNow
| diff --git a/tests/test_plugin_ustvnow.py b/tests/test_plugin_ustvnow.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_ustvnow.py
@@ -0,0 +1,16 @@
+import unittest
+
+from streamlink.plugins.ustvnow import USTVNow
+
+
+class TestPluginUSTVNow(unittest.TestCase):
+ def test_can_handle_url(self):
+ self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com"))
+ self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/"))
+ self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com/watch"))
+ self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch"))
+ self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch/syfy"))
+ self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/guide/foxnews"))
+
+ def test_can_not_handle_url(self):
+ self.assertFalse(USTVNow.can_handle_url("http://www.tvplayer.com"))
| Plugin request: USTVnow
### Checklist
- [ ] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
Hi, i would like to request a plugin for [USTVnow](https://www.ustvnow.com/). They offer [free](https://www.ustvnow.com/register.php?sub=7) access to [7 US TV Channels](https://support.ustvnow.com/hc/en-us/articles/214145143-What-plans-channels-are-available-) and paid access to 30 channels, [some in HD](https://support.ustvnow.com/hc/en-us/articles/214145203-What-USTVnow-channels-are-available-in-HD-on-the-paid-plans-).
Access-URL:
http://m.ustvnow.com/iphone (iStuff)
http://www.ustvnow.com/gtv/ (SmartTVs)
http://watch.ustvnow.com/guide (Webbrowsers)
The direct links are javascript-obfuscated and i can't see deep-links to the programs
They use various protocols, including HLS and RTMP, **but HLS access only works for 30 days on the free account**. HLS seems to offer a bit more quality (even on the SD-Only free account)
There are already several projects in python that can produce an m3u playlist (the urls are only valid for about 30mins):
https://github.com/mathsgrinds/ustvnow-iptv-m3u-playlist (HLS playlist, worked a week ago)
https://github.com/guilleiguaran/ustvnow-m3u-server (RTMP playlist, stopped working about a year ago).
A choice of the protocol(s) would be great (as mentioned, HLS only works for 30 days for free), but i would be happy with anything that "just works" :)
Thanks :D
| Hmm this one might be a bit questionable, if they're obfuscating links or doing any sort of encryption it might be difficult to support. Looking at that script that was working a week ago, it looks like they were specifically pulling it as a mobile stream, so that's probably fixed whatever mechanic was allowing that bypass. Thanks for the request, we'll see if someone wants to investigate it.
Hiya, i'm not sure obfuscating was the right term, i meant they are not simply using www.ustvnow.com/abc etc links in the browser but some javascript-links, but i'm pretty sure they don't use encryption, at least when i was testing it a year ago, the rtmp links where standard rtmp (not rtmps etc)... Also, the hls playlists worked fine last week (before my trial expired) with tvheadend, which does NOT support encrypted hls-stream...
But then again, you can probably see more from the two python-examples than i can ever tell you ;). Just one thing i forgot, they also offer access via Roku, so there has to be a (relativly) stable api... In any case, thanks for your time :)
Sounds cool, I'll take a look :)
Edit: thanks for the detailed request!
Just FYI I am using https://github.com/mathsgrinds/ustvnow-iptv-m3u-playlist in termux on android and generating a playlist that works beautfully.
What I have been unable to detgermine is how long the links are valid it seems somewhat random
You probably should try the mathgrinds USTVNow code | 2018-05-28T23:35:04 |
streamlink/streamlink | 1,717 | streamlink__streamlink-1717 | [
"173"
] | 9d63e64bbcbdaac647cd5059704c287819069d4a | diff --git a/src/streamlink/plugins/steam.py b/src/streamlink/plugins/steam.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/steam.py
@@ -0,0 +1,210 @@
+import base64
+import logging
+import re
+import time
+
+from Crypto.Cipher import PKCS1_v1_5
+from Crypto.PublicKey import RSA
+
+import streamlink
+from streamlink.exceptions import FatalPluginError
+from streamlink.plugin import Plugin, PluginArguments, PluginArgument
+from streamlink.plugin.api import http
+from streamlink.plugin.api import validate
+from streamlink.plugin.api.validate import Schema
+from streamlink.stream.dash import DASHStream
+
+log = logging.getLogger(__name__)
+
+
+class SteamLoginFailed(Exception):
+ pass
+
+
+class SteamBroadcastPlugin(Plugin):
+ _url_re = re.compile(r"https?://steamcommunity.com/broadcast/watch/(\d+)")
+ _get_broadcast_url = "https://steamcommunity.com/broadcast/getbroadcastmpd/"
+ _user_agent = "streamlink/{}".format(streamlink.__version__)
+ _broadcast_schema = Schema({
+ "success": validate.any("ready", "unavailable", "waiting", "waiting_to_start", "waiting_for_start"),
+ "retry": int,
+ "broadcastid": validate.any(validate.text, int),
+ validate.optional("url"): validate.url(),
+ validate.optional("viewertoken"): validate.text
+ })
+ _get_rsa_key_url = "https://steamcommunity.com/login/getrsakey/"
+ _rsa_key_schema = validate.Schema({
+ "publickey_exp": validate.all(validate.text, validate.transform(lambda x: int(x, 16))),
+ "publickey_mod": validate.all(validate.text, validate.transform(lambda x: int(x, 16))),
+ "success": True,
+ "timestamp": validate.text,
+ "token_gid": validate.text
+ })
+ _dologin_url = "https://steamcommunity.com/login/dologin/"
+ _dologin_schema = validate.Schema({
+ "success": bool,
+ "requires_twofactor": bool,
+ validate.optional("message"): validate.text,
+ validate.optional("emailauth_needed"): bool,
+ validate.optional("emaildomain"): validate.text,
+ validate.optional("emailsteamid"): validate.text,
+ validate.optional("login_complete"): bool,
+ validate.optional("captcha_needed"): bool,
+ validate.optional("captcha_gid"): validate.any(validate.text, int)
+ })
+ _captcha_url = "https://steamcommunity.com/public/captcha.php?gid={}"
+
+ arguments = PluginArguments(
+ PluginArgument(
+ "email",
+ metavar="EMAIL",
+ requires=["password"],
+ help="""
+ A Steam account email address to access friends/private streams
+ """
+ ),
+ PluginArgument(
+ "password",
+ metavar="PASSWORD",
+ sensitive=True,
+ help="""
+ A Steam account password to use with --steam-email.
+ """
+ ))
+
+ def __init__(self, url):
+ super(SteamBroadcastPlugin, self).__init__(url)
+ http.headers["User-Agent"] = self._user_agent
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ @property
+ def donotcache(self):
+ return str(int(time.time() * 1000))
+
+ def encrypt_password(self, email, password):
+ """
+ Get the RSA key for the user and encrypt the users password
+ :param email: steam account
+ :param password: password for account
+ :return: encrypted password
+ """
+ res = http.get(self._get_rsa_key_url, params=dict(username=email, donotcache=self.donotcache))
+ rsadata = http.json(res, schema=self._rsa_key_schema)
+
+ rsa = RSA.construct((rsadata["publickey_mod"], rsadata["publickey_exp"]))
+ cipher = PKCS1_v1_5.new(rsa)
+ return base64.b64encode(cipher.encrypt(password.encode("utf8"))), rsadata["timestamp"]
+
+ def dologin(self, email, password, emailauth="", emailsteamid="", captchagid="-1", captcha_text="", twofactorcode=""):
+ """
+ Logs in to Steam
+
+ """
+ epassword, rsatimestamp = self.encrypt_password(email, password)
+
+ login_data = {
+ 'username': email,
+ "password": epassword,
+ "emailauth": emailauth,
+ "loginfriendlyname": "Streamlink",
+ "captchagid": captchagid,
+ "captcha_text": captcha_text,
+ "emailsteamid": emailsteamid,
+ "rsatimestamp": rsatimestamp,
+ "remember_login": True,
+ "donotcache": self.donotcache,
+ "twofactorcode": twofactorcode
+ }
+
+ res = http.post(self._dologin_url, data=login_data)
+
+ resp = http.json(res, schema=self._dologin_schema)
+
+ if not resp[u"success"]:
+ if resp.get(u"captcha_needed"):
+ # special case for captcha
+ captchagid = resp[u"captcha_gid"]
+ log.error("Captcha result required, open this URL to see the captcha: {}".format(
+ self._captcha_url.format(captchagid)))
+ try:
+ captcha_text = self.input_ask("Captcha text")
+ except FatalPluginError:
+ captcha_text = None
+ if not captcha_text:
+ return False
+ else:
+ # If the user must enter the code that was emailed to them
+ if resp.get(u"emailauth_needed"):
+ if not emailauth:
+ try:
+ emailauth = self.input_ask("Email auth code required")
+ except FatalPluginError:
+ emailauth = None
+ if not emailauth:
+ return False
+ else:
+ raise SteamLoginFailed("Email auth key error")
+
+ # If the user must enter a two factor auth code
+ if resp.get(u"requires_twofactor"):
+ try:
+ twofactorcode = self.input_ask("Two factor auth code required")
+ except FatalPluginError:
+ twofactorcode = None
+ if not twofactorcode:
+ return False
+
+ if resp.get(u"message"):
+ raise SteamLoginFailed(resp[u"message"])
+
+ return self.dologin(email, password,
+ emailauth=emailauth,
+ emailsteamid=resp.get(u"emailsteamid", u""),
+ captcha_text=captcha_text,
+ captchagid=captchagid,
+ twofactorcode=twofactorcode)
+ elif resp.get("login_complete"):
+ return True
+ else:
+ log.error("Something when wrong when logging in to Steam")
+ return False
+
+ def login(self, email, password):
+ log.info("Attempting to login to Steam as {}".format(email))
+ return self.dologin(email, password)
+
+ def _get_broadcast_stream(self, steamid, viewertoken=0):
+ res = http.get(self._get_broadcast_url,
+ params=dict(broadcastid=0,
+ steamid=steamid,
+ viewertoken=viewertoken))
+ return http.json(res, schema=self._broadcast_schema)
+
+ def _get_streams(self):
+ streamdata = None
+ if self.get_option("email"):
+ if self.login(self.get_option("email"), self.get_option("password")):
+ log.info("Logged in as {0}".format(self.get_option("email")))
+ self.save_cookies(lambda c: "steamMachineAuth" in c.name)
+
+ # extract the steam ID from the URL
+ steamid = self._url_re.match(self.url).group(1)
+
+ while streamdata is None or streamdata[u"success"] in ("waiting", "waiting_for_start"):
+ streamdata = self._get_broadcast_stream(steamid)
+
+ if streamdata[u"success"] == "ready":
+ return DASHStream.parse_manifest(self.session, streamdata["url"])
+ elif streamdata[u"success"] == "unavailable":
+ log.error("This stream is currently unavailable")
+ return
+ else:
+ r = streamdata[u"retry"] / 1000.0
+ log.info("Waiting for stream, will retry again in {} seconds...".format(r))
+ time.sleep(r)
+
+
+__plugin__ = SteamBroadcastPlugin
| diff --git a/tests/test_plugin_steam.py b/tests/test_plugin_steam.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_steam.py
@@ -0,0 +1,15 @@
+import unittest
+
+from streamlink.plugins.steam import SteamBroadcastPlugin
+
+
+class TestPluginSteamBroadcastPlugin(unittest.TestCase):
+ def test_can_handle_url(self):
+ self.assertTrue(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com/broadcast/watch/12432432'))
+ self.assertTrue(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast/watch/342342'))
+
+ def test_can_handle_url_negative(self):
+ # shouldn't match
+ self.assertFalse(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast'))
+ self.assertFalse(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com'))
+ self.assertFalse(SteamBroadcastPlugin.can_handle_url('https://youtube.com'))
| Support for Steam Broadcasting
Hey boys and girls,
Recently jumped ship over to streamlink and was wondering if you guys could figure out how to enable support for Steam Broadcasting.
The folks over at livestreamer gave it a crack, but development for it soon died out.
(Here's the link to the livestreamer issue thread: https://github.com/chrippa/livestreamer/issues/621)
This may be a bit of an ask because it requires the user to be logged in but I'm fully happy to enter in my steam information to get it working.
Here's a link to the directory of live broadcasts: http://steamcommunity.com/?subsection=broadcasts
Hope this isn't too much of a challenge for you guys.
Cheers.
| @desperation123 Only some streams requires the user to be logged in? Because i tried some of them and works without logging.
@RosadinTV Oh right, I'm guessing it's due to this option setting.
http://i.imgur.com/OHpNGgk.png
I've got a mate who I always watch and I always have to log in.
Must have his setting on one of the friends settings.
@desperation123 Got it, the problem here (asides of the plugin) is that Streamlink currently dont support this type of streaming method, the stream is based in separated audio and video chunks.
@beardypig This may work with pymp4? (Video= video/mp4 with avc1.4d4032 codec and Audio= audio/mp4 with mp4a.40.2 codec)
Edit: Seems like here is more info about this protocol: https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
I will take a look. DASH isn't currently supported, but I am working on it :-)
Took a look a the steam broadcasts, it seems pretty easy to get the public stream URLs. Once I finish working on supporting DASH streams it won't be too hard to complete the plugin. I'll have to get a friend to broadcast something to get that bit working though.
| 2018-05-30T22:15:34 |
streamlink/streamlink | 1,721 | streamlink__streamlink-1721 | [
"789"
] | 4924b8a15a45de36b459cf1ed20296d414a85c15 | diff --git a/src/streamlink/plugins/funimationnow.py b/src/streamlink/plugins/funimationnow.py
--- a/src/streamlink/plugins/funimationnow.py
+++ b/src/streamlink/plugins/funimationnow.py
@@ -1,23 +1,39 @@
from __future__ import print_function
+import logging
import random
import re
+from streamlink.compat import urljoin
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import http
from streamlink.plugin.api import useragents
+from streamlink.plugin.api import validate
+from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
from streamlink.stream import HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
+log = logging.getLogger(__name__)
+
class Experience(object):
- api_base = "https://prod-api-funimationnow.dadcdigital.com/api"
- show_api_url = api_base + "/source/catalog/title/experience/{experience_id}/"
- sources_api_url = api_base + "/source/catalog/video/{experience_id}/signed/"
+ CSRF_NAME = "csrfmiddlewaretoken"
+ login_url = "https://www.funimation.com/log-in/"
+ api_base = "https://www.funimation.com/api"
+ login_api_url = "https://prod-api-funimationnow.dadcdigital.com/api/auth/login/"
+ show_api_url = api_base + "/experience/{experience_id}/"
+ sources_api_url = api_base + "/showexperience/{experience_id}/"
languages = ["english", "japanese"]
alphas = ["uncut", "simulcast"]
+ login_schema = validate.Schema(validate.any(
+ {"success": False,
+ "error": validate.text},
+ {"token": validate.text,
+ "user": {"id": int}}
+ ))
+
def __init__(self, experience_id):
"""
:param experience_id: starting experience_id, may be changed later
@@ -25,6 +41,23 @@ def __init__(self, experience_id):
self.experience_id = experience_id
self._language = None
self.cache = {}
+ self.token = None
+
+ def request(self, method, url, *args, **kwargs):
+ headers = kwargs.pop("headers", {})
+ if self.token:
+ headers.update({"Authorization": "Token {0}".format(self.token)})
+ http.cookies.update({"src_token": self.token})
+
+ log.debug("Making {0}request to {1}".format("authorized " if self.token else "", url))
+
+ return http.request(method, url, *args, headers=headers, **kwargs)
+
+ def get(self, *args, **kwargs):
+ return self.request("GET", *args, **kwargs)
+
+ def post(self, *args, **kwargs):
+ return self.request("POST", *args, **kwargs)
@property
def pinst_id(self):
@@ -34,7 +67,8 @@ def pinst_id(self):
def _update(self):
api_url = self.show_api_url.format(experience_id=self.experience_id)
- res = http.get(api_url)
+ log.debug("Requesting experience data: {0}".format(api_url))
+ res = self.get(api_url)
data = http.json(res)
self.cache[self.experience_id] = data
@@ -91,19 +125,47 @@ def sources(self):
:return: sources dict
"""
api_url = self.sources_api_url.format(experience_id=self.experience_id)
- res = http.get(api_url, params=dict(pinstId=self.pinst_id))
+ res = self.get(api_url, params={"pinst_id": self.pinst_id})
return http.json(res)
+ def login_csrf(self):
+ r = http.get(self.login_url)
+ for input in itertags(r.text, "input"):
+ if input.attributes.get("name") == self.CSRF_NAME:
+ return input.attributes.get("value")
+
+ def login(self, email, password):
+ log.debug("Attempting to login as {0}".format(email))
+ r = self.post(self.login_api_url,
+ data={'username': email, 'password': password, self.CSRF_NAME: self.login_csrf()},
+ raise_for_status=False,
+ headers={"Referer": "https://www.funimation.com/log-in/"})
+ d = http.json(r, schema=self.login_schema)
+ self.token = d.get("token", None)
+ return self.token is not None
+
class FunimationNow(Plugin):
arguments = PluginArguments(
+ PluginArgument(
+ "email",
+ argument_name="funimation-email",
+ requires=["password"],
+ help="Email address for your Funimation account."
+ ),
+ PluginArgument(
+ "password",
+ argument_name="funimation-password",
+ sensitive=True,
+ help="Password for your Funimation account."
+ ),
PluginArgument(
"language",
argument_name="funimation-language",
choices=["en", "ja", "english", "japanese"],
default="english",
help="""
- The audio language to use for Funimation streams; japanese or english.
+ The audio language to use for the stream; japanese or english.
Default is "english".
"""
@@ -135,31 +197,39 @@ def _get_streams(self):
# remap en to english, and ja to japanese
rlanguage = {"en": "english", "ja": "japanese"}.get(self.get_option("language").lower(),
self.get_option("language").lower())
+ if "_Incapsula_Resource" in res.text:
+ self.bypass_incapsula(res)
+ res = http.get(self.url)
id_m = self.experience_id_re.search(res.text)
experience_id = id_m and int(id_m.group(1))
if experience_id:
- self.logger.debug("Found experience ID: {0}", experience_id)
+ log.debug("Found experience ID: {0}", experience_id)
exp = Experience(experience_id)
+ if self.get_option("email") and self.get_option("password"):
+ if exp.login(self.get_option("email"), self.get_option("password")):
+ log.info("Logged in to Funimation as {0}", self.get_option("email"))
+ else:
+ log.warning("Failed to login")
- self.logger.debug("Found episode: {0}", exp.episode_info["episodeTitle"])
- self.logger.debug(" has languages: {0}", ", ".join(exp.episode_info["languages"].keys()))
- self.logger.debug(" requested language: {0}", rlanguage)
- self.logger.debug(" current language: {0}", exp.language)
+ log.debug("Found episode: {0}", exp.episode_info["episodeTitle"])
+ log.debug(" has languages: {0}", ", ".join(exp.episode_info["languages"].keys()))
+ log.debug(" requested language: {0}", rlanguage)
+ log.debug(" current language: {0}", exp.language)
if rlanguage != exp.language:
- self.logger.debug("switching language to: {0}", rlanguage)
+ log.debug("switching language to: {0}", rlanguage)
exp.set_language(rlanguage)
if exp.language != rlanguage:
- self.logger.warning("Requested language {0} is not available, continuing with {1}",
- rlanguage, exp.language)
+ log.warning("Requested language {0} is not available, continuing with {1}",
+ rlanguage, exp.language)
else:
- self.logger.debug("New experience ID: {0}", exp.experience_id)
+ log.debug("New experience ID: {0}", exp.experience_id)
subtitles = None
stream_metadata = {}
disposition = {}
for subtitle in exp.subtitles():
- self.logger.info("Subtitles: {0}", subtitle["src"])
+ log.debug("Subtitles: {0}", subtitle["src"])
if subtitle["src"].endswith(".vtt") or subtitle["src"].endswith(".srt"):
sub_lang = {"en": "eng", "ja": "jpn"}[subtitle["language"]]
# pick the first suitable subtitle stream
@@ -167,7 +237,13 @@ def _get_streams(self):
stream_metadata["s:s:0"] = ["language={0}".format(sub_lang)]
stream_metadata["s:a:0"] = ["language={0}".format(exp.language_code)]
- for item in exp.sources()["items"]:
+ sources = exp.sources()
+ if 'errors' in sources:
+ for error in sources['errors']:
+ log.error("{0} : {1}".format(error['title'], error['detail']))
+ return
+
+ for item in sources["items"]:
url = item["src"]
if ".m3u8" in url:
for q, s in HLSStream.parse_variant_playlist(self.session, url).items():
@@ -186,7 +262,24 @@ def _get_streams(self):
yield self.mp4_quality, s
else:
- self.logger.error("Could not find experience ID?!")
+ log.error("Could not find experience ID?!")
+
+ def bypass_incapsula(self, res):
+ log.info("Attempting to by-pass Incapsula...")
+ self.clear_cookies(lambda c: "incap" in c.name)
+ for m in re.finditer(r'''"([A-Z0-9]+)"''', res.text):
+ d = m.group(1)
+ # decode the encoded blob to text
+ js = "".join(map(lambda i: chr(int(i, 16)), [d[x:x + 2] for x in range(0, len(d), 2)]))
+ jsm = re.search(r'''"GET","([^"]+)''', js)
+ url = jsm and jsm.group(1)
+ if url:
+ log.debug("Found Incapsula auth URL: {0}", url)
+ res = http.get(urljoin(self.url, url))
+ success = res.status_code == 200
+ if success:
+ self.save_cookies(lambda c: "incap" in c.name)
+ return success
__plugin__ = FunimationNow
| diff --git a/tests/test_plugin_funimationnow.py b/tests/test_plugin_funimationnow.py
--- a/tests/test_plugin_funimationnow.py
+++ b/tests/test_plugin_funimationnow.py
@@ -38,9 +38,11 @@ def test_arguments(self):
}
setup_plugin_args(session, parser)
-
self.assertSequenceEqual(plugin_parser.add_argument.mock_calls,
- [call('--funimation-language',
+ [call('--funimation-email', help=ANY),
+ call('--funimation-password', help=ANY),
+ call('--funimation-language',
choices=["en", "ja", "english", "japanese"],
default="english", help=ANY),
call('--funimation-mux-subtitles', action="store_true", help=ANY)])
+
| Funimation Login
- [X] This is a feature request.
### Description
Is it possible to add a login feature for funimation, like in the crunchyroll plugin?
| I'd like to second this if possible.
Ah, was going to work on but forgot... I'll take a look :-)
I have created a branch on my fork which supports logins for Funimation - it could do with some real world testing: https://github.com/beardypig/streamlink/tree/funimation
@beardypig Has this addition been merged yet? If not, are there any plans to merge the funimation login functionality any time soon (I just want to be sure before I create an AUR package of your fork)?
@vinnyA3 I just checked the master branch and those changes are not in there.
@vinnyA3 yeah, I plan to merge it. But, I haven’t done any proper testing and no one reported back if they tried it. Have you tested it? | 2018-05-31T22:40:28 |
streamlink/streamlink | 1,727 | streamlink__streamlink-1727 | [
"1723"
] | 35a43db395e49749111d37b104c5c30abe5296bd | diff --git a/src/streamlink/plugins/facebook.py b/src/streamlink/plugins/facebook.py
--- a/src/streamlink/plugins/facebook.py
+++ b/src/streamlink/plugins/facebook.py
@@ -1,26 +1,42 @@
import re
from streamlink.plugin import Plugin
-from streamlink.stream import HLSStream
-
-_playlist_url = "https://www.facebook.com/video/playback/playlist.m3u8?v={0}"
-
-_url_re = re.compile(r"http(s)?://(www\.)?facebook\.com/[^/]+/videos/(?P<video_id>\d+)")
+from streamlink.plugin.api import http, useragents
+from streamlink.stream import DASHStream, HTTPStream
+from streamlink.utils import parse_json
class Facebook(Plugin):
+ _url_re = re.compile(r"https?://(?:www\.)?facebook\.com/[^/]+/videos")
+ _mpd_re = re.compile(r'''(sd|hd)_src["']?\s*:\s*(?P<quote>["'])(?P<url>.+?)(?P=quote)''')
+ _playlist_re = re.compile(r'''video:\[({url:".+?}\])''')
+ _plurl_re = re.compile(r'''url:"(.*?)"''')
+
@classmethod
def can_handle_url(cls, url):
- return _url_re.match(url)
+ return cls._url_re.match(url)
- @Plugin.broken(990)
def _get_streams(self):
- match = _url_re.match(self.url)
- video = match.group("video_id")
+ res = http.get(self.url, headers={"User-Agent": useragents.CHROME})
+ with open("temp.html", "w") as f:
+ f.write(res.text)
+
+ for match in self._mpd_re.finditer(res.text):
+ manifest_url = match.group("url")
+ if "\\/" in manifest_url:
+ # if the URL is json encoded, decode it
+ manifest_url = parse_json("\"{}\"".format(manifest_url))
+ for s in DASHStream.parse_manifest(self.session, manifest_url).items():
+ yield s
+ else:
+ match = self._playlist_re.search(res.text)
+ playlist = match and match.group(1)
+ if playlist:
+ for url in {url.group(1) for url in self._plurl_re.finditer(playlist)}:
+ yield "live", HTTPStream(self.session, url)
+
- playlist = _playlist_url.format(video)
- return HLSStream.parse_variant_playlist(self.session, playlist)
__plugin__ = Facebook
| Request: Add more functions to facebook plugin
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
Reminder that with the new initial support of Mpeg Dash #880 and #990 might be fixable now, depending on what streamlink supports and how Facebook's videos and livestreaming has changed since this was last looked it.
| there dash stream does not work with streamlink
```
[console][info] Found matching plugin dash for URL https://video.fhaj1-1.fna.fbcdn.net/.../live-dash/dash-abr4/000.mpd?...
[plugin.dash][debug] Parsing MPD URL: https://video.fhaj1-1.fna.fbcdn.net/.../live-dash/dash-abr4/000.mpd?...
[console][info] Available streams: 240p (worst), 360p, 480p, 720p (best)
[console][info] Opening stream: 720p (dash)
[stream.dash][debug] Opening DASH reader for: live-hd1-v
[stream.dash][debug] Opening DASH reader for: live-md-a
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-hd1-v))
[stream.dash][debug] Reloading manifest (live-hd1-v)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-md-a))
[stream.dash][debug] Reloading manifest (live-md-a)
[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-18118-462 -i /tmp/ffmpeg-18118-804 -c:v copy -c:a copy -copyts -f matroska pipe:1
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-18118-462
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-18118-804
[console][debug] Pre-buffering 8192 bytes
[stream.dash][debug] Download of segment: .../live-dash/live-hd1-v/000-init.m4v complete
[stream.dash][debug] Download of segment: .../live-dash/live-md-a/000-init.m4a complete
[stream.dash][debug] Download of segment: .../live-dash/live-hd1-v/000-11894667.m4v complete
[stream.dash][debug] Download of segment: .../live-dash/live-md-a/000-11894667.m4a complete
[console][info] Starting player: /usr/bin/mpv
[console][debug] Writing stream to output
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-hd1-v))
[stream.dash][debug] Reloading manifest (live-hd1-v)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-md-a))
[stream.dash][debug] Reloading manifest (live-md-a)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-hd1-v))
[stream.dash][debug] Reloading manifest (live-hd1-v)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-md-a))
[stream.dash][debug] Reloading manifest (live-md-a)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-hd1-v))
[stream.dash][debug] Reloading manifest (live-hd1-v)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live-md-a))
[stream.dash][debug] Reloading manifest (live-md-a)
```
@back-to any chance of a redacted mpd on gist?
sure https://gist.github.com/back-to/bc2437374b0ae1a47d67eb3a5b386e2f
@back-to is it OK to include that mpd in the test resources?
@back-to would you be able to upload 2 mpds 5 seconds apart? I cannot see why it wouldn't work. (I don't use Facebook).
here is a git-diff
https://gist.github.com/back-to/bc2437374b0ae1a47d67eb3a5b386e2f#file-123-diff
it does not change that much
---
the probleme is
it works for **2 sec**,
but it won't reload for the next segments
Perfect, thanks @back-to
Looks like they don't update `MPD@publishTime`... I'm working on a more reliable method to detect changes in the segments. | 2018-06-01T23:29:48 |
|
streamlink/streamlink | 1,731 | streamlink__streamlink-1731 | [
"1730"
] | 1efbd18f240e272cc3a8a09600c414f5e7dc6f90 | diff --git a/src/streamlink/plugins/vaughnlive.py b/src/streamlink/plugins/vaughnlive.py
--- a/src/streamlink/plugins/vaughnlive.py
+++ b/src/streamlink/plugins/vaughnlive.py
@@ -40,10 +40,10 @@ class VaughnLive(Plugin):
range(1, 6))]
origin = "https://vaughnlive.tv"
rtmp_server_map = {
- "594140c69edad": "192.240.105.171:1935",
- "585c4cab1bef1": "192.240.105.171:1935",
- "5940d648b3929": "192.240.105.171:1935",
- "5941854b39bc4": "192.240.105.171:1935"
+ "594140c69edad": "192.240.105.171:2935",
+ "585c4cab1bef1": "192.240.105.171:2935",
+ "5940d648b3929": "192.240.105.171:2935",
+ "5941854b39bc4": "192.240.105.171:2935"
}
name_remap = {"#vl": "live", "#btv": "btv", "#pt": "pt", "#igb": "instagib", "#vtv": "vtv"}
domain_map = {"vaughnlive": "#vl", "breakers": "#btv", "instagib": "#igb", "vapers": "#vtv", "pearltime": "#pt"}
| Vaughnlive RTMP port changed from 1935 to 2935
Very brief bug, very simple fix.
rtmp_server_map for all requests uses 192.240.105.171:1935 and doesn't work. (No data returned from stream)
rtmp_server_map change all requests to 192.240.105.171:2935 works for me.
| Thanks for the info @jshir, did you want to create a PR?
Sure, can you authorize me on this repository then? | 2018-06-02T21:13:07 |
|
streamlink/streamlink | 1,736 | streamlink__streamlink-1736 | [
"1574"
] | e2deec291585570ff2e94f8aa5e7a22acab3c085 | diff --git a/src/streamlink/plugins/crunchyroll.py b/src/streamlink/plugins/crunchyroll.py
--- a/src/streamlink/plugins/crunchyroll.py
+++ b/src/streamlink/plugins/crunchyroll.py
@@ -1,8 +1,8 @@
import argparse
+import datetime
import random
import re
import string
-import datetime
from streamlink.plugin import Plugin, PluginError, PluginArguments, PluginArgument
from streamlink.plugin.api import http, validate
@@ -159,16 +159,11 @@ def start_session(self, device_id, **kwargs):
Is recommended that you call this method before making any other calls
to make sure you have a valid session against the server.
"""
- params = {
- "device_id": device_id,
- "device_type": API_DEVICE_TYPE,
- "access_token": API_ACCESS_TOKEN,
- }
-
- if self.auth:
- params["auth"] = self.auth
-
- return self._api_call("start_session", params, **kwargs)
+ if self.session_id:
+ http.cookies["sess_id"] = self.session_id
+ res = http.get("https://www.crunchyroll.com",
+ headers={"User-Agent": API_USER_AGENT.format(self.locale)})
+ return res.cookies.get("sess_id", self.session_id)
def login(self, username, password, **kwargs):
"""Authenticates the session to be able to access restricted data from
@@ -236,7 +231,12 @@ class Crunchyroll(Plugin):
metavar="SESSION_ID",
help="""
Set a specific session ID for crunchyroll, can be used to bypass
- region restrictions.
+ region restrictions. If using an authenticated session ID, it is
+ recommended that the authentication parameters be omitted as the
+ session ID is account specific.
+
+ Note: The session ID will be overwritten if authentication is used
+ and the session ID does not match the account.
"""
),
# Deprecated, uses the general locale setting
@@ -331,15 +331,7 @@ def _create_api(self):
)
self.logger.debug("Creating session with locale: {0}", locale)
- try:
- api.session_id = api.start_session(device_id, schema=_session_schema)
- except CrunchyrollAPIError as err:
- if err.code == "bad_session":
- self.logger.debug("Current session has expired, creating a new one")
- api = CrunchyrollAPI(locale=locale)
- api.session_id = api.start_session(device_id, schema=_session_schema)
- else:
- raise err
+ api.session_id = api.start_session(device_id, schema=_session_schema)
# Save session and hope it lasts for a few hours
self.cache.set("session_id", api.session_id, 4 * 60 * 60)
@@ -349,7 +341,7 @@ def _create_api(self):
self.logger.debug("Using saved credentials")
elif self.options.get("username"):
try:
- self.logger.info("Attempting to login using username and password")
+ self.logger.debug("Attempting to login using username and password")
login = api.login(
self.options.get("username"),
self.options.get("password"),
@@ -357,6 +349,11 @@ def _create_api(self):
)
api.auth = login["auth"]
+ user_session_id = api.start_session(device_id, schema=_session_schema)
+ if user_session_id != api.session_id:
+ self.logger.warning("Session ID does not match account, resetting session ID")
+ api.session_id = user_session_id
+
self.logger.info("Successfully logged in as '{0}'",
login["user"]["username"] or login["user"]["email"])
| Media lookup error for specific Crunchyroll show only
----
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
When I try to play any episode of Nekomonogatari Kuro, streamlink gives me a media lookup error.
### Expected / Actual behavior
Fetch the available formats for any episode of Nekomonogatari Kuro from Crunchyroll.
/
```
[atemu@localhost ~]$ streamlink http://www.crunchyroll.com/nekomonogatari-black/episode-1-tsubasa-family-part-1-677667
[cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/nekomonogatari-black/episode-1-tsubasa-family-part-1-677667
[plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content
error: Media lookup error: You don't have permission to do this.
[atemu@localhost ~]$ streamlink http://www.crunchyroll.com/nekomonogatari-black/episode-2-tsubasa-family-part-2-677669
[cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/nekomonogatari-black/episode-2-tsubasa-family-part-2-677669
[plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content
error: Media lookup error: You don't have permission to do this.
[atemu@localhost ~]$ streamlink http://www.crunchyroll.com/nekomonogatari-black/episode-3-tsubasa-family-part-3-677671
[cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/nekomonogatari-black/episode-3-tsubasa-family-part-3-677671
[plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content
error: Media lookup error: You don't have permission to do this.
[atemu@localhost ~]$ streamlink http://www.crunchyroll.com/nekomonogatari-black/episode-4-tsubasa-family-part-4-677673
[cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/nekomonogatari-black/episode-4-tsubasa-family-part-4-677673
[plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content
error: Media lookup error: You don't have permission to do this.
```
### Reproduction steps / Explicit stream URLs to test
Be in the US (either physically or through VPN) or pass a US session ID to streamlink and use one of the following URLs:
1. http://www.crunchyroll.com/nekomonogatari-black/episode-1-tsubasa-family-part-1-677667
2. http://www.crunchyroll.com/nekomonogatari-black/episode-2-tsubasa-family-part-2-677669
3. http://www.crunchyroll.com/nekomonogatari-black/episode-3-tsubasa-family-part-3-677671
4. http://www.crunchyroll.com/nekomonogatari-black/episode-4-tsubasa-family-part-4-677673
### Log
```
[atemu@localhost ~]$ streamlink http://www.crunchyroll.com/nekomonogatari-black/episode-1-tsubasa-family-part-1-677667 -l debug
[cli][debug] OS: Linux-3.4.113-lineageos-gbe73925-armv7l-with-arch
[cli][debug] Python: 3.6.4
[cli][debug] Streamlink: 0.11.0
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/nekomonogatari-black/episode-1-tsubasa-family-part-1-677667
[plugin.crunchyroll][debug] Creating session with locale: en_US
[plugin.crunchyroll][debug] Session created
[plugin.crunchyroll][warning] No authentication provided, you won't be able to access premium restricted content
error: Media lookup error: You don't have permission to do this.
```
### Comments, screenshots, etc.
The show is geo blocked in my country (DE), so I have to use a US session ID and that worked with every other geoblocked Crunchyroll show so far.
I've also tried using a US VPN but that didn't make a difference either.
I have tested other geoblocked and non geoblocked Crunchyroll shows under the same conditions and they worked without any issues.
The show does not require CR Premium and plays in both the Official app and through youtube-dl.
| I had a similar issue as yours recently. As strange as it might sound, it seems like changing the locale settings of my system from DE to US fixed the problem. What is yours set to? Might be worth a try.
My whole system uses en_US.UTF-8
Try the option `--locale en_US`, to be sure - it appears the locale is set correctly, but worth a go perhaps.
It's giving me the same error unfortunately.
Do the links work for you? I want to make sure this isn't on my end.
Doesn't work for me with the same error. It's very odd to me that it's just this one series... I know we've seen issues with specific episodes in the past, but it's rarely been limited to a single set of episodes like this.
Is there a way to find out what exactly goes wrong?
The error message isn't very specific and the debug output doesn't tell you anything either.
I don't have a crunchy roll account at the moment to test this out :(
@beardypig You don't need one, this is a publicly available video (I don't have one either).
Atleast the first link does work for me.
That said, I first tried with a command from my shell history, which gave me the same "Media lookup error". I had to get a new session id to get it working again, as the other one was a few days old and seems to be expired.
So, did you try using a new session id?
Edit: all 4 links work for me
I'm always generating a new session ID using the CR API, so that could a source of error, but those session IDs have worked for all other Geo blocked shows I've watched so far (including the previous seasons of this Anime) and letting streamlink create a new session by itself while I'm in the US through a VPN doesn't work either.
Some shows are very picky for some reason, you need to have a session ID generated from the US and access the stream from an IP in the US (doesn't have to be the same IP though).
There does seem to be an issue with this particular show where it doesn't work with the session IDs generated by streamlink. | 2018-06-03T13:50:46 |
|
streamlink/streamlink | 1,744 | streamlink__streamlink-1744 | [
"1742"
] | 060d38d3f0acc2c4f3b463ea988361622a9b6544 | diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py
--- a/src/streamlink_cli/main.py
+++ b/src/streamlink_cli/main.py
@@ -663,10 +663,6 @@ def setup_console(output):
# All console related operations is handled via the ConsoleOutput class
console = ConsoleOutput(output, streamlink)
- # We don't want log output when we are printing JSON or a command-line.
- if not any(getattr(args, attr) for attr in QUIET_OPTIONS):
- console.set_level(args.loglevel)
-
if args.quiet_player:
log.warning("The option --quiet-player is deprecated since "
"version 1.4.3 as hiding player output is now "
@@ -955,7 +951,12 @@ def main():
console_out = sys.stderr
else:
console_out = sys.stdout
- setup_logging(console_out, args.loglevel)
+
+ # We don't want log output when we are printing JSON or a command-line.
+ silent_log = any(getattr(args, attr) for attr in QUIET_OPTIONS)
+ log_level = args.loglevel if not silent_log else "none"
+ setup_logging(console_out, log_level)
+
setup_streamlink()
# load additional plugins
setup_plugins(args.plugin_dirs)
@@ -963,8 +964,11 @@ def main():
# call setup args again once the plugin specific args have been added
setup_args(parser)
setup_config_args(parser)
+
# update the logging level if changed by a plugin specific config
- logger.root.setLevel(args.loglevel)
+ log_level = args.loglevel if not silent_log else "none"
+ logger.root.setLevel(log_level)
+
setup_console(console_out)
setup_http_session()
check_root()
| Problem with '--quiet' or '--json' options
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
With previous versions, add '--json' option to command line print JSON information without traditional debug info : `[console][info] ....`
Today, these debug lines are constantly present, whether the '--quiet' option is there or not
### Expected / Actual behavior
print desired information with the correct options
### Reproduction steps / Explicit stream URLs to test
1. `streamlink "https://rmcsport.bfmtv.com/mediaplayer/live-bfm-sport/" --json`
2. observe first line in the console output `[console][info] Found matching plugin bfmtv for URL https://rmcsport.bfmtv.com/mediaplayer/live-bfm-sport/`
| ok. I've to specify `-l none` ...
so quiet alias doesn't work | 2018-06-04T09:54:31 |
|
streamlink/streamlink | 1,746 | streamlink__streamlink-1746 | [
"1728"
] | 060d38d3f0acc2c4f3b463ea988361622a9b6544 | diff --git a/src/streamlink/plugins/youtube.py b/src/streamlink/plugins/youtube.py
--- a/src/streamlink/plugins/youtube.py
+++ b/src/streamlink/plugins/youtube.py
@@ -1,11 +1,14 @@
import re
+from requests import codes
+
from streamlink.compat import urlparse, parse_qsl
-from streamlink.plugin import Plugin, PluginError
-from streamlink.plugin.api import http, validate
+from streamlink.plugin import Plugin, PluginError, PluginArguments, PluginArgument
+from streamlink.plugin.api import http, validate, useragents
from streamlink.plugin.api.utils import parse_query
from streamlink.stream import HTTPStream, HLSStream
from streamlink.stream.ffmpegmux import MuxedStream
+from streamlink.utils import parse_json, search_dict
API_KEY = "AIzaSyBDBi-4roGzWJN4du9TuDMLd_jVTcVkKz4"
API_BASE = "https://www.googleapis.com/youtube/v3"
@@ -96,6 +99,7 @@ def parse_fmt_list(formatsmap):
_channelid_re = re.compile(r'meta itemprop="channelId" content="([^"]+)"')
_livechannelid_re = re.compile(r'meta property="og:video:url" content="([^"]+)')
+_ytdata_re = re.compile(r'window\["ytInitialData"\]\s*=\s*({.*?});', re.DOTALL)
_url_re = re.compile(r"""
http(s)?://(\w+\.)?youtube.com
(?:
@@ -138,6 +142,14 @@ class YouTube(Plugin):
258: 258,
}
+ arguments = PluginArguments(
+ PluginArgument(
+ "api-key",
+ sensitive=True,
+ help="API key to use for YouTube API requests"
+ )
+ )
+
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
@@ -204,13 +216,28 @@ def _create_adaptive_streams(self, info, streams, protected):
def _find_channel_video(self):
res = http.get(self.url)
- match = _channelid_re.search(res.text)
- if not match:
- return
- channel_id = match.group(1)
- self.logger.debug("Found channel_id: {0}".format(channel_id))
- return self._get_channel_video(channel_id)
+ datam = _ytdata_re.search(res.text)
+ if datam:
+ data = parse_json(datam.group(1))
+ # find the videoRenderer object, where there is a LVE NOW badge
+ for x in search_dict(data, 'videoRenderer'):
+ for bstyle in search_dict(x.get("badges", {}), "style"):
+ if bstyle == "BADGE_STYLE_TYPE_LIVE_NOW":
+ if x.get("videoId"):
+ self.logger.debug("Found channel video ID via HTML: {0}", x["videoId"])
+ return x["videoId"]
+
+ else:
+ # fall back on API
+ self.logger.debug("No channel data, falling back to API")
+ match = _channelid_re.search(res.text)
+ if not match:
+ return
+
+ channel_id = match.group(1)
+ self.logger.debug("Found channel_id: {0}".format(channel_id))
+ return self._get_channel_video(channel_id)
def _get_channel_video(self, channel_id):
query = {
@@ -218,15 +245,25 @@ def _get_channel_video(self, channel_id):
"type": "video",
"eventType": "live",
"part": "id",
- "key": API_KEY
+ "key": self.get_option("api_key") or API_KEY
}
- res = http.get(API_SEARCH_URL, params=query)
- videos = http.json(res, schema=_search_schema)
+ res = http.get(API_SEARCH_URL, params=query, raise_for_status=False)
+ if res.status_code == codes.ok:
+ videos = http.json(res, schema=_search_schema)
+
+ for video in videos:
+ video_id = video["id"]["videoId"]
+ self.logger.debug("Found video_id: {0}".format(video_id))
+ return video_id
+ else:
+ try:
+ errors = http.json(res, exception=ValueError)
+ self.logger.error("Cloud not resolve channel video:")
+ for error in errors['error']['errors']:
+ self.logger.error(" {message} ({reason})".format(**error))
- for video in videos:
- video_id = video["id"]["videoId"]
- self.logger.debug("Found video_id: {0}".format(video_id))
- return video_id
+ except ValueError:
+ self.logger.error("Cloud not resolve channel video: {0} error".format(res.status_code))
def _find_canonical_stream_info(self):
res = http.get(self.url)
@@ -263,6 +300,7 @@ def _get_stream_info(self, url):
_params_3 = {"eurl": "https://youtube.googleapis.com/v/{0}".format(video_id)}
count = 0
+ info_parsed = None
for _params in (_params_1, _params_2, _params_3):
count += 1
params = {"video_id": video_id}
@@ -281,6 +319,7 @@ def _get_stream_info(self, url):
return info_parsed
def _get_streams(self):
+ http.headers.update({'User-Agent': useragents.CHROME})
is_live = False
info = self._get_stream_info(self.url)
@@ -307,7 +346,7 @@ def _get_streams(self):
streams[name] = stream
- if is_live is False:
+ if not is_live:
streams, protected = self._create_adaptive_streams(info, streams, protected)
hls_playlist = info.get("hlsvp")
diff --git a/src/streamlink/utils/__init__.py b/src/streamlink/utils/__init__.py
--- a/src/streamlink/utils/__init__.py
+++ b/src/streamlink/utils/__init__.py
@@ -199,6 +199,26 @@ def memoizer(*args, **kwargs):
return memoizer
+def search_dict(data, key):
+ """
+ Search for a key in a nested dict, or list of nested dicts, and return the values.
+
+ :param data: dict/list to search
+ :param key: key to find
+ :return: matches for key
+ """
+ if isinstance(data, dict):
+ for dkey, value in data.items():
+ if dkey == key:
+ yield value
+ for result in search_dict(value, key):
+ yield result
+ elif isinstance(data, list):
+ for value in data:
+ for result in search_dict(value, key):
+ yield result
+
+
#####################################
# Deprecated functions, do not use. #
#####################################
| diff --git a/tests/test_utils.py b/tests/test_utils.py
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,7 +1,7 @@
import sys
from streamlink.plugin.api.validate import xml_element, text
-from streamlink.utils import update_scheme, url_equal
+from streamlink.utils import update_scheme, url_equal, search_dict
try:
import xml.etree.cElementTree as ET
@@ -124,3 +124,30 @@ def test_url_equal(self):
self.assertTrue(url_equal("http://test.com/test", "http://test.com/test#hello", ignore_fragment=True))
self.assertTrue(url_equal("http://test.com/test", "http://test2.com/test", ignore_netloc=True))
self.assertFalse(url_equal("http://test.com/test", "http://test2.com/test1", ignore_netloc=True))
+
+ def test_search_dict(self):
+
+ self.assertSequenceEqual(
+ list(search_dict(["one", "two"], "one")),
+ []
+ )
+ self.assertSequenceEqual(
+ list(search_dict({"two": "test2"}, "one")),
+ []
+ )
+ self.assertSequenceEqual(
+ list(search_dict({"one": "test1", "two": "test2"}, "one")),
+ ["test1"]
+ )
+ self.assertSequenceEqual(
+ list(search_dict({"one": {"inner": "test1"}, "two": "test2"}, "inner")),
+ ["test1"]
+ )
+ self.assertSequenceEqual(
+ list(search_dict({"one": [{"inner": "test1"}], "two": "test2"}, "inner")),
+ ["test1"]
+ )
+ self.assertSequenceEqual(
+ list(sorted(search_dict({"one": [{"inner": "test1"}], "two": {"inner": "test2"}}, "inner"))),
+ list(sorted(["test1", "test2"]))
+ )
| Youtube API returns 403 forbidden error (exceeded quota) most of the time when using streamlink on a channel URL
- [x] This is a bug report.
- [x] I have read the contribution guidelines.
### Description
I have been getting 403 forbidden errors returned from the Youtube API when using streamlink on channel URLs (since livestreams often have new URLs, so if you want to monitor whether or not someone is streaming you need to check that) about 90% of the time I try any channel. I don't have any issues on a video link to the stream itself - only a channel link.
I have found several [[1](https://github.com/streamlink/streamlink/issues/667), [2](https://github.com/streamlink/streamlink/issues/1384)] closed issues (I think due to nobody posting debug information and difficulty replicating) with recent posts at the bottom where people are having the same issue.
It doesn't matter if I wait a few minutes between a check, or run a loop to keep running the streamlink command until it successfully asks for me to select a quality, it still fails most of the time for me. I've also tried on a different IP address.
I had my friend who never had streamlink installed (so never used the youtube API, on a residential IP, no VPN) try it just now on 2 random livestreams and he got the 403 forbidden on both URL's and whenever he retried the command, so if there is some kind of rate limiting/quota being hit it appears to be shared and not related to an individual's IP address.
### Expected / Actual behavior
For it to return the stream URL and play it 100% of the time
### Reproduction steps / Explicit stream URLs to test
Any channel URL, preferably one with an active livestream happening. Aside from the one in the log below (the first one I could find on the live trending page), [Ice Poseidon's channel](https://www.youtube.com/channel/UCv9Edl_WbtbPeURPtFDo-uA/). I also tried on a random livestream with ~50 viewers and had the same problem.
### Logs
```
streamlink -l debug https://www.youtube.com/channel/UC2wKfjlioOCLP4xQMOWNcgg 1080p --player mpv
[cli][debug] OS: Linux-4.16.11-300.fc28.x86_64-x86_64-with-fedora-28-Twenty_Eight
[cli][debug] Python: 2.7.15
[cli][debug] Streamlink: 0.12.1
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/channel/UC2wKfjlioOCLP4xQMOWNcgg
[plugin.youtube][debug] Found channel_id: UC2wKfjlioOCLP4xQMOWNcgg
error: Unable to open URL: https://www.googleapis.com/youtube/v3/search (403 Client Error: Forbidden for url: https://www.googleapis.com/youtube/v3/search?eventType=live&part=id&channelId=UC2wKfjlioOCLP4xQMOWNcgg&type=video&key=AIzaSyBDBi-4roGzWJN4du9TuDMLd_jVTcVkKz4)
```
Also [here is a screenshot](https://i.imgur.com/LXConCK.png) from when my friend tried it
I just tried running the URL streamlink reports in the command line in the browser and it is a more detailed error message - specifically, it mentions the **quota being exceeded**
![quota](https://user-images.githubusercontent.com/39682954/40871105-ba3f9416-6624-11e8-8dce-e71efb60a52e.png)
| This is normal. This means that the number of free requests for resolving a video have exceeded a certain quota.
Thanks for the detailed report @Marty665. Better error messages are required here to explain to the user what’s happening, and would have pinned this down quicker.
We should add an option for users to specify their own YouTube API key. I don’t know if we can do much else, if we change the key the same thing will happen again I think...
there are some solutions
1. Adding more than one API_KEY
2. only using there API as a **fallback**, instead use the html code for the video_id
Multiple keys is a bit of a pain as you need a verified (by sms/call) Google account, iirc, to create an account. I was looking at scraping the channel page HTML too, using the API as a fallback is a good idea :) | 2018-06-04T14:01:06 |
streamlink/streamlink | 1,790 | streamlink__streamlink-1790 | [
"1780"
] | c83c77bfc21a323c164c53a97e391fcaa31d07da | diff --git a/src/streamlink/plugins/vaughnlive.py b/src/streamlink/plugins/vaughnlive.py
--- a/src/streamlink/plugins/vaughnlive.py
+++ b/src/streamlink/plugins/vaughnlive.py
@@ -1,14 +1,9 @@
-import itertools
-import logging
-import random
import re
-import ssl
-
-import websocket
+from streamlink import StreamError
from streamlink.plugin import Plugin
from streamlink.plugin.api import useragents
-from streamlink.stream import RTMPStream
+from streamlink.stream import HTTPStream, StreamIOIterWrapper, StreamIOThreadWrapper
_url_re = re.compile(r"""
http(s)?://(\w+\.)?
@@ -18,92 +13,62 @@
""", re.VERBOSE)
-class VLWebSocket(websocket.WebSocket):
- def __init__(self, **_):
- self.session = _.pop("session")
- self.logger = logging.getLogger("streamlink.plugins.vaughnlive.websocket")
- sslopt = _.pop("sslopt", {})
- sslopt["cert_reqs"] = ssl.CERT_NONE
- super(VLWebSocket, self).__init__(sslopt=sslopt, **_)
+class VaughnStream(HTTPStream):
+ def open(self):
+ method = self.args.get("method", "GET")
+ timeout = self.session.options.get("http-timeout")
+ res = self.session.http.request(method=method,
+ stream=True,
+ exception=StreamError,
+ timeout=timeout,
+ **self.args)
+
+ def fix_stream():
+ """
+ Replace the first 3 bytes of the stream with b'FLV'
+ :return: stream iterator
+ """
+ content_iter = res.iter_content(8192)
+ data = next(content_iter)
+ yield b'FLV' + data[3:]
+ for chunk in content_iter:
+ yield chunk
- def send(self, payload, opcode=websocket.ABNF.OPCODE_TEXT):
- self.logger.debug("Sending message: {0}", payload)
- return super(VLWebSocket, self).send(payload + "\n\x00", opcode)
+ fd = StreamIOIterWrapper(fix_stream())
+ if self.buffered:
+ fd = StreamIOThreadWrapper(self.session, fd, timeout=timeout)
- def recv(self):
- d = super(VLWebSocket, self).recv().replace("\n", "").replace("\x00", "")
- return d.split(" ", 1)
+ return fd
class VaughnLive(Plugin):
- servers = ["wss://sapi-ws-{0}x{1:02}.vaughnlive.tv".format(x, y) for x, y in itertools.product(range(1, 3),
- range(1, 6))]
- origin = "https://vaughnlive.tv"
- rtmp_server_map = {
- "594140c69edad": "192.240.105.171:2935",
- "585c4cab1bef1": "192.240.105.171:2935",
- "5940d648b3929": "192.240.105.171:2935",
- "5941854b39bc4": "192.240.105.171:2935"
- }
- name_remap = {"#vl": "live", "#btv": "btv", "#pt": "pt", "#igb": "instagib", "#vtv": "vtv"}
- domain_map = {"vaughnlive": "#vl", "breakers": "#btv", "instagib": "#igb", "vapers": "#vtv", "pearltime": "#pt"}
+ domain_map = {"vaughnlive": "live", "breakers": "btv", "instagib": "igb", "vapers": "vtv", "pearltime": "pt"}
+ stream_url = "https://mp4.vaughnsoft.net/live"
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
- def api_url(self):
- return random.choice(self.servers)
-
- def parse_ack(self, action, message):
- if action.endswith("3"):
- channel, _, viewers, token, server, choked, is_live, chls, trns, ingest = message.split(";")
- is_live = is_live == "1"
- viewers = int(viewers)
- self.logger.debug("Viewers: {0}, isLive={1}", viewers, is_live)
- domain, channel = channel.split("-", 1)
- return is_live, server, domain, channel, token, ingest
- else:
- self.logger.error("Unhandled action format: {0}", action)
-
- def _get_info(self, stream_name):
- server = self.api_url()
- self.logger.debug("Connecting to API: {0}", server)
- ws = websocket.create_connection(server,
- header=["User-Agent: {0}".format(useragents.CHROME)],
- origin=self.origin,
- class_=VLWebSocket,
- session=self.session)
- ws.send("MVN LOAD3 {0}".format(stream_name))
- action, message = ws.recv()
- return self.parse_ack(action, message)
-
- def _get_rtmp_streams(self, server, domain, channel, token):
- rtmp_server = self.rtmp_server_map.get(server, server)
-
- url = "rtmp://{0}/live?{1}".format(rtmp_server, token)
-
- yield "live", RTMPStream(self.session, params={
- "rtmp": url,
- "pageUrl": self.url,
- "playpath": "{0}_{1}".format(self.name_remap.get(domain, "live"), channel),
- "live": True
- })
-
def _get_streams(self):
+ self.session.http.headers = {
+ "Origin": "https://vaughnlive.tv",
+ "Referer": self.url,
+ "User-Agent": useragents.FIREFOX
+ }
m = _url_re.match(self.url)
if m:
- stream_name = "{0}-{1}".format(self.domain_map[(m.group("domain").lower())],
+ stream_name = "{0}_{1}".format(self.domain_map[(m.group("domain").lower())],
m.group("channel"))
-
- is_live, server, domain, channel, token, ingest = self._get_info(stream_name)
-
- if not is_live:
- self.logger.info("Stream is currently off air")
- else:
- self.logger.info("Stream powered by VaughnSoft - remember to support them.")
- for s in self._get_rtmp_streams(server, domain, channel, token):
- yield s
+ self.logger.info("Stream powered by VaughnSoft - remember to support them.")
+ stream = VaughnStream(self.session,
+ self.stream_url,
+ params=dict(app="live",
+ stream=stream_name,
+ port=2935))
+ stream_url = stream.to_url()
+ res = self.session.http.head(stream_url, raise_for_status=False)
+ print(res.status_code)
+ yield "live", stream
__plugin__ = VaughnLive
| Vaughn Live returns invalid links
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [X] I have read the contribution guidelines.
### Description
...
### Expected / Actual behavior
...
### Reproduction steps / Explicit stream URLs to test
1. streamlink https://vaughnlive.tv/everything80s --stream-url --best >>my.m3u
2. streamlink https://vaughnlive.tv/franky_eyes2 --stream-url --best >>my.m3u
the above result in unplayable streams:
output from file:
rtmp://192.240.105.171:1935/live? live=1 pageUrl=https://vaughnlive.tv/everything80s playpath=live_everything80s
rtmp://192.240.105.171:1935/live? live=1 pageUrl=https://vaughnlive.tv/franky_eyes2 playpath=live_franky_eyes2
### Logs
sorry no log , and no idea where to get it.
### Comments, screenshots, etc.
...
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| Vaughnlive changed the port number for their rtmp servers the other week, I think this was fixed in 0.13.0. Make sure you are using the latest version of streamlink.
I've been having problems with it too, even when using port 2935.
```
[console][error] Try 1/1: Could not open stream <RTMPStream({'pageUrl': 'https://vaughnlive.tv/wiriamu', 'flv': '-', 'live': True, 'playpath': 'live_wiriamu', 'rtmp': 'rtmp://192.240.105.171:2935/live?'}, redirect=False> (Failed to read data from stream: Read timeout)
error: Could not open stream <RTMPStream({'pageUrl': 'https://vaughnlive.tv/wiriamu', 'flv': '-', 'live': True, 'playpath': 'live_wiriamu', 'rtmp': 'rtmp://192.240.105.171:2935/live?'}, redirect=False>, tried 1 times, exiting
[console][info] Closing currently open stream...
```
| 2018-06-13T07:39:29 |
|
streamlink/streamlink | 1,791 | streamlink__streamlink-1791 | [
"1788"
] | 9d63e64bbcbdaac647cd5059704c287819069d4a | diff --git a/src/streamlink/plugins/itvplayer.py b/src/streamlink/plugins/itvplayer.py
--- a/src/streamlink/plugins/itvplayer.py
+++ b/src/streamlink/plugins/itvplayer.py
@@ -1,213 +1,83 @@
+import json
+import logging
import re
-from uuid import uuid4
-
-try:
- import xml.etree.cElementTree as ET
-except ImportError:
- import xml.etree.ElementTree as ET
+from streamlink.compat import urljoin
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.stream import RTMPStream, HDSStream
-from streamlink.compat import urlparse, unquote
+from streamlink.plugin.api import http, useragents, validate
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
-ITV_PLAYER_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36'
-LIVE_SWF_URL = "http://www.itv.com/mediaplayer/ITVMediaPlayer.swf"
-ONDEMAND_SWF_URL = "http://www.itv.com/mercury/Mercury_VideoPlayer.swf"
-CHANNEL_MAP = {'itv': 1, 'itv2': 2, 'itv3': 3, 'itv4': 4, 'itvbe': 8, 'citv': 7}
-_url_re = re.compile(r"http(?:s)?://(?:www.)?itv.com/hub/(?P<stream>.+)")
+log = logging.getLogger(__name__)
class ITVPlayer(Plugin):
- def __init__(self, url):
- Plugin.__init__(self, url)
- match = _url_re.match(url)
- self._stream = match and match.groupdict()["stream"]
+ _url_re = re.compile(r"https?://(?:www.)?itv.com/hub/(?P<stream>.+)")
+ _video_info_schema = validate.Schema({
+ "StatusCode": 200,
+ "AdditionalInfo": {
+ "Message": validate.any(None, validate.text)
+ },
+ "Playlist": {
+ "VideoType": validate.text,
+ "Video": {
+ "Subtitles": validate.any(None, [{
+ "Href": validate.url(),
+ }]),
+ "Base": validate.url(),
+ "MediaFiles": [
+ {"Href": validate.text,
+ "KeyServiceUrl": validate.any(None, validate.url())}
+ ]
+ }
+ }
+ })
@classmethod
- def can_handle_url(self, url):
- match = _url_re.match(url)
- return match
-
- @property
- def channel_id(self):
- if self._stream in CHANNEL_MAP:
- return CHANNEL_MAP[self._stream]
+ def can_handle_url(cls, url):
+ match = cls._url_re.match(url)
+ return match is not None
@property
- def production_id(self):
- if self._stream not in CHANNEL_MAP:
- res = http.get(self.url, verify=False)
- production_id_match = re.findall(r'data-video-production-id="(.+?)"', res.text)
- if production_id_match:
- return unquote(production_id_match[0])
- else:
- self.logger.error(u"No production ID found, has the page layout changed?")
+ def device_info(self):
+ return {"user": {},
+ "device": {"manufacturer": "Chrome", "model": "66",
+ "os": {"name": "Windows", "version": "10", "type": "desktop"}},
+ "client": {"version": "4.1", "id": "browser"},
+ "variantAvailability": {"featureset": {"min": ["hls", "aes"],
+ "max": ["hls", "aes"]},
+ "platformTag": "dotcom"}}
+
+ def video_info(self):
+ page = http.get(self.url)
+ for div in itertags(page.text, 'div'):
+ if div.attributes.get("id") == "video":
+ return div.attributes
def _get_streams(self):
"""
Find all the streams for the ITV url
:return: Mapping of quality to stream
"""
- soap_message = self._soap_request()
-
- headers = {'Content-Length': '{0:d}'.format(len(soap_message)),
- 'Content-Type': 'text/xml; charset=utf-8',
- 'Host': 'secure-mercury.itv.com',
- 'Origin': 'http://www.itv.com',
- 'Referer': 'http://www.itv.com/Mercury/Mercury_VideoPlayer.swf?v=null',
- 'SOAPAction': "http://tempuri.org/PlaylistService/GetPlaylist",
- 'User-Agent': ITV_PLAYER_USER_AGENT,
- "X-Requested-With": "ShockwaveFlash/16.0.0.305"}
-
- res = http.post("https://secure-mercury.itv.com/PlaylistService.svc?wsdl",
- headers=headers,
- data=soap_message)
-
- # Parse XML
- xmldoc = http.xml(res)
-
- # Check that geo region has been accepted
- faultcode = xmldoc.find('.//faultcode')
- if faultcode is not None:
- if 'InvalidGeoRegion' in faultcode.text:
- self.logger.error('Failed to retrieve playlist data '
- '(invalid geo region)')
- return None
-
- # Look for <MediaFiles> tag (RTMP streams)
- mediafiles = xmldoc.find('.//VideoEntries//MediaFiles')
-
- # Look for <ManifestFile> tag (HDS streams)
- manifestfile = xmldoc.find('.//VideoEntries//ManifestFile')
-
- # No streams
- if not mediafiles and not manifestfile:
- return None
-
- streams = {}
-
- # Proxy not needed for media retrieval (Note: probably better to use flag)
- # for x in ('http', 'https'):
- # if x in http.proxies:
- # http.proxies.pop(x);
-
- # Parse RTMP streams
- if mediafiles:
- rtmp = mediafiles.attrib['base']
-
- for mediafile in mediafiles.findall("MediaFile"):
- playpath = mediafile.find("URL").text
-
- rtmp_url = urlparse(rtmp)
- app = (rtmp_url.path[1:] + '?' + rtmp_url.query).rstrip('?')
- live = app == "live"
-
- params = dict(rtmp="{u.scheme}://{u.netloc}{u.path}".format(u=rtmp_url),
- app=app.rstrip('?'),
- playpath=playpath,
- swfVfy=LIVE_SWF_URL if live else ONDEMAND_SWF_URL,
- timeout=10)
- if live:
- params['live'] = True
-
- bitrate = int(mediafile.attrib['bitrate']) / 1000
- quality = "{0:d}k".format(int(bitrate))
- streams[quality] = RTMPStream(self.session, params)
-
- # Parse HDS streams
- if manifestfile:
- url = manifestfile.find('URL').text
-
- if urlparse(url).path.endswith('f4m'):
- streams.update(
- HDSStream.parse_manifest(self.session, url, pvswf=LIVE_SWF_URL)
- )
-
- return streams
-
- def _soap_request(self):
-
- def sub_ns(parent, tag, ns):
- return ET.SubElement(parent, "{%s}%s" % (ns, tag))
-
- def sub_common(parent, tag):
- return sub_ns(parent, tag, "http://schemas.itv.com/2009/05/Common")
-
- def sub_soap(parent, tag):
- return sub_ns(parent, tag, "http://schemas.xmlsoap.org/soap/envelope/")
-
- def sub_item(parent, tag):
- return sub_ns(parent, tag, "http://tempuri.org/")
-
- def sub_itv(parent, tag):
- return sub_ns(parent, tag, "http://schemas.datacontract.org/2004/07/Itv.BB.Mercury.Common.Types")
-
- production_id = self.production_id
- channel_id = self.channel_id
-
- ET.register_namespace("com", "http://schemas.itv.com/2009/05/Common")
- ET.register_namespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/")
- ET.register_namespace("tem", "http://tempuri.org/")
- ET.register_namespace("itv", "http://schemas.datacontract.org/2004/07/Itv.BB.Mercury.Common.Types")
-
- # Start of XML
- root = ET.Element("{http://schemas.xmlsoap.org/soap/envelope/}Envelope")
-
- sub_soap(root, "Header")
- body = sub_soap(root, "Body")
-
- # build request
- get_playlist = sub_item(body, "GetPlaylist")
- request = sub_item(get_playlist, "request")
- prode = sub_itv(request, "ProductionId")
-
- if production_id:
- # request -> ProductionId
- prode.text = production_id
-
- # request -> RequestGuid
- sub_itv(request, "RequestGuid").text = str(uuid4()).upper()
-
- vodcrid = sub_itv(request, "Vodcrid")
- # request -> Vodcrid -> Id
- vod_id = sub_common(vodcrid, "Id")
- # request -> Vodcrid -> Partition
- sub_common(vodcrid, "Partition").text = "itv.com"
-
- if channel_id:
- vod_id.text = "sim{0}".format(channel_id)
+ http.headers.update({"User-Agent": useragents.FIREFOX})
+ video_info = self.video_info()
+ video_info_url = video_info.get("data-html5-playlist") or video_info.get("data-video-id")
- # build userinfo
- userinfo = sub_item(get_playlist, "userInfo")
- sub_itv(userinfo, "Broadcaster").text = "Itv"
- sub_itv(userinfo, "RevenueScienceValue").text = "ITVPLAYER.2.18.14.+build.a778cd30ac"
- sub_itv(userinfo, "SessionId")
- sub_itv(userinfo, "SsoToken")
- sub_itv(userinfo, "UserToken")
- # GeoLocationToken -> Token
- # sub_itv(sub_itv(userinfo, "GeoLocationToken"), "Token")
+ res = http.post(video_info_url,
+ data=json.dumps(self.device_info),
+ headers={"hmac": video_info.get("data-video-hmac")})
+ data = http.json(res, schema=self._video_info_schema)
- # build siteinfo
- siteinfo = sub_item(get_playlist, "siteInfo")
- sub_itv(siteinfo, "AdvertisingRestriction").text = "None"
- sub_itv(siteinfo, "AdvertisingSite").text = "ITV"
- sub_itv(siteinfo, "AdvertisingType").text = "Any"
- sub_itv(siteinfo,
- "Area").text = "ITVPLAYER.VIDEO" # "channels.itv{0}".format(channel_id) if channel_id else "ITVPLAYER.VIDEO"
- sub_itv(siteinfo, "Category")
- sub_itv(siteinfo, "Platform").text = "DotCom"
- sub_itv(siteinfo, "Site").text = "ItvCom"
+ log.debug("Video ID info response: {0}".format(data))
- # build deviceInfo
- deviceinfo = sub_item(get_playlist, "deviceInfo")
- sub_itv(deviceinfo, "ScreenSize").text = "Big"
+ stype = data['Playlist']['VideoType']
- # build playerinfo
- playerinfo = sub_item(get_playlist, "playerInfo")
- sub_itv(playerinfo, "Version").text = "2"
+ for media in data['Playlist']['Video']['MediaFiles']:
+ url = urljoin(data['Playlist']['Video']['Base'], media['Href'])
+ name_fmt = "{pixels}_{bitrate}" if stype == "CATCHUP" else None
+ for s in HLSStream.parse_variant_playlist(self.session, url, name_fmt=name_fmt).items():
+ yield s
- return ET.tostring(root)
__plugin__ = ITVPlayer
| ITV player uses DASH
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Expected / Actual behavior
running streamlink against itv player does not work for new streams as they use DASH encoding. Is there any way to get dash working with itv player?
```console
> streamlink https://www.itv.com/hub/unforgotten/2a3372a0008
[console][info] Found matching plugin itvplayer for URL https://www.itv.com/hub/unforgotten/2a3372a0008
error: No playable streams found on this URL: https://www.itv.com/hub/unforgotten/2a3372a0008
```
### Logs
_Logs are always required for a bug report, use `-l debug` [(help)](https://streamlink.github.io/cli.html#cmdoption-l)
Make sure to **remove username and password**
You can upload your logs to https://gist.github.com/ or_
```
REPLACE THIS TEXT WITH YOUR LOG
```
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| @danpilch the VOD streams that I have seen that are DASH are protected by ClearKey DRM - at this time, DRM (even ClearKey) is not supported. However, it might be worth adding ClearKey support, as this is similar to the basic encryption supported by HLS streams.
Update: HLS streams are actually available. | 2018-06-13T09:51:19 |
|
streamlink/streamlink | 1,805 | streamlink__streamlink-1805 | [
"506"
] | 933126d6a9b15fa2ca019c1b559e5136b9c5c575 | diff --git a/src/streamlink/plugins/yupptv.py b/src/streamlink/plugins/yupptv.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/yupptv.py
@@ -0,0 +1,84 @@
+import logging
+import re
+
+from streamlink import PluginError
+from streamlink.plugin import Plugin, PluginArguments, PluginArgument
+from streamlink.plugin.api import http, useragents
+from streamlink.stream import HLSStream
+
+
+
+log = logging.getLogger(__name__)
+
+
+class YuppTV(Plugin):
+ _url_re = re.compile(r"""https?://(?:www\.)?yupptv\.com""", re.VERBOSE)
+ _m3u8_re = re.compile(r'''['"](http.+\.m3u8.*?)['"]''')
+ _login_url = "https://www.yupptv.com/auth/validateSignin"
+ _box_logout = "https://www.yupptv.com/auth/confirmLogout"
+ _signin_url = "https://www.yupptv.com/signin/"
+ _account_url = "https://www.yupptv.com/account/myaccount.aspx"
+
+ arguments = PluginArguments(
+ PluginArgument(
+ "email",
+ requires=["password"],
+ metavar="EMAIL",
+ help="Your YuppTV account email"
+ ),
+ PluginArgument(
+ "password",
+ sensitive=True,
+ metavar="PASSWORD",
+ help="Your YuppTV account password."
+ )
+ )
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def login(self, username, password, depth=3):
+ if depth == 0:
+ log.error("Failed to login to YuppTV")
+ raise PluginError("cannot login")
+
+ res = http.post(self._login_url, data=dict(user=username, password=password, isMobile=0), headers={"Referer": self._signin_url})
+ data = http.json(res)
+ resp = data['Response']
+ if resp["tempBoxid"]:
+ # log out on other device
+ log.info("Logging out on other device: {0}".format(resp["tempBoxid"]))
+ _ = http.get(self._box_logout, params=dict(boxId=resp["tempBoxid"]))
+ return self.login(username, password, depth-1)
+ return resp['errorCode'], resp['statusmsg']
+
+ def _get_streams(self):
+ http.headers.update({"User-Agent": useragents.CHROME})
+
+ if self.get_option("email") and self.get_option("password"):
+ error_code, error_msg = self.login(self.get_option("email"), self.get_option("password"))
+ if error_code is None:
+ log.info("Logged in as {0}".format(self.get_option("email")))
+ else:
+ log.error("Failed to login: {1} (code: {0})".format(error_code, error_msg))
+
+ page = http.get(self.url)
+ match = self._m3u8_re.search(page.text)
+ if match:
+ stream_url = match.group(1)
+ if "preview/" in stream_url:
+ if "btnsignup" in page.text:
+ log.error("This stream requires you to login")
+ else:
+ log.error("This stream requires a subscription")
+ return
+
+ return HLSStream.parse_variant_playlist(self.session, stream_url)
+ elif "btnsignup" in page.text:
+ log.error("This stream requires you to login")
+ elif "btnsubscribe" in page.text:
+ log.error("This stream requires a subscription")
+
+
+__plugin__ = YuppTV
| diff --git a/tests/test_plugin_yupptv.py b/tests/test_plugin_yupptv.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_yupptv.py
@@ -0,0 +1,15 @@
+import unittest
+
+from streamlink.plugins.yupptv import YuppTV
+
+
+class TestPluginZattoo(unittest.TestCase):
+ def test_can_handle_url(self):
+ self.assertTrue(YuppTV.can_handle_url('https://www.yupptv.com/channels/etv-telugu/live'))
+ self.assertTrue(YuppTV.can_handle_url('https://www.yupptv.com/channels/india-today-news/news/25326023/15-jun-2018'))
+
+ def test_can_handle_negative(self):
+ # shouldn't match
+ self.assertFalse(YuppTV.can_handle_url('https://ewe.de'))
+ self.assertFalse(YuppTV.can_handle_url('https://netcologne.de'))
+ self.assertFalse(YuppTV.can_handle_url('https://zattoo.com'))
| Add plugin: yupptv
I am suspecting that cookies/token expires and I am no longer able to play the stream, not even a restart as it returns **`403 Client Error: Forbidden`**
Example of the links I am getting:
`http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/master.m3u8?hdnea=st%3d1485750135%7eexp%3d1485750495%7eacl%3d%2fi%2fams54_russiatoday%40349571%2f*%7edata%3d1814225%7ehmac%3da3a3c4227a1c121aca77c38e9c21252bd881a5a9d5c96d7851ac8f53bb56c2a7&dw=160`
Streaming url:
`http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/master.m3u8`
Token?:
`hdnea=st%3d1485750135%7eexp%3d1485750495%7eacl%3d%2fi%2fams54_russiatoday%40349571%2f*%7edata%3d1814225%7ehmac%3da3a3c4227a1c121aca77c38e9c21252bd881a5a9d5c96d7851ac8f53bb56c2a7&dw=160`
Seems like there is linux epoch time that sets the expiry of the stream. So each time i need to login to the website and request new token.
I also know the following:
SWF: `http://d3hprka3kr08q2.cloudfront.net/staticstorage/jwplayer/jw_7_8_2/jwplayer.loader.swf`
Content of M3U8 file:
```
#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=87000,RESOLUTION=256x144,CODECS="avc1.66.30, mp4a.40.2"
http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/index_64_av-p.m3u8?sd=10&dw=160&rebase=on&hdntl=exp=1485836971~acl=%2fi%2fams54_russiatoday%40349571%2f*~data=hdntl~hmac=a18a639e66837c960067f07eae81b129b3d20804fd69aaec598f138ab9321128
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=226000,RESOLUTION=384x216,CODECS="avc1.66.30, mp4a.40.2"
http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/index_200_av-p.m3u8?sd=10&dw=160&rebase=on&hdntl=exp=1485836971~acl=%2fi%2fams54_russiatoday%40349571%2f*~data=hdntl~hmac=a18a639e66837c960067f07eae81b129b3d20804fd69aaec598f138ab9321128
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=403000,RESOLUTION=480x270,CODECS="avc1.66.30, mp4a.40.2"
http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/index_400_av-p.m3u8?sd=10&dw=160&rebase=on&hdntl=exp=1485836971~acl=%2fi%2fams54_russiatoday%40349571%2f*~data=hdntl~hmac=a18a639e66837c960067f07eae81b129b3d20804fd69aaec598f138ab9321128
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=647000,RESOLUTION=512x288,CODECS="avc1.66.30, mp4a.40.2"
http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/index_800_av-p.m3u8?sd=10&dw=160&rebase=on&hdntl=exp=1485836971~acl=%2fi%2fams54_russiatoday%40349571%2f*~data=hdntl~hmac=a18a639e66837c960067f07eae81b129b3d20804fd69aaec598f138ab9321128
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1233000,RESOLUTION=704x396,CODECS="avc1.66.30, mp4a.40.2"
http://hlsbanglanews-lh.akamaihd.net/i/ams54_russiatoday@349571/index_1100_av-p.m3u8?sd=10&dw=160&rebase=on&hdntl=exp=1485836971~acl=%2fi%2fams54_russiatoday%40349571%2f*~data=hdntl~hmac=a18a639e66837c960067f07eae81b129b3d20804fd69aaec598f138ab9321128
```
Also, few attributes such as "Referer" for the m3u8 stream.
Is it possible to somehow automate via streamlink the token request process? The website does require a log on in order to get the stream link.
| You will almost certainly need a plugin to do this. What is the website?
Normally the Akamai HLS streams set a long token cookie, but there have been some streams where the long token doesn't work for the playlist. Not much you can do expect create a plugin to support the site.
yupptv.com
How would I go about seeking help for the plugin? Not even sure where to look and who to ask...?
Thank you,
You can request one here :-)
Would it need to be as a new ticket?
Just update the title of this one :)
Done :)
Is there plugin for it to download:)
Can some help how to make plugin for it
anyluck with yupptv.com plugin
| 2018-06-15T20:05:14 |
streamlink/streamlink | 1,813 | streamlink__streamlink-1813 | [
"1811"
] | 933126d6a9b15fa2ca019c1b559e5136b9c5c575 | diff --git a/src/streamlink/plugins/lrt.py b/src/streamlink/plugins/lrt.py
new file mode 100644
diff --git a/src/streamlink/plugins/nos.py b/src/streamlink/plugins/nos.py
--- a/src/streamlink/plugins/nos.py
+++ b/src/streamlink/plugins/nos.py
@@ -5,72 +5,49 @@
Live: http://www.nos.nl/livestream/*
Tour: http://nos.nl/tour/live
"""
-
+import logging
import re
-import json
+from streamlink.compat import urljoin
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
-from streamlink.plugin.api.utils import parse_json
-from streamlink.stream import HTTPStream, HLSStream
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
-_url_re = re.compile(r"http(s)?://(\w+\.)?nos.nl/")
-_js_re = re.compile(r'\((.*)\)')
-_data_stream_re = re.compile(r'data-stream="(.*?)"', re.DOTALL | re.IGNORECASE)
-_source_re = re.compile(r"<source(?P<source>[^>]+)>", re.IGNORECASE)
-_source_src_re = re.compile(r"src=\"(?P<src>[^\"]+)\"", re.IGNORECASE)
-_source_type_re = re.compile(r"type=\"(?P<type>[^\"]+)\"", re.IGNORECASE)
+log = logging.getLogger(__name__)
class NOS(Plugin):
+ _url_re = re.compile(r"https?://(?:\w+\.)?nos.nl/")
+
@classmethod
def can_handle_url(cls, url):
- return _url_re.match(url)
+ return cls._url_re.match(url)
def _resolve_stream(self):
res = http.get(self.url)
- match = _data_stream_re.search(res.text)
- if not match:
- return
- data_stream = match.group(1)
-
- resolve_data = {
- 'stream': data_stream
- }
- res = http.post(
- 'http://www-ipv4.nos.nl/livestream/resolve/',
- data=json.dumps(resolve_data)
- )
- data = http.json(res)
-
- res = http.get(data['url'])
- match = _js_re.search(res.text)
- if not match:
- return
-
- stream_url = parse_json(match.group(1))
-
- return HLSStream.parse_variant_playlist(self.session, stream_url)
+ for video in itertags(res.text, 'video'):
+ stream_url = video.attributes.get("data-stream")
+ log.debug("Stream data: {0}".format(stream_url))
+ return HLSStream.parse_variant_playlist(self.session, stream_url)
def _get_source_streams(self):
res = http.get(self.url)
- streams = {}
- sources = _source_re.findall(res.text)
- for source in sources:
- src = _source_src_re.search(source).group("src")
- pixels = _source_type_re.search(source).group("type")
-
- streams[pixels] = HTTPStream(self.session, src)
-
- return streams
+ for atag in itertags(res.text, 'a'):
+ if "video-play__link" in atag.attributes.get("class", ""):
+ href = urljoin(self.url, atag.attributes.get("href"))
+ log.debug("Loading embedded video page")
+ vpage = http.get(href, params=dict(ajax="true", npo_cc_skip_wall="true"))
+ for source in itertags(vpage.text, 'source'):
+ return HLSStream.parse_variant_playlist(self.session, source.attributes.get("src"))
def _get_streams(self):
- urlparts = self.url.split('/')
-
- if urlparts[-2] == 'livestream' or urlparts[-3] == 'tour':
+ if "/livestream/" in self.url or "/tour/" in self.url:
+ log.debug("Finding live streams")
return self._resolve_stream()
else:
+ log.debug("Finding VOD streams")
return self._get_source_streams()
| Error with nos.nl plugin
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
When I try to open a nos.nl live stream this is the output I get:
```
$ streamlink https://nos.nl/livestream/2236311
[cli][info] Found matching plugin nos for URL https://nos.nl/livestream/2236311
error: Unable to open URL: http://www-ipv4.nos.nl/livestream/resolve/ (404 Client Error: Not Found for url: http://www-ipv4.nos.nl/livestream/resolve/)
```
### Expected / Actual behavior
I have a Netherlands IP and I expect to see the stream like in the web browser.
### Reproduction steps / Explicit stream URLs to test
1. streamlink https://nos.nl/livestream/2236311
2. streamlink https://nos.nl/livestream/npo-politiek.html
### Logs
```
[cli][debug] OS: Linux-4.16.13-2-ARCH-x86_64-with-arch-Arch-Linux
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 0.13.0+35.g933126d6
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin nos for URL https://nos.nl/livestream/2236311
error: Unable to open URL: http://www-ipv4.nos.nl/livestream/resolve/ (404 Client Error: Not Found for url: http://www-ipv4.nos.nl/livestream/resolve/)
```
| 2018-06-17T22:36:19 |
||
streamlink/streamlink | 1,814 | streamlink__streamlink-1814 | [
"1812"
] | 933126d6a9b15fa2ca019c1b559e5136b9c5c575 | diff --git a/src/streamlink/plugins/lrt.py b/src/streamlink/plugins/lrt.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/lrt.py
@@ -0,0 +1,43 @@
+import logging
+import re
+from functools import partial
+
+from streamlink.plugin import Plugin
+from streamlink.plugin.api import http
+from streamlink.stream import HLSStream
+from streamlink.utils import parse_json
+from streamlink.compat import urlparse
+
+log = logging.getLogger(__name__)
+
+
+class LRT(Plugin):
+ _url_re = re.compile(r"https?://(?:www\.)?lrt.lt/mediateka/.")
+ _source_re = re.compile(r'sources\s*:\s*(\[{.*?}\]),', re.DOTALL | re.IGNORECASE)
+ js_to_json = partial(re.compile(r'(?!<")(\w+)\s*:\s*(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2')
+
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url)
+
+ def _get_streams(self):
+ page = http.get(self.url)
+ m = self._source_re.search(page.text)
+ if m:
+ params = ""
+ data = m.group(1)
+ log.debug("Source data: {0}".format(data))
+ if "location.hash.substring" in data:
+ log.debug("Removing hash substring addition")
+ data = re.sub(r"\s*\+\s*location.hash.substring\(\d+\)", "", data)
+ params = urlparse(self.url).fragment
+ data = self.js_to_json(data)
+ for stream in parse_json(data):
+ for s in HLSStream.parse_variant_playlist(self.session, stream['file'], params=params).items():
+ yield s
+ else:
+ log.debug("No match for sources regex")
+
+
+__plugin__ = LRT
| diff --git a/tests/test_plugin_lrt.py b/tests/test_plugin_lrt.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_lrt.py
@@ -0,0 +1,24 @@
+import unittest
+
+from streamlink.plugins.lrt import LRT
+
+
+class TestPluginLRT(unittest.TestCase):
+ def test_can_handle_url(self):
+ should_match = [
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-televizija",
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-kultura",
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica"
+ "https://www.lrt.lt/mediateka/irasas/1013694276/savanoriai-tures-galimybe-pamatyti-popieziu-is-arciau#wowzaplaystart=1511000&wowzaplayduration=168000"
+ ]
+ for url in should_match:
+ self.assertTrue(LRT.can_handle_url(url))
+
+ def test_can_handle_url_negative(self):
+ should_not_match = [
+ "https://www.lrt.lt",
+ "https://www.youtube.com",
+
+ ]
+ for url in should_not_match:
+ self.assertFalse(LRT.can_handle_url(url))
| [plugn request] lrt.lt
### Checklist
- [ ] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
Would it be possible to add a plugin for the Lithuanian National Television? Video streams are located [here](https://www.lrt.lt/mediateka/tiesiogiai/lrt-televizija), [here](https://www.lrt.lt/mediateka/tiesiogiai/lrt-kultura) and [here](https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica).
Thanks.
| 2018-06-17T23:19:56 |
|
streamlink/streamlink | 1,817 | streamlink__streamlink-1817 | [
"1815"
] | fe4f7776acf5076f127fe51cd49fe1c8d48d76e6 | diff --git a/src/streamlink/plugins/delfi.py b/src/streamlink/plugins/delfi.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/delfi.py
@@ -0,0 +1,68 @@
+"""
+Plugin to support the videos from Delfi.lt
+
+https://en.wikipedia.org/wiki/Delfi_(web_portal)
+"""
+import re
+import logging
+
+import itertools
+
+from streamlink.plugin import Plugin
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HTTPStream, HLSStream, DASHStream
+from streamlink.utils import update_scheme
+
+log = logging.getLogger(__name__)
+
+
+class Delfi(Plugin):
+ url_re = re.compile(r"https?://(?:[\w-]+\.)?delfi\.(lt|lv|ee)")
+ _api = {
+ "lt": "http://g2.dcdn.lt/vfe/data.php",
+ "lv": "http://g.delphi.lv/vfe/data.php",
+ "ee": "http://g4.nh.ee/vfe/data.php"
+ }
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls.url_re.match(url) is not None
+
+ @property
+ def api_server(self):
+ m = self.url_re.match(self.url)
+ domain = m and m.group(1)
+ return self._api.get(domain, "lt") # fallback to lt
+
+ def _get_streams_api(self, video_id):
+ res = self.session.http.get(self.api_server,
+ params=dict(video_id=video_id))
+ data = self.session.http.json(res)
+ if data["success"]:
+ for x in itertools.chain(*data['data']['versions'].values()):
+ src = update_scheme(self.url, x['src'])
+ if x['type'] == "application/x-mpegurl":
+ for s in HLSStream.parse_variant_playlist(self.session, src).items():
+ yield s
+ elif x['type'] == "application/dash+xml":
+ for s in DASHStream.parse_manifest(self.session, src).items():
+ yield s
+ elif x['type'] == "video/mp4":
+ yield "{0}p".format(x['res']), HTTPStream(self.session, src)
+ else:
+ log.error("Failed to get streams: {0} ({1})".format(
+ data['message'], data['code']
+ ))
+
+
+ def _get_streams(self):
+ res = self.session.http.get(self.url)
+ for div in itertags(res.text, 'div'):
+ if div.attributes.get("data-provider") == "dvideo":
+ video_id = div.attributes.get("data-id")
+ log.debug("Found video ID: {0}".format(video_id))
+ for s in self._get_streams_api(video_id):
+ yield s
+
+
+__plugin__ = Delfi
| diff --git a/tests/test_plugin_delfi.py b/tests/test_plugin_delfi.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_delfi.py
@@ -0,0 +1,22 @@
+import unittest
+
+from streamlink import Streamlink
+from streamlink.plugins.delfi import Delfi
+
+
+class TestPluginDelfi(unittest.TestCase):
+ def setUp(self):
+ self.session = Streamlink()
+
+ def test_can_handle_url(self):
+ # should match
+ self.assertTrue(Delfi.can_handle_url("http://www.delfi.lt/video/sportas/kroatiska-tvarka-kaliningrade-laisvai-liejosi-gerimai-dainos-sokiai-ir-ziezirbos.d?id=78322857"))
+ self.assertTrue(Delfi.can_handle_url("https://www.delfi.lt/video/sportas/zalgiris-atsidure-per-pergale-nuo-lkl-aukso.d?id=78321125"))
+ self.assertTrue(Delfi.can_handle_url("https://www.delfi.lt/video/laidos/nba/warriors-cempioniskomis-tapusios-ketvirtos-finalo-rungtynes.d?id=78246059"))
+ self.assertTrue(Delfi.can_handle_url("http://rahvahaal.delfi.ee/news/videod/video-joviaalne-piduline-kaotab-raekoja-platsil-ilutulestiku-ule-kontrolli-ja-raketid-lendavad-rahva-sekka?id=82681069"))
+ self.assertTrue(Delfi.can_handle_url("http://www.delfi.lv/delfi-tv-ar-jani-domburu/pilnie-raidijumi/delfi-tv-ar-jani-domburu-atbild-veselibas-ministre-anda-caksa-pilna-intervija?id=49515013"))
+
+ def test_can_handle_url_negative(self):
+ # shouldn't match
+ self.assertFalse(Delfi.can_handle_url("http://www.tvcatchup.com/"))
+ self.assertFalse(Delfi.can_handle_url("http://www.youtube.com/"))
| [plugin request] delfi.lt
### Checklist
- [ ] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
[And just one more, please... :)]
Would it be possible to add a plugin for the [Delfi](https://en.wikipedia.org/wiki/Delfi_(web_portal)) web portal? Video streams' examples can be found [here](http://www.delfi.lt/video/sportas/kroatiska-tvarka-kaliningrade-laisvai-liejosi-gerimai-dainos-sokiai-ir-ziezirbos.d?id=78322857), [here](https://www.delfi.lt/video/sportas/zalgiris-atsidure-per-pergale-nuo-lkl-aukso.d?id=78321125), and [here](https://www.delfi.lt/video/laidos/nba/warriors-cempioniskomis-tapusios-ketvirtos-finalo-rungtynes.d?id=78246059).
Thank you in advance :).
| 2018-06-18T10:03:53 |
|
streamlink/streamlink | 1,820 | streamlink__streamlink-1820 | [
"1808"
] | fe4f7776acf5076f127fe51cd49fe1c8d48d76e6 | diff --git a/src/streamlink/cache.py b/src/streamlink/cache.py
--- a/src/streamlink/cache.py
+++ b/src/streamlink/cache.py
@@ -2,8 +2,8 @@
import os
import shutil
import tempfile
+from time import time, mktime
-from time import time
from .compat import is_win32
if is_win32:
@@ -62,7 +62,7 @@ def _save(self):
except (IOError, OSError):
os.remove(tempname)
- def set(self, key, value, expires=60 * 60 * 24 * 7):
+ def set(self, key, value, expires=60 * 60 * 24 * 7, expires_at=None):
self._load()
self._prune()
@@ -71,6 +71,9 @@ def set(self, key, value, expires=60 * 60 * 24 * 7):
expires += time()
+ if expires_at:
+ expires = mktime(expires_at.timetuple())
+
self._cache[key] = dict(value=value, expires=expires)
self._save()
diff --git a/src/streamlink/plugins/crunchyroll.py b/src/streamlink/plugins/crunchyroll.py
--- a/src/streamlink/plugins/crunchyroll.py
+++ b/src/streamlink/plugins/crunchyroll.py
@@ -3,23 +3,16 @@
import random
import re
import string
+import logging
+from uuid import uuid4
from streamlink.plugin import Plugin, PluginError, PluginArguments, PluginArgument
-from streamlink.plugin.api import http, validate
+from streamlink.plugin.api import http, validate, useragents
from streamlink.stream import HLSStream
-API_URL = "https://api.crunchyroll.com/{0}.0.json"
-API_DEFAULT_LOCALE = "en_US"
-API_USER_AGENT = "Mozilla/5.0 (iPhone; iPhone OS 8.3.0; {0})"
-API_HEADERS = {
- "Host": "api.crunchyroll.com",
- "Accept-Encoding": "gzip, deflate",
- "Accept": "*/*",
- "Content-Type": "application/x-www-form-urlencoded"
-}
-API_VERSION = "2313.8"
-API_ACCESS_TOKEN = "QWjz212GspMHH9h"
-API_DEVICE_TYPE = "com.crunchyroll.iphone"
+log = logging.getLogger(__name__)
+
+
STREAM_WEIGHTS = {
"low": 240,
"mid": 420,
@@ -106,40 +99,70 @@ def __init__(self, msg, code):
class CrunchyrollAPI(object):
- def __init__(self, session_id=None, auth=None, locale=API_DEFAULT_LOCALE):
+ _api_url = "https://api.crunchyroll.com/{0}.0.json"
+ _default_locale = "en_US"
+ _user_agent = "Dalvik/1.6.0 (Linux; U; Android 4.4.2; Android SDK built for x86 Build/KK)"
+ _version_code = 444
+ _version_name = "2.1.10"
+ _access_token = "Scwg9PRRZ19iVwD"
+ _access_type = "com.crunchyroll.crunchyroid"
+
+ def __init__(self, cache, session_id=None, locale=_default_locale):
"""Abstract the API to access to Crunchyroll data.
Can take saved credentials to use on it's calls to the API.
"""
+ self.cache = cache
self.session_id = session_id
- self.auth = auth
+ if self.session_id: # if the session ID is setup don't use the cached auth token
+ self.auth = None
+ else:
+ self.auth = cache.get("auth")
+ self.device_id = cache.get("device_id") or self.generate_device_id()
self.locale = locale
+ self.headers = {
+ "X-Android-Device-Is-GoogleTV": "0",
+ "X-Android-Device-Product": "google_sdk_x86",
+ "X-Android-Device-Model": "Android SDK built for x86",
+ "Using-Brightcove-Player": "1",
+ "X-Android-Release": "4.4.2",
+ "X-Android-SDK": "19",
+ "X-Android-Application-Version-Name": self._version_name,
+ "X-Android-Application-Version-Code": str(self._version_code),
+ 'User-Agent': self._user_agent
+ }
- def _api_call(self, entrypoint, params, schema=None):
+ def _api_call(self, entrypoint, params=None, schema=None):
"""Makes a call against the api.
:param entrypoint: API method to call.
:param params: parameters to include in the request data.
:param schema: schema to use to validate the data
"""
- url = API_URL.format(entrypoint)
+ url = self._api_url.format(entrypoint)
# Default params
- params = dict(params)
+ params = params or {}
+ if self.session_id:
+ params.update({
+ "session_id": self.session_id
+ })
+ else:
+ params.update({
+ "device_id": self.device_id,
+ "device_type": self._access_type,
+ "access_token": self._access_token,
+ "version": self._version_code
+ })
params.update({
- "version": API_VERSION,
"locale": self.locale.replace('_', ''),
})
if self.session_id:
params["session_id"] = self.session_id
- # Headers
- headers = dict(API_HEADERS)
- headers['User-Agent'] = API_USER_AGENT.format(self.locale)
-
# The certificate used by Crunchyroll cannot be verified in some environments.
- res = http.get(url, params=params, headers=headers, verify=False)
+ res = http.post(url, data=params, headers=self.headers, verify=False)
json_res = http.json(res, schema=_api_schema)
if json_res["error"]:
@@ -153,47 +176,66 @@ def _api_call(self, entrypoint, params, schema=None):
return data
- def start_session(self, device_id, **kwargs):
- """Starts a session against Crunchyroll's server.
+ def generate_device_id(self):
+ device_id = str(uuid4())
+ # cache the device id
+ self.cache.set("device_id", 365 * 24 * 60 * 60)
+ log.debug("Device ID: {0}".format(device_id))
+ return device_id
+
- Is recommended that you call this method before making any other calls
- to make sure you have a valid session against the server.
+ def start_session(self):
"""
- if self.session_id:
- http.cookies["sess_id"] = self.session_id
- res = http.get("https://www.crunchyroll.com",
- headers={"User-Agent": API_USER_AGENT.format(self.locale)})
- return res.cookies.get("sess_id", self.session_id)
-
- def login(self, username, password, **kwargs):
- """Authenticates the session to be able to access restricted data from
- the server (e.g. premium restricted videos).
+ Starts a session against Crunchyroll's server.
+ Is recommended that you call this method before making any other calls
+ to make sure you have a valid session against the server.
+ """
+ params = {}
+ if self.auth:
+ params["auth"] = self.auth
+ self.session_id = self._api_call("start_session", params, schema=_session_schema)
+ log.debug("Session created with ID: {0}".format(self.session_id))
+ return self.session_id
+
+ def login(self, username, password):
+ """
+ Authenticates the session to be able to access restricted data from
+ the server (e.g. premium restricted videos).
"""
params = {
"account": username,
"password": password
}
- return self._api_call("login", params, **kwargs)
+ login = self._api_call("login", params, schema=_login_schema)
+ self.auth = login["auth"]
+ self.cache.set("auth", login["auth"], expires_at=login["expires"])
+ return login
- def get_info(self, media_id, fields=None, **kwargs):
- """Returns the data for a certain media item.
+ def authenticate(self):
+ data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema)
+ self.auth = data["auth"]
+ self.cache.set("auth", data["auth"], expires_at=data["expires"])
+ return data
- :param media_id: id that identifies the media item to be accessed.
- :param fields: list of the media"s field to be returned. By default the
- API returns some fields, but others are not returned unless they are
- explicity asked for. I have no real documentation on the fields, but
- they all seem to start with the "media." prefix (e.g. media.name,
- media.stream_data).
+ def get_info(self, media_id, fields=None, schema=None):
"""
- params = {
- "media_id": media_id
- }
+ Returns the data for a certain media item.
+
+ :param media_id: id that identifies the media item to be accessed.
+ :param fields: list of the media"s field to be returned. By default the
+ API returns some fields, but others are not returned unless they are
+ explicity asked for. I have no real documentation on the fields, but
+ they all seem to start with the "media." prefix (e.g. media.name,
+ media.stream_data).
+ :param schema: validation schema to use
+ """
+ params = {"media_id": media_id}
if fields:
params["fields"] = ",".join(fields)
- return self._api_call("info", params, **kwargs)
+ return self._api_call("info", params, schema=schema)
class Crunchyroll(Plugin):
@@ -265,8 +307,8 @@ def _get_streams(self):
media_id = int(match.group("media_id"))
try:
- info = api.get_info(media_id, fields=["media.stream_data"],
- schema=_media_schema)
+ # the media.stream_data field is required, no stream data is returned otherwise
+ info = api.get_info(media_id, fields=["media.stream_data"], schema=_media_schema)
except CrunchyrollAPIError as err:
raise PluginError(u"Media lookup error: {0}".format(err.msg))
@@ -300,18 +342,6 @@ def _get_streams(self):
return streams
- def _get_device_id(self):
- """Returns the saved device id or creates a new one and saves it."""
- device_id = self.cache.get("device_id")
-
- if not device_id:
- # Create a random device id and cache it for a year
- char_set = string.ascii_letters + string.digits
- device_id = "".join(random.sample(char_set, 32))
- self.cache.set("device_id", device_id, 365 * 24 * 60 * 60)
-
- return device_id
-
def _create_api(self):
"""Creates a new CrunchyrollAPI object, initiates it's session and
tries to authenticate it either by using saved credentials or the
@@ -322,50 +352,35 @@ def _create_api(self):
self.cache.set("auth", None, 0)
self.cache.set("session_id", None, 0)
- current_time = datetime.datetime.utcnow()
- device_id = self._get_device_id()
# use the crunchyroll locale as an override, for backwards compatibility
locale = self.get_option("locale") or self.session.localization.language_code
- api = CrunchyrollAPI(
- self.options.get("session_id") or self.cache.get("session_id"), self.cache.get("auth"), locale
- )
-
- self.logger.debug("Creating session with locale: {0}", locale)
- api.session_id = api.start_session(device_id, schema=_session_schema)
-
- # Save session and hope it lasts for a few hours
- self.cache.set("session_id", api.session_id, 4 * 60 * 60)
- self.logger.debug("Session created")
-
- if api.auth:
- self.logger.debug("Using saved credentials")
- elif self.options.get("username"):
- try:
- self.logger.debug("Attempting to login using username and password")
- login = api.login(
- self.options.get("username"),
- self.options.get("password"),
- schema=_login_schema
- )
- api.auth = login["auth"]
+ api = CrunchyrollAPI(self.cache, session_id=self.get_option("session_id"), locale=locale)
- user_session_id = api.start_session(device_id, schema=_session_schema)
- if user_session_id != api.session_id:
- self.logger.warning("Session ID does not match account, resetting session ID")
- api.session_id = user_session_id
+ if not self.get_option("session_id"):
+ self.logger.debug("Creating session with locale: {0}", locale)
+ api.start_session()
+ if api.auth:
+ self.logger.debug("Using saved credentials")
+ login = api.authenticate()
self.logger.info("Successfully logged in as '{0}'",
login["user"]["username"] or login["user"]["email"])
-
- expires = (login["expires"] - current_time).total_seconds()
- self.cache.set("auth", login["auth"], expires)
- except CrunchyrollAPIError as err:
- raise PluginError(u"Authentication error: {0}".format(err.msg))
- else:
- self.logger.warning(
- "No authentication provided, you won't be able to access "
- "premium restricted content"
- )
+ elif self.options.get("username"):
+ try:
+ self.logger.debug("Attempting to login using username and password")
+ api.login(self.options.get("username"),
+ self.options.get("password"))
+ login = api.authenticate()
+ self.logger.info("Logged in as '{0}'",
+ login["user"]["username"] or login["user"]["email"])
+
+ except CrunchyrollAPIError as err:
+ raise PluginError(u"Authentication error: {0}".format(err.msg))
+ else:
+ self.logger.warning(
+ "No authentication provided, you won't be able to access "
+ "premium restricted content"
+ )
return api
| diff --git a/tests/test_cache.py b/tests/test_cache.py
--- a/tests/test_cache.py
+++ b/tests/test_cache.py
@@ -3,8 +3,11 @@
import tempfile
import os.path
+import datetime
+
import streamlink.cache
from shutil import rmtree
+import time
try:
from unittest.mock import patch
@@ -52,9 +55,21 @@ def test_load_fail(self, exists_mock):
self.assertEqual({}, self.cache._cache)
def test_expired(self):
- self.cache.set("value", 10, expires=-1)
+ self.cache.set("value", 10, expires=-20)
+ self.assertEqual(None, self.cache.get("value"))
+
+ def test_expired_at(self):
+ self.cache.set("value", 10, expires_at=datetime.datetime.now() - datetime.timedelta(seconds=20))
self.assertEqual(None, self.cache.get("value"))
+ def test_not_expired(self):
+ self.cache.set("value", 10, expires=20)
+ self.assertEqual(10, self.cache.get("value"))
+
+ def test_expired_at(self):
+ self.cache.set("value", 10, expires_at=datetime.datetime.now() + datetime.timedelta(seconds=20))
+ self.assertEqual(10, self.cache.get("value"))
+
def test_create_directory(self):
try:
streamlink.cache.cache_dir = os.path.join(tempfile.gettempdir(), "streamlink-test")
| No streams found for newest CR episodes that are only available to premium users
*Thanks for reporting an issue!*
*Please read the contribution guidelines first! (see the link above)*
*Also check the list of known issues before reporting an issue!*
*Feel free to use the following template. Be as detailed as possible.*
*Please see the text preview to avoid unnecessary formatting errors.*
*Don't forget to remove this text before submitting.*
----
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
I'm not sure if its fair to call this a bug as it might be an issue on Crunchyroll's end either purposeful or not. I'm not able to watch the latest episode in a series if it's only available to premium users using Streamlink, even logged in as a premium user as there are no streams available according to Streamlink.
error: No playable streams found on this URL: http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957
I can't find any recent issues that match this behaviour and I used to be able to play the latest episode with Streamlink though the last time I used Streamlink was about a month or so ago for new episodes I've mainly been rewatching older shows.
URL Tested with http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957
Tested watching other URLs which are not exclusive to premium users and they work fine.
...
### Expected / Actual behavior
A stream should be found and playable using Streamlink as there is no CR related issues open at present.
...
### Reproduction steps / Explicit stream URLs to test
1. Grab a URL (E.G http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957) for a new episode which is only available to premium users at present.
2. Use URL with Streamlink as usual.
### Logs
_Logs are always required for a bug report, use `-l debug` [(help)](https://streamlink.github.io/cli.html#cmdoption-l)
Make sure to **remove username and password**
You can upload your logs to https://gist.github.com/ or_
```
[console][debug] OS: Windows 10
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957
[console][debug] Plugin specific arguments:
[console][debug] --crunchyroll-username=howdlej (username)
[console][debug] --crunchyroll-password=******** (password)
[plugin.crunchyroll][debug] Creating session with locale: en_GB
[plugin.crunchyroll][debug] Session created
[plugin.crunchyroll][debug] Using saved credentials
C:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
error: No playable streams found on this URL: http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957
```
### Comments, screenshots, etc.
If this is a known issue and something CR is doing specifically to counter Streamlink then please feel free to delete or mark as closed but I couldn't see anything about this specific issue or any other related CR issues.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| I will take a look. Are you in the correct region? It’s not a geoblocked episode is it?
Nope, not geo-blocked, I'm able to watch it fine through the website. Thanks for the response.
We've had this happen in the past @beardypig: https://github.com/streamlink/streamlink/issues/1014. @Orsidus Can you try this: `streamlink --crunchyroll-purge-credentials --crunchyroll-username=USER --crunchyroll-password=PASSWORD http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957 best` but with your user and password.
Excluding the initial line for password reasons.
```
[console][info] Found matching plugin crunchyroll for URL http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957
C:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
[plugin.crunchyroll][warning] Session ID does not match account, resetting session ID
[plugin.crunchyroll][info] Successfully logged in as 'howdlej'
C:\Program Files (x86)\Streamlink\pkgs\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
error: No playable streams found on this URL: http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957
```
@Orsidus Hmm, you know I just realized that you're using en_GB for your session. If you feel comfortable with it could you send me your current creds so I can try from a en_US locale? If you feel comfortable with it I'll be on gitter (https://gitter.im/streamlink/streamlink) for a bit and you can just log in there with your Github account and send me a private message or you can email me. I seem to remember this happening before and it was time sensitive (started working after a day or two for some weird reason).
@gravyboat Don't take this personally, but unfortunately I don't feel comfortable doing that. However, my suspicion of it being directly linked to the fact the episode is currently not available to free users yet and only to premium users seems to be close to the truth. The issue you referred to earlier, the person claimed it said it was working over 2 weeks later than when he made his post.
Episodes on CR switch from being premium to free after 1 week. I've tried a number of currently premium-only episodes on CR and not a single one is playing. I will check Food Wars Episode 22 tomorrow after the new episode comes to see if it plays and that should confirm that its linked directly to that.
However this is something that I've only noticed happening recently (maybe it's been happening for no more than 2 months or so) but I did notice there was news on their website about changes to their backend recently so prehaps they've done something to counter however streamlink obtains the video streams for non-free episodes.
URLs Tested:
http://www.crunchyroll.com/darling-in-the-franxx/episode-21-for-you-my-love-769615
http://www.crunchyroll.com/boruto-naruto-next-generations/episode-62-the-otsutsuki-invasion-765641
http://www.crunchyroll.com/food-wars-shokugeki-no-soma/episode-22-to-the-final-battleground-769065 (This episode specifically is listed as becoming free tomorrow (Jun 17th))
http://www.crunchyroll.com/megalobox/episode-11-a-deadmarch-768819
@Orsidus No worries I totally understand. I'm pretty sure the last time this happened it was from outside the US as well which made me think something weird is going on with how their edge nodes work where the website falls back to other servers when it doesn't find the content, but something about how we make the request doesn't (sounds weird but honestly it's the only thing that I can think would cause this unless they have some weird mitigation in place as you noted). That food wars episode you linked is 6 days old at this point however so you would think it would have propagated.
Do you have the link to the blog post that talks about these recent changes? The last time I remember this happening was at least 4-6 months ago, if not more.
@gravyboat This is the blog post: https://blog.ellation.com/crunchyroll-maintenance-e11c4c065737 Though I had actually had this issue myself once last week before this rolled out so I don't think this has changed anything since once it happened again this week.
If there is any tests or anything you can think of that might give you some more information to work with feel free to let me know and I'll run what I can. I did notice that this new VRV thing they have going on is relatively new to me at least though I cannot access it from outside the U.S it might've caused them to do something to change how their premium streams work perhaps?
you could try to change your locale settings with `--locale en_US`
https://streamlink.github.io/cli.html#cmdoption-locale
but reset your session with `--crunchyroll-purge-credentials`
maybe it changes something.
```
streamlink --crunchyroll-purge-credentials --locale en_US --crunchyroll-username=howdlej --crunchyroll-password=<Ommited> http://www.crunchyroll.com/my-hero-academia/episode-49-one-for-all-768957 best
```
Same result. Unable to find any playable streams.
Seems like a similar issue to #1574. @Orsidus, do you have an Android smart phone? If so, could you test out the Android App and see if those premium streams play?
@beardypig The only error I've ever gotten besides the https warning is "No playable streams found on this URL" I've never had the media look up error refeered to in that issue. To update, the link for Food Wars Episode 22 now works but the rest do not as predicted. I have an android phone and just tested that all episodes linked earlier work on the android app.
Thanks @Orsidus. It believe it is related to the session ID generation - which was the root cause of #1574 :)
@beardypig Fingers crossed! Thanks for the helped so far, let me know if there's anything else you need testing wise. | 2018-06-18T14:50:01 |
streamlink/streamlink | 1,823 | streamlink__streamlink-1823 | [
"1821"
] | fe4f7776acf5076f127fe51cd49fe1c8d48d76e6 | diff --git a/src/streamlink/plugins/vrtbe.py b/src/streamlink/plugins/vrtbe.py
--- a/src/streamlink/plugins/vrtbe.py
+++ b/src/streamlink/plugins/vrtbe.py
@@ -1,85 +1,92 @@
+import logging
import re
+from streamlink.compat import urljoin
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
from streamlink.plugin.api import validate
-from streamlink.stream import HDSStream
-from streamlink.stream import HLSStream
-from streamlink.utils import parse_json
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream, DASHStream
-_url_re = re.compile(r'''https?://www\.vrt\.be/vrtnu/(?:kanalen/(?P<channel>[^/]+)|\S+)''')
-_json_re = re.compile(r'''(\173[^\173\175]+\175)''')
+log = logging.getLogger(__name__)
-API_LIVE = 'https://services.vrt.be/videoplayer/r/live.json'
-API_VOD = 'https://mediazone.vrt.be/api/v1/{0}/assets/{1}'
-_stream_schema = validate.Schema({
- 'targetUrls': [
- {
- 'type': validate.text,
- 'url': validate.text
+class VRTbe(Plugin):
+ _url_re = re.compile(r'''https?://www\.vrt\.be/vrtnu/(?:kanalen/(?P<channel>[^/]+)|\S+)''')
+
+ _stream_schema = validate.Schema(
+ validate.any({
+ "code": validate.text,
+ "message": validate.text
},
- ],
-})
+ {
+ "drm": validate.any(None, validate.text),
+ 'targetUrls': [{
+ 'type': validate.text,
+ 'url': validate.text
+ }],
+ })
+ )
+ _token_schema = validate.Schema({
+ "vrtPlayerToken": validate.text
+ }, validate.get("vrtPlayerToken"))
+
+ api_url = "https://api.vuplay.co.uk/"
-class VRTbe(Plugin):
@classmethod
def can_handle_url(cls, url):
- return _url_re.match(url)
+ return cls._url_re.match(url)
- def _get_live_stream(self, channel):
- channel = 'vualto_{0}'.format(channel)
- _live_json_re = re.compile(r'''"{0}":\s(\173[^\173\175]+\175)'''.format(channel))
+ def _get_api_info(self, page):
+ for div in itertags(page.text, 'div'):
+ if div.attributes.get("class") == "vrtvideo":
+ api_base = div.attributes.get("data-mediaapiurl") + "/"
- res = http.get(API_LIVE)
- match = _live_json_re.search(res.text)
- if not match:
- return
- data = parse_json(match.group(1))
+ data = {"token_url": urljoin(api_base, "tokens")}
+ if div.attributes.get("data-videotype") == "live":
+ data["stream_url"] = urljoin(urljoin(api_base, "videos/"), div.attributes.get("data-livestream"))
+ else:
+ resource = "{0}%24{1}".format(div.attributes.get("data-publicationid"), div.attributes.get("data-videoid"))
+ data["stream_url"] = urljoin(urljoin(api_base, "videos/"), resource)
+ return data
- hls_url = data['hls']
+ def _get_streams(self):
+ page = self.session.http.get(self.url)
+ api_info = self._get_api_info(page)
- if hls_url:
- for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
- yield s
+ if not api_info:
+ log.error("Could not find API info in page")
+ return
- def _get_vod_stream(self):
- vod_url = self.url
- if vod_url.endswith('/'):
- vod_url = vod_url[:-1]
+ token_res = self.session.http.post(api_info["token_url"])
+ token = self.session.http.json(token_res, schema=self._token_schema)
- json_url = '{0}.securevideo.json'.format(vod_url)
+ log.debug("Got token: {0}".format(token))
+ log.debug("Getting stream data: {0}".format(api_info["stream_url"]))
+ res = self.session.http.get(api_info["stream_url"],
+ params={
+ "vrtPlayerToken": token,
+ "client": "vrtvideo"
+ }, raise_for_status=False)
+ data = self.session.http.json(res, schema=self._stream_schema)
- res = http.get(json_url)
- match = _json_re.search(res.text)
- if not match:
+ if "code" in data:
+ log.error("{0} ({1})".format(data['message'], data['code']))
return
- data = parse_json(match.group(1))
- res = http.get(API_VOD.format(data['clientid'], data['mzid']))
- data = http.json(res, schema=_stream_schema)
+ log.debug("Streams have {0}DRM".format("no " if not data["drm"] else ""))
- for d in data['targetUrls']:
- if d['type'] == 'HDS':
- hds_url = d['url']
- for s in HDSStream.parse_manifest(self.session, hds_url).items():
+ for target in data["targetUrls"]:
+ if data["drm"]:
+ if target["type"] == "hls_aes":
+ for s in HLSStream.parse_variant_playlist(self.session, target["url"]).items():
+ yield s
+ elif target["type"] == "hls":
+ for s in HLSStream.parse_variant_playlist(self.session, target["url"]).items():
yield s
-
- if d['type'] == 'HLS':
- hls_url = d['url']
- for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
+ elif target["type"] == "mpeg_dash":
+ for s in DASHStream.parse_manifest(self.session, target["url"]).items():
yield s
- def _get_streams(self):
- match = _url_re.match(self.url)
-
- channel = match.group('channel')
-
- if channel:
- return self._get_live_stream(channel)
- else:
- return self._get_vod_stream()
-
__plugin__ = VRTbe
diff --git a/src/streamlink/stream/dash_manifest.py b/src/streamlink/stream/dash_manifest.py
--- a/src/streamlink/stream/dash_manifest.py
+++ b/src/streamlink/stream/dash_manifest.py
@@ -488,7 +488,7 @@ def format_media(self, **kwargs):
else:
for segment, n in zip(self.segmentTimeline.segments, count(self.startNumber)):
yield (self.make_url(self.media(Time=segment.t, Number=n, **kwargs)),
- datetime.timedelta(seconds=segment.d / self.timescale))
+ datetime.datetime.now(tz=utc))
else:
for number, available_at in self.segment_numbers():
| vrt.nu plugin: doesnt works anymore
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
vrt.nu (Belgian Flemish television) plugin doesnt works anymore
### Expected / Actual behavior
is there a way to fix this issue ?
### Reproduction steps / Explicit stream URLs to test
1. type command in terminal: `streamlink https://www.vrt.be/vrtnu/kanalen/een/ best`
### Logs
https://paste.ubuntu.com/p/PcTCH29Pq7/
### Environment details
- OS : Ubuntu 18.04 bionic 32bits
- Python version : 3.6.5
- Streamlink : 0.13.0
| 2018-06-19T00:11:05 |
||
streamlink/streamlink | 1,844 | streamlink__streamlink-1844 | [
"1843"
] | 7ec020b6cc3802d4e199fc5ed409b56b7314a952 | diff --git a/src/streamlink/plugins/atresplayer.py b/src/streamlink/plugins/atresplayer.py
--- a/src/streamlink/plugins/atresplayer.py
+++ b/src/streamlink/plugins/atresplayer.py
@@ -1,38 +1,56 @@
from __future__ import print_function
+
+import logging
import re
-import time
-import random
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.plugin.api import validate
-from streamlink.stream import HDSStream
+from streamlink.plugin.api import http, validate
+from streamlink.stream import HLSStream
+from streamlink.utils import parse_json, update_scheme
+
+log = logging.getLogger(__name__)
class AtresPlayer(Plugin):
- url_re = re.compile(r"https?://(?:www.)?atresplayer.com/directos/television/(\w+)/?")
- player_re = re.compile(r"""div.*?directo=(\d+)""")
- stream_api = "https://servicios.atresplayer.com/api/urlVideoLanguage/v3/{id}/web/{id}|{time}|{hash}/es.xml"
- manifest_re = re.compile(r"<resultDes>(.*?)</resultDes>")
+ url_re = re.compile(r"https?://(?:www.)?atresplayer.com/directos/([\w-]+)/?")
+ state_re = re.compile(r"""window.__PRELOADED_STATE__\s*=\s*({.*?});""", re.DOTALL)
+ channel_id_schema = validate.Schema(
+ validate.transform(state_re.search),
+ validate.any(
+ None,
+ validate.all(
+ validate.get(1),
+ validate.transform(parse_json),
+ {
+ "programming": {
+ validate.text: validate.all({"urlVideo": validate.text},
+ validate.get("urlVideo"))
+ }
+ },
+ validate.get("programming")
+ )))
+ stream_schema = validate.Schema(
+ validate.transform(parse_json),
+ {"sources": [
+ validate.all({"src": validate.url()},
+ validate.get("src"))
+ ]}, validate.get("sources"))
+
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
+ def __init__(self, url):
+ # must be HTTPS
+ super(AtresPlayer, self).__init__(update_scheme("https://", url))
+
def _get_streams(self):
- res = http.get(self.url)
- match = self.player_re.search(res.text)
- if match:
- channel_id = match.group(1)
-
- stream_api = self.stream_api.format(id=channel_id,
- time=int(time.time()),
- hash=''.join(random.choice("abcdef0123456789") for x in range(28)))
-
- res = http.get(stream_api)
- f4m_url = self.manifest_re.search(res.text)
- if f4m_url:
- return HDSStream.parse_manifest(self.session, f4m_url.group(1))
+ programming = http.get(self.url, schema=self.channel_id_schema)
+ for api_url in programming.values():
+ for src in http.get(api_url, schema=self.stream_schema):
+ for s in HLSStream.parse_variant_playlist(self.session, src).items():
+ yield s
__plugin__ = AtresPlayer
| Atresplayer
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
Links Live:
https://www.atresplayer.com/directos/antena3/
https://www.atresplayer.com/directos/lasexta/
https://www.atresplayer.com/directos/neox/
https://www.atresplayer.com/directos/nova/
https://www.atresplayer.com/directos/mega/
https://www.atresplayer.com/directos/atreseries/
```
streamlink.exe https://www.atresplayer.com/directos/antena3/ best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
error: No plugin can handle URL: https://www.atresplayer.com/directos/antena3/
```
*I have executed the same command with the six links.
Sorry for English, I do not speak it.
| 2018-06-25T21:51:59 |
||
streamlink/streamlink | 1,848 | streamlink__streamlink-1848 | [
"1845"
] | 7ec020b6cc3802d4e199fc5ed409b56b7314a952 | diff --git a/src/streamlink/plugins/mitele.py b/src/streamlink/plugins/mitele.py
--- a/src/streamlink/plugins/mitele.py
+++ b/src/streamlink/plugins/mitele.py
@@ -31,7 +31,7 @@ class Mitele(Plugin):
"telecinco": livehlsdai,
}
- pdata_url = "https://indalo.mediaset.es/mmc-player/api/mmc/v1/{channel}/live/flash.json"
+ pdata_url = "https://indalo.mediaset.es/mmc-player/api/mmc/v1/{channel}/live/html5.json"
gate_url = "https://gatekeeper.mediaset.es"
pdata_schema = validate.Schema(
@@ -39,7 +39,7 @@ class Mitele(Plugin):
{
"locations": [{
"gcp": validate.text,
- "ogn": validate.text,
+ "ogn": validate.any(None, validate.text),
}],
},
validate.get("locations"),
@@ -117,7 +117,7 @@ def _get_streams(self):
if hls_url:
self.logger.debug("HLS URL: {0}".format(hls_url))
- for s in HLSStream.parse_variant_playlist(self.session, hls_url, headers=self.headers).items():
+ for s in HLSStream.parse_variant_playlist(self.session, hls_url, headers=self.headers, name_fmt="{pixels}_{bitrate}").items():
yield s
| Mitele
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
Channel Energy:
https://www.mitele.es/directo/energy
```
streamlink.exe https://www.mitele.es/directo/energy best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin mitele for URL https://www.mitele.es/directo/energy
error: Unable to validate JSON: Unable to validate key 'locations': Unable to validate key 'ogn': Type of None should be 'str' but is 'NoneType'
```
Channel Be Mad:
https://www.mitele.es/directo/bemad
```
streamlink.exe https://www.mitele.es/directo/bemad best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin mitele for URL https://www.mitele.es/directo/bemad
[plugin.mitele][debug] HLS URL: https://mdslivehls-i.akamaihd.net/hls/live/571646/bemad/master.m3u8?hdnea=st=1529962765~exp=1529962773~acl=/hls/live/571646/bemad/*~hmac=479d365ee94787ee2b8589af0481965e7d9db7b64f221e972e9ae700a4dbc511&ogn=o0t6vboys4gf5myd/zPCDTrD4mngkRY2xpxAy2RZpc8YKMY/OXWaKkIdDCyb1JsI6lgjrjbG62fAz0QlSA7PGYLbDOCkr17OPEswGGPi3Hk=
[console][info] Available streams: 360p (worst), 480p, 720p_alt, 720p (best)
[console][info] Opening stream: 720p (hls)
[stream.hls][debug] Reloading playlist
[console][error] Try 1/1: Could not open stream <HLSStream('https://mdslivehls-i.akamaihd.net/hls/live/571646/bemad/bitrate_3.m3u8')> (Could not open stream: Unable to open URL: https://mdslivehls-i.akamaihd.net/hls/live/571646/bemad/bitrate_3.m3u8 (404 Client Error: Not Found for url: https://mdslivehls-i.akamaihd.net/hls/live/571646/bemad/bitrate_3.m3u8))
error: Could not open stream <HLSStream('https://mdslivehls-i.akamaihd.net/hls/live/571646/bemad/bitrate_3.m3u8')>, tried 1 times, exiting
```
Channel Boing:
https://www.mitele.es/directo/boing
```
streamlink.exe https://www.mitele.es/directo/boing best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin mitele for URL https://www.mitele.es/directo/boing
[plugin.mitele][debug] HLS URL: https://mdslivehls-i.akamaihd.net/hls/live/571647/boing/master.m3u8?hdnea=st=1529963719~exp=1529963727~acl=/hls/live/571647/boing/*~hmac=a4496414861bffafc289305413248f581d26478a6a1680dc14b0c0d628ff185a&ogn=o0t6vboys4gf5myd/zPCDTrD4mngkRY2xpxAy2RZpc8YKMY/OXWaKkIdDCyb1JsIKjCZ1AX0ylNLwo7kPa/4h0j6jEXEzzq1zbN69Jz07zU=
[console][info] Available streams: 360p (worst), 480p, 720p_alt, 720p (best)
[console][info] Opening stream: 720p (hls)
[stream.hls][debug] Reloading playlist
[console][error] Try 1/1: Could not open stream <HLSStream('https://mdslivehls-i.akamaihd.net/hls/live/571647/boing/bitrate_3.m3u8')> (Could not open stream: Unable to open URL: https://mdslivehls-i.akamaihd.net/hls/live/571647/boing/bitrate_3.m3u8 (404 Client Error: Not Found for url: https://mdslivehls-i.akamaihd.net/hls/live/571647/boing/bitrate_3.m3u8))
error: Could not open stream <HLSStream('https://mdslivehls-i.akamaihd.net/hls/live/571647/boing/bitrate_3.m3u8')>, tried 1 times, exiting
```
| 2018-06-25T23:20:16 |
||
streamlink/streamlink | 1,851 | streamlink__streamlink-1851 | [
"1850"
] | b7e57851c642b0019313e04df289b6369322e8dd | diff --git a/src/streamlink/plugins/tv3cat.py b/src/streamlink/plugins/tv3cat.py
--- a/src/streamlink/plugins/tv3cat.py
+++ b/src/streamlink/plugins/tv3cat.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+import logging
import re
from streamlink.plugin import Plugin
@@ -6,46 +7,40 @@
from streamlink.stream import HLSStream
from streamlink.plugin.api import validate
-STREAM_INFO_URL = "http://dinamics.ccma.cat/pvideo/media.jsp?media=video&version=0s&idint={ident}&profile=pc&desplacament=0"
-_url_re = re.compile(r"http://(?:www.)?ccma.cat/tv3/directe/(.+?)/")
-_media_schema = validate.Schema({
- "geo": validate.text,
- "url": validate.url(scheme=validate.any("http"))
-})
-_channel_schema = validate.Schema({
- "media": validate.any([_media_schema], _media_schema)
-})
+log = logging.getLogger(__name__)
class TV3Cat(Plugin):
+ _url_re = re.compile(r"http://(?:www.)?ccma.cat/tv3/directe/(.+?)/")
+ _stream_info_url = "http://dinamics.ccma.cat/pvideo/media.jsp?media=video&version=0s&idint={ident}&profile=pc&desplacament=0"
+ _media_schema = validate.Schema({
+ "geo": validate.text,
+ "url": validate.url(scheme=validate.any("http", "https"))
+ })
+ _channel_schema = validate.Schema({
+ "media": validate.any([_media_schema], _media_schema)},
+ validate.get("media"),
+ # If there is only one item, it's not a list ... silly
+ validate.transform(lambda x: x if isinstance(x, list) else [x])
+ )
+
@classmethod
- def can_handle_url(self, url):
- match = _url_re.match(url)
- return match
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
def _get_streams(self):
-
- match = _url_re.match(self.url)
+ match = self._url_re.match(self.url)
if match:
ident = match.group(1)
- data_url = STREAM_INFO_URL.format(ident=ident)
-
- # find the region, default to TOTS (international)
- res = http.get(self.url)
- geo_data = re.search(r'data-geo="([A-Z]+?)"', res.text)
- geo = geo_data and geo_data.group(1) or "TOTS"
-
- stream_data = http.json(http.get(data_url), schema=_channel_schema)
-
- # If there is only one item, it's not a list ... silly
- if isinstance(stream_data['media'], list):
- stream_infos = stream_data['media']
- else:
- stream_infos = [stream_data['media']]
+ data_url = self._stream_info_url.format(ident=ident)
+ stream_infos = http.json(http.get(data_url), schema=self._channel_schema)
for stream in stream_infos:
- if stream['geo'] == geo:
- return HLSStream.parse_variant_playlist(self.session, stream['url'])
+ try:
+ return HLSStream.parse_variant_playlist(self.session, stream['url'], name_fmt="{pixels}_{bitrate}")
+ except:
+ log.debug("Failed to get streams for: {0}".format(stream['geo']))
+ pass
__plugin__ = TV3Cat
| tv3cat
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
Links Live:
http://www.ccma.cat/tv3/directe/tv3/
http://www.ccma.cat/tv3/directe/324/
http://www.ccma.cat/tv3/directe/33/
http://www.ccma.cat/tv3/directe/esport3/
Channels 324 / Esport3 / 33 / TV3:
```
streamlink.exe http://www.ccma.cat/tv3/directe/esport3/ best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin tv3cat for URL http://www.ccma.cat/tv3/directe/esport3/
error: Unable to validate JSON: Unable to validate key 'media': Unable to validate result: Unable to validate key 'url': Unable to validate URL attribute 'scheme': 'https' does not equal 'http' or Unable to validate result: Type of [{'geo':
'CATALUNYA', 'format': 'HLS', 'url': 'https://ccma-tva-cat-cellnex-live-hls.secure.footprint.net/cat/ngrp:es3_web/playlist.m3u8'}, {'geo': 'ESPANYA', 'format':
'HLS', 'url': 'https://ccma-tva-es-cellnex-live-hls.secure.footprint.net/es/ngrp:es3_web/playlist.m3u8'}, {'geo': 'TOTS', 'format': 'HLS', 'url': 'https://ccma-tva-int-cellnex-live-hls.secure.footprint.net/int/ngrp:es3_web/playlist.m3u8'}]
should be 'dict' but is 'list'
streamlink.exe http://www.ccma.cat/tv3/directe/33/ best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin tv3cat for URL http://www.ccma.cat/tv3/directe/33/
error: Unable to validate JSON: Unable to validate key 'media': Unable to validate result: Unable to validate key 'url': Unable to validate URL attribute 'scheme': 'https' does not equal 'http' or Unable to validate result: Type of [{'format': 'HLS', 'url': 'https://ccma-tva-cat-cellnex-live-hls.secure.footprint.net/cat/ngrp:c33_web/playlist.m3u8', 'geo': 'CATALUNYA'}, {'format': 'HLS', 'url': 'https://ccma-tva-es-cellnex-live-hls.secure.footprint.net/es/ngrp:c33_web/playlist.m3u8', 'geo': 'ESPANYA'}, {'format': 'HLS', 'url': 'https://ccma-tva-int-cellnex-live-hls.secure.footprint.net/int/ngrp:c33_web/playlist.m3u8', 'geo': 'TOTS'}]
should be 'dict' but is 'list'
streamlink.exe http://www.ccma.cat/tv3/directe/324/ best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin tv3cat for URL http://www.ccma.cat/tv3/directe/324/
error: Unable to validate JSON: Unable to validate key 'media': Type of {'geo':
'TOTS', 'url': 'https://ccma-tva-int-cellnex-live-hls.secure.footprint.net/int/ngrp:324_web/playlist.m3u8', 'format': 'HLS'} should be 'list' but is 'dict' or Unable to validate result: Unable to validate key 'url': Unable to validate URL attribute 'scheme': 'https' does not equal 'http'
streamlink.exe http://www.ccma.cat/tv3/directe/tv3/ best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin tv3cat for URL http://www.ccma.cat/tv3/directe/tv3/
error: Unable to validate JSON: Unable to validate key 'media': Unable to validate result: Unable to validate key 'url': Unable to validate URL attribute 'scheme': 'https' does not equal 'http' or Unable to validate result: Type of [{'geo':
'CATALUNYA', 'url': 'https://ccma-tva-cat-cellnex-live-hls.secure.footprint.net/cat/ngrp:tv3_web/playlist.m3u8', 'format': 'HLS'}, {'geo': 'ESPANYA', 'url': 'https://ccma-tva-es-cellnex-live-hls.secure.footprint.net/es/ngrp:tv3_web/playlist.m3u8', 'format': 'HLS'}, {'geo': 'TOTS', 'url': 'https://ccma-tva-int-cellnex-live-hls.secure.footprint.net/int/ngrp:tv3_web/playlist.m3u8', 'format': 'HLS'}]
should be 'dict' but is 'list'
```
| 2018-06-26T08:05:54 |
||
streamlink/streamlink | 1,852 | streamlink__streamlink-1852 | [
"1849"
] | b7e57851c642b0019313e04df289b6369322e8dd | diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py
--- a/src/streamlink/stream/dash.py
+++ b/src/streamlink/stream/dash.py
@@ -28,6 +28,7 @@ def fetch(self, segment, retries=None):
return
try:
+ headers = {}
now = datetime.datetime.now(tz=utc)
if segment.available_at > now:
time_to_wait = (segment.available_at - now).total_seconds()
@@ -35,9 +36,18 @@ def fetch(self, segment, retries=None):
log.debug("Waiting for segment: {fname} ({wait:.01f}s)".format(fname=fname, wait=time_to_wait))
sleep_until(segment.available_at)
+ if segment.range:
+ start, length = segment.range
+ if length:
+ end = start + length - 1
+ else:
+ end = ""
+ headers["Range"] = "bytes={0}-{1}".format(start, end)
+
return self.session.http.get(segment.url,
timeout=self.timeout,
- exception=StreamError)
+ exception=StreamError,
+ headers=headers)
except StreamError as err:
log.error("Failed to open segment {0}: {1}", segment.url, err)
return self.fetch(segment, retries - 1)
diff --git a/src/streamlink/stream/dash_manifest.py b/src/streamlink/stream/dash_manifest.py
--- a/src/streamlink/stream/dash_manifest.py
+++ b/src/streamlink/stream/dash_manifest.py
@@ -32,12 +32,13 @@ def dst(self, dt):
class Segment(object):
- def __init__(self, url, duration, init=False, content=True, available_at=epoch_start):
+ def __init__(self, url, duration, init=False, content=True, available_at=epoch_start, range=None):
self.url = url
self.duration = duration
self.init = init
self.content = content
self.available_at = available_at
+ self.range = range
def datetime_to_seconds(dt):
@@ -119,6 +120,15 @@ def _timedelta(seconds):
return _timedelta
+ @staticmethod
+ def range(range_spec):
+ r = range_spec.split("-")
+ if len(r) != 2:
+ raise MPDParsingError("invalid byte-range-spec")
+
+ start, end = int(r[0]), r[1] and int(r[1]) or None
+ return start, end and ((end-start) + 1)
+
class MPDParsingError(Exception):
pass
@@ -322,9 +332,53 @@ class EventStream(MPDNode):
__tag__ = "EventStream"
+class Initialization(MPDNode):
+ __tag__ = "Initialization"
+
+ def __init__(self, node, root=None, parent=None, *args, **kwargs):
+ super(Initialization, self).__init__(node, root, parent, *args, **kwargs)
+ self.source_url = self.attr("sourceURL")
+
+
+class SegmentURL(MPDNode):
+ __tag__ = "SegmentURL"
+
+ def __init__(self, node, root=None, parent=None, *args, **kwargs):
+ super(SegmentURL, self).__init__(node, root, parent, *args, **kwargs)
+ self.media = self.attr("media")
+ self.media_range = self.attr("mediaRange", parser=MPDParsers.range)
+
+
class SegmentList(MPDNode):
__tag__ = "SegmentList"
+ def __init__(self, node, root=None, parent=None, *args, **kwargs):
+ super(SegmentList, self).__init__(node, root, parent, *args, **kwargs)
+
+ self.presentation_time_offset = self.attr("presentationTimeOffset")
+ self.timescale = self.attr("timescale", parser=int)
+ self.duration = self.attr("duration", parser=int)
+ self.start_number = self.attr("startNumber", parser=int, default=1)
+
+ if self.duration:
+ self.duration_seconds = self.duration / float(self.timescale)
+ else:
+ self.duration_seconds = None
+
+
+ self.initialization = self.only_child(Initialization)
+ self.segment_urls = self.children(SegmentURL, minimum=1)
+
+ @property
+ def segments(self):
+ if self.initialization:
+ yield Segment(self.make_url(self.initialization.source_url), 0, init=True, content=False)
+ for n, segment_url in enumerate(self.segment_urls, self.start_number):
+ yield Segment(self.make_url(segment_url.media), self.duration_seconds, range=segment_url.media_range)
+
+ def make_url(self, url):
+ return BaseURL.join(self.base_url, url)
+
class AdaptationSet(MPDNode):
__tag__ = u"AdaptationSet"
@@ -523,7 +577,7 @@ def __init__(self, node, root=None, parent=None, *args, **kwargs):
self.baseURLs = self.children(BaseURL)
self.subRepresentation = self.children(SubRepresentation)
self.segmentBase = self.only_child(SegmentBase)
- self.segmentList = self.only_child(SegmentList)
+ self.segmentList = self.children(SegmentList)
self.segmentTemplate = self.only_child(SegmentTemplate)
def segments(self, **kwargs):
@@ -538,7 +592,7 @@ def segments(self, **kwargs):
"""
segmentBase = self.segmentBase or self.walk_back_get_attr("segmentBase")
- segmentList = self.segmentList or self.walk_back_get_attr("segmentList")
+ segmentLists = self.segmentList or self.walk_back_get_attr("segmentList")
segmentTemplate = self.segmentTemplate or self.walk_back_get_attr("segmentTemplate")
if segmentTemplate:
@@ -549,6 +603,10 @@ def segments(self, **kwargs):
yield segment
else:
yield segment
+ elif segmentLists:
+ for segmentList in segmentLists:
+ for segment in segmentList.segments:
+ yield segment
else:
yield Segment(self.base_url, 0, True, True)
| diff --git a/tests/resources/dash/test_7.mpd b/tests/resources/dash/test_7.mpd
new file mode 100644
--- /dev/null
+++ b/tests/resources/dash/test_7.mpd
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns="urn:mpeg:dash:schema:mpd:2011"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd"
+ profiles="urn:mpeg:dash:profile:isoff-main:2011"
+ type="static"
+ publishTime="2018-06-25T18:01:58Z"
+ mediaPresentationDuration="PT53M18.059S"
+ minBufferTime="PT1.5S">
+<ProgramInformation>
+ <Title>test/dash.smil</Title>
+</ProgramInformation>
+<Period id="0" start="PT0.0S">
+ <AdaptationSet id="0" group="1" mimeType="video/mp4" maxWidth="1920" maxHeight="1080" par="16:9" frameRate="25" segmentAlignment="true" startWithSAP="1" subsegmentAlignment="true" subsegmentStartsWithSAP="1">
+ <Representation id="p0va0br4332748" codecs="avc1.640028" width="1920" height="1080" sar="1:1" bandwidth="4332748">
+ <SegmentList presentationTimeOffset="0" timescale="90000" duration="900000" startNumber="1">
+ <Initialization sourceURL="chunk_ctvideo_ridp0va0br4332748_cinit_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn1_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn2_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn3_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn4_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn5_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn6_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn7_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn8_mpd.m4s"/>
+ <SegmentURL media="chunk_ctvideo_ridp0va0br4332748_cn9_mpd.m4s"/>
+ </SegmentList>
+ </Representation>
+ </AdaptationSet>
+</Period>
+</MPD>
diff --git a/tests/streams/test_dash_parser.py b/tests/streams/test_dash_parser.py
--- a/tests/streams/test_dash_parser.py
+++ b/tests/streams/test_dash_parser.py
@@ -61,6 +61,11 @@ def test_timedelta(self):
self.assertEqual(MPDParsers.timedelta(10)(100),
datetime.timedelta(0, 10.0))
+ def test_range(self):
+ self.assertEqual(MPDParsers.range("100-"), (100, None))
+ self.assertEqual(MPDParsers.range("100-199"), (100, 100))
+ self.assertRaises(MPDParsingError, MPDParsers.range, "100")
+
class TestMPDParser(unittest.TestCase):
maxDiff = None
@@ -149,6 +154,21 @@ def test_segments_static_no_publish_time(self):
'http://test.se/dash/150633-video_eng=194000-4000.dash',
])
+ def test_segments_list(self):
+ with xml("dash/test_7.mpd") as mpd_xml:
+ mpd = MPD(mpd_xml, base_url="http://test.se/", url="http://test.se/manifest.mpd")
+
+ segments = mpd.periods[0].adaptationSets[0].representations[0].segments()
+ init_segment = next(segments)
+ self.assertEqual(init_segment.url, "http://test.se/chunk_ctvideo_ridp0va0br4332748_cinit_mpd.m4s")
+
+ video_segments = [x.url for x in itertools.islice(segments, 3)]
+ self.assertSequenceEqual(video_segments,
+ ['http://test.se/chunk_ctvideo_ridp0va0br4332748_cn1_mpd.m4s',
+ 'http://test.se/chunk_ctvideo_ridp0va0br4332748_cn2_mpd.m4s',
+ 'http://test.se/chunk_ctvideo_ridp0va0br4332748_cn3_mpd.m4s',
+ ])
+
def test_segments_dynamic_timeline_continue(self):
with xml("dash/test_6_p1.mpd") as mpd_xml_p1:
with xml("dash/test_6_p2.mpd") as mpd_xml_p2:
| MPEG-DASH
### Checklist
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
MPD link extracted from https://www.atresplayer.com/antena3/series/el-secreto-de-puente-viejo/julieta-y-los-hermanos-ortega/25-06-18_5b2bdd907ed1a8d25b535d21/
```
streamlink.exe https://deswowa3player.akamaized.net/vsg/_definst_/assets3/2018/06/21/C4681643-C9A2-4C50-85AB-70A64228EC98/dash.smil/manifest_mvlist.mpd best --player ffplay -l debug
[console][debug] OS: Windows 7
[console][debug] Python: 3.5.2
[console][debug] Streamlink: 0.13.0
[console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0)
[console][info] Found matching plugin dash for URL https://deswowa3player.akamaized.net/vsg/_definst_/assets3/2018/06/21/C4681643-C9A2-4C50-85AB-70A64228EC98/dash.smil/manifest_mvlist.mpd
[plugin.dash][debug] Parsing MPD URL: https://deswowa3player.akamaized.net/vsg/_definst_/assets3/2018/06/21/C4681643-C9A2-4C50-85AB-70A64228EC98/dash.smil/manifest_mvlist.mpd
[console][info] Available streams: 240p (worst), 360p, 480p, 720p, 1080p (best)
[console][info] Opening stream: 1080p (dash)
[stream.dash][debug] Opening DASH reader for: p0va0br4332748
[stream.dash][debug] Opening DASH reader for: p0aa0br128000
[stream.mp4mux-ffmpeg][debug] ffmpeg command: C:\Program Files (x86)\Streamlink\ffmpeg\ffmpeg.exe -nostats -y -i \\.\pipe\ffmpeg-4340-187 -i \\.\pipe\ffmpeg-434
0-51 -c:v copy -c:a copy -copyts -f matroska pipe:1
[stream.ffmpegmux][debug] Starting copy to pipe: \\.\pipe\ffmpeg-4340-187
[stream.ffmpegmux][debug] Starting copy to pipe: \\.\pipe\ffmpeg-4340-51
[stream.dash][debug] Download of segment: https://deswowa3player.akamaized.net/vsg/_definst_/assets3/2018/06/21/C4681643-C9A2-4C50-85AB-70A64228EC98/dash.smil complete
[console][debug] Pre-buffering 8192 bytes
[stream.dash][debug] Download of segment: https://deswowa3player.akamaized.net/vsg/_definst_/assets3/2018/06/21/C4681643-C9A2-4C50-85AB-70A64228EC98/dash.smil complete
[stream.segmented][debug] Closing worker thread
[stream.segmented][debug] Closing writer thread
[stream.ffmpegmux][debug] Pipe copy complete: \\.\pipe\ffmpeg-4340-187
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.segmented][debug] Closing worker thread
[stream.segmented][debug] Closing writer thread
[stream.ffmpegmux][debug] Closed all the substreams
[console][error] Try 1/1: Could not open stream <Stream()> (No data returned from stream)
error: Could not open stream <Stream()>, tried 1 times, exiting
[console][info] Closing currently open stream...
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.ffmpegmux][debug] Closed all the substreams
```
| 2018-06-26T10:58:06 |
|
streamlink/streamlink | 1,857 | streamlink__streamlink-1857 | [
"1834"
] | f8f2c9ca540079fa031cd3296eb9bc14105db328 | diff --git a/src/streamlink/plugins/mjunoon.py b/src/streamlink/plugins/mjunoon.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/mjunoon.py
@@ -0,0 +1,34 @@
+import logging
+import re
+
+from streamlink.compat import urlparse, parse_qsl
+from streamlink.plugin import Plugin
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
+
+log = logging.getLogger(__name__)
+
+
+class Mjunoon(Plugin):
+ url_re = re.compile(r"""https?://(?:www.)?mjunoon.tv/""", re.VERBOSE)
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls.url_re.match(url) is not None
+
+ def _get_streams(self):
+ res = self.session.http.get(self.url)
+ for script in itertags(res.text, 'script'):
+ if script.attributes.get("id") == "playerScript":
+ log.debug("Found the playerScript script tag")
+ urlparts = urlparse(script.attributes.get("src"))
+ i = 0
+
+ for key, url in parse_qsl(urlparts.query):
+ if key == "streamUrl":
+ i += 1
+ for s in HLSStream.parse_variant_playlist(self.session, url, params=dict(id=i), verify=False).items():
+ yield s
+
+
+__plugin__ = Mjunoon
| diff --git a/tests/test_plugin_mjunoon.py b/tests/test_plugin_mjunoon.py
new file mode 100644
--- /dev/null
+++ b/tests/test_plugin_mjunoon.py
@@ -0,0 +1,36 @@
+import unittest
+import requests_mock
+
+from streamlink import Streamlink
+from tests.mock import patch, Mock, ANY, call
+from streamlink.plugins.mjunoon import Mjunoon
+
+
+class TestPluginMixer(unittest.TestCase):
+ def test_can_handle_url(self):
+ # should match
+ self.assertTrue(Mjunoon.can_handle_url('https://mjunoon.tv/news-live'))
+ self.assertTrue(Mjunoon.can_handle_url('http://mjunoon.tv/watch/some-long-vod-name23456'))
+ self.assertTrue(Mjunoon.can_handle_url('https://www.mjunoon.tv/other-live'))
+ self.assertTrue(Mjunoon.can_handle_url('https://www.mjunoon.tv/watch/something-else-2321'))
+
+ def test_can_handle_url_negative(self):
+ # shouldn't match
+ self.assertFalse(Mjunoon.can_handle_url('https://mjunoon.com'))
+
+ @patch('streamlink.plugins.mjunoon.HLSStream.parse_variant_playlist')
+ def test_get_streams(self, parse_variant_playlist):
+ session = Streamlink()
+ Mjunoon.bind(session, "test")
+ script_text = """
+ <script id="playerScript" src="playerAssets/js/player.js?v=2.2&streamUrl=https://vod.mjunoon.tv:8181/live/41/41.m3u8&streamUrl=https://vod.mjunoon.tv:8181/live/17/17.m3u8"></script>
+ """
+ parse_variant_playlist.items.return_value = [("test", Mock())]
+ with requests_mock.Mocker() as rmock:
+ rmock.get("https://mjunoon.tv/news-live", text=script_text)
+ plugin = Mjunoon("https://mjunoon.tv/news-live")
+ _ = list(plugin.streams())
+ self.assertSequenceEqual(
+ [call(ANY, "https://vod.mjunoon.tv:8181/live/41/41.m3u8", params=dict(id=1), verify=False),
+ call(ANY, "https://vod.mjunoon.tv:8181/live/17/17.m3u8", params=dict(id=2), verify=False)],
+ [parse_variant_playlist.mock_calls[0], parse_variant_playlist.mock_calls[3]])
| plugin rerquest for mjunoon
https://www.mjunoon.tv/
streamlink https://www.mjunoon.tv/a-tv-live
[cli][info] streamlink is running as root! Be careful!
error: No plugin can handle URL: https://www.mjunoon.tv/a-tv-live
| live streeams
https://www.mjunoon.tv/urdu-1-live
https://www.mjunoon.tv/filmazia-live
https://www.mjunoon.tv/aruj-live
and more vod stream
https://www.mjunoon.tv/watch/tonight-with-jasmeen-21june2018-kanwar-dilshad-amjad-shoaib-khawaja-fareed-u913yoexxyg
https://www.mjunoon.tv/watch/tax-aur-aap-ep-28-10-feb-2017-opnbtxuuzxu
anything else required lett me know
some details about the website, it looks **legal** to me.
> mjunoon: Powered by Convex Interactive ...
https://www.mjunoon.tv/about-us
> Watch licensed Live TV & Radio channels for Free.
https://play.google.com/store/apps/details?id=com.convex.mjunoon.TV&hl=en_US
> PEMRA (Pakistan Electronic Media Regulatory Authority)
Grants Mobile TV License to Convex Interactive
https://propakistani.pk/2016/04/01/pemra-grants-mobile-tv-license-to-convex-interactive/
yeah its hundred percent legal | 2018-06-26T22:41:51 |
streamlink/streamlink | 1,860 | streamlink__streamlink-1860 | [
"1858"
] | f8f2c9ca540079fa031cd3296eb9bc14105db328 | diff --git a/src/streamlink/plugins/tv8cat.py b/src/streamlink/plugins/tv8cat.py
--- a/src/streamlink/plugins/tv8cat.py
+++ b/src/streamlink/plugins/tv8cat.py
@@ -1,80 +1 @@
-from __future__ import print_function
-import re
-
-from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.compat import urlparse, parse_qsl
-from streamlink.plugin.api import useragents
-from streamlink.plugin.api import validate
-from streamlink.stream import HLSStream
-from streamlink.stream import RTMPStream
-from streamlink.utils import parse_json
-
-
-class TV8cat(Plugin):
- url_re = re.compile(r"https?://(?:www\.)?tv8\.cat/directe/?")
- live_iframe = "http://www.8tv.cat/wp-content/themes/8tv/_/inc/_live_html.php"
- iframe_re = re.compile(r'iframe .*?src="((?:https?)?//[^"]*?)"')
- account_id_re = re.compile(r"accountId:\"(\d+?)\"")
- policy_key_re = re.compile(r"policyKey:\"(.+?)\"")
- britecove = "https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}"
- britecove_schema = validate.Schema({
- "sources": [
- {"height": int,
- validate.optional("src"): validate.url(),
- validate.optional("app_name"): validate.url(scheme="rtmp"),
- validate.optional("stream_name"): validate.text}
- ]
- })
-
- @classmethod
- def can_handle_url(cls, url):
- return cls.url_re.match(url) is not None
-
- def _find_iframe(self, res):
- iframe = self.iframe_re.search(res.text)
- url = iframe and iframe.group(1)
- if url and url.startswith("//"):
- p = urlparse(self.url)
- url = "{0}:{1}".format(p.scheme, url)
- return url
-
- def _britecove_params(self, url):
- res = http.get(url, headers={"User-Agent": useragents.FIREFOX,
- "Referer": self.url})
- acc = self.account_id_re.search(res.text)
- pk = self.policy_key_re.search(res.text)
-
- query = dict(parse_qsl(urlparse(url).query))
- return {"video_id": query.get("videoId"),
- "account_id": acc and acc.group(1),
- "policy_key": pk and pk.group(1),
- }
-
- def _get_stream_data(self, **params):
- api_url = self.britecove.format(**params)
- res = http.get(api_url, headers={"Accept": "application/json;pk={policy_key}".format(**params)})
- return parse_json(res.text, schema=self.britecove_schema)
-
- def _get_streams(self):
- res = http.get(self.live_iframe)
- britecove_url = self._find_iframe(res)
-
- if britecove_url:
- self.logger.debug("Found britecove embed url: {0}", britecove_url)
- params = self._britecove_params(britecove_url)
- self.logger.debug("Got britecode params: {0}", params)
- stream_info = self._get_stream_data(**params)
- for source in stream_info.get("sources"):
- if source.get("src"):
- for s in HLSStream.parse_variant_playlist(self.session, source.get("src")).items():
- yield s
- else:
- q = "{0}p".format(source.get("height"))
- s = RTMPStream(self.session,
- {"rtmp": source.get("app_name"),
- "playpath": source.get("stream_name")})
- yield q, s
-
-
-__plugin__ = TV8cat
+# Plugin removed, see https://github.com/streamlink/streamlink/issues/1858
| diff --git a/tests/test_plugin_tv8cat.py b/tests/test_plugin_tv8cat.py
deleted file mode 100644
--- a/tests/test_plugin_tv8cat.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import unittest
-
-from streamlink.plugins.tv8cat import TV8cat
-
-
-class TestPluginTV8cat(unittest.TestCase):
- def test_can_handle_url(self):
- # should match
- self.assertTrue(TV8cat.can_handle_url("http://tv8.cat/directe"))
- self.assertTrue(TV8cat.can_handle_url("http://www.tv8.cat/directe"))
- self.assertTrue(TV8cat.can_handle_url("http://www.tv8.cat/directe/"))
- self.assertTrue(TV8cat.can_handle_url("https://tv8.cat/directe/"))
-
- # shouldn't match
- self.assertFalse(TV8cat.can_handle_url("http://www.tv8.cat/algo/"))
- self.assertFalse(TV8cat.can_handle_url("http://www.tvcatchup.com/"))
- self.assertFalse(TV8cat.can_handle_url("http://www.youtube.com/"))
| 8tv.cat live broadcast gone
### Description
8tv.cat no longer broadcast live streams. We should remove the plugin as it no longer works, and is not fixable.
It never actually worked quite right, the URL regex was wrong - if you used the wrong URL it worked fine, but with the actual URL it did not work.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-06-27T14:46:11 |
|
streamlink/streamlink | 1,863 | streamlink__streamlink-1863 | [
"1862"
] | 0cf6ce0f7d6c0f3451554f1d1f7daee72bd09ccb | diff --git a/src/streamlink/plugins/nineanime.py b/src/streamlink/plugins/nineanime.py
--- a/src/streamlink/plugins/nineanime.py
+++ b/src/streamlink/plugins/nineanime.py
@@ -1,69 +1 @@
-import re
-from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.plugin.api import useragents
-from streamlink.plugin.api import validate
-from streamlink.stream import HTTPStream
-from streamlink.compat import urlparse
-
-
-class NineAnime(Plugin):
- _episode_info_url = "//9anime.to/ajax/episode/info"
-
- _info_schema = validate.Schema({
- "grabber": validate.url(),
- "params": {
- "id": validate.text,
- "token": validate.text,
- "options": validate.text,
- }
- })
-
- _streams_schema = validate.Schema({
- "token": validate.text,
- "error": None,
- "data": [{
- "label": validate.text,
- "file": validate.url(),
- "type": "mp4"
- }]
- })
-
- _url_re = re.compile(r"https?://9anime.to/watch/(?:[^.]+?\.)(\w+)/(\w+)")
-
- @classmethod
- def can_handle_url(cls, url):
- return cls._url_re.match(url) is not None
-
- def add_scheme(self, url):
- # update the scheme for the grabber url if required
- if url.startswith("//"):
- url = "{0}:{1}".format(urlparse(self.url).scheme, url)
- return url
-
- @Plugin.broken(1110)
- def _get_streams(self):
- match = self._url_re.match(self.url)
- film_id, episode_id = match.groups()
-
- headers = {
- "Referer": self.url,
- "User-Agent": useragents.FIREFOX
- }
-
- # Get the info about the Episode, including the Grabber API URL
- info_res = http.get(self.add_scheme(self._episode_info_url),
- params=dict(update=0, film=film_id, id=episode_id),
- headers=headers)
- info = http.json(info_res, schema=self._info_schema)
-
- # Get the data about the streams from the Grabber API
- grabber_url = self.add_scheme(info["grabber"])
- stream_list_res = http.get(grabber_url, params=info["params"], headers=headers)
- stream_data = http.json(stream_list_res, schema=self._streams_schema)
-
- for stream in stream_data["data"]:
- yield stream["label"], HTTPStream(self.session, stream["file"])
-
-
-__plugin__ = NineAnime
+# Plugin removed - https://github.com/streamlink/streamlink/issues/1862
| Remove 9anime.to
As discussed over here: https://github.com/streamlink/streamlink/issues/1110#issuecomment-400687075 9anime.to isn't worth supporting at this point and is broken so I'm proposing we remove it.
| 2018-06-27T22:46:25 |
||
streamlink/streamlink | 1,878 | streamlink__streamlink-1878 | [
"1872"
] | 215d78956138452353c06810785b7919e17a02a8 | diff --git a/src/streamlink/plugins/live_russia_tv.py b/src/streamlink/plugins/live_russia_tv.py
--- a/src/streamlink/plugins/live_russia_tv.py
+++ b/src/streamlink/plugins/live_russia_tv.py
@@ -1,33 +1,81 @@
+import logging
import re
+
from streamlink.plugin import Plugin
-from streamlink.plugin.api import http
-from streamlink.stream import HLSStream
+from streamlink.plugin.api import http, validate
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream, HTTPStream
+
+log = logging.getLogger(__name__)
+
class LiveRussia(Plugin):
- url_re = re.compile(r"https?://(?:www.)?live.russia.tv/index/index/channel_id/")
- iframe_re = re.compile(r"""<iframe[^>]*src=["']([^'"]+)["'][^>]*>""")
- stream_re = re.compile(r"""window.pl.data.*m3u8":"(.*)"}.*};""")
+ url_re = re.compile(r"https?://(?:www\.|live\.)?russia.tv")
+ _data_re = re.compile(r"""window\.pl\.data\.([\w_]+)\s*=\s*['"]?(.*?)['"]?;""")
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
+ def _get_iframe_url(self, url):
+ res = http.get(url)
+ for iframe in itertags(res.text, 'iframe'):
+ src = iframe.attributes.get("src")
+ if src:
+ return src
+
+ def _get_stream_info_url(self, url):
+ data = {}
+ res = http.get(url)
+ for m in self._data_re.finditer(res.text):
+ data[m.group(1)] = m.group(2)
+
+ log.debug("Got pl_data={0}".format(data))
+
+ if data:
+ if data["isVod"] == '0':
+ return "https:{domain}/iframe/datalive/id/{id}/sid/{sid}".format(**data)
+ else:
+ return "https:{domain}/iframe/datavideo/id/{id}/sid/{sid}".format(**data)
+
def _get_streams(self):
- res = http.get(self.url)
- iframe_result = re.search(self.iframe_re, res.text)
+ iframe_url = self._get_iframe_url(self.url)
+
+ if iframe_url:
+ log.debug("Found iframe URL={0}".format(iframe_url))
+ info_url = self._get_stream_info_url(iframe_url)
+
+ if info_url:
+ log.debug("Getting info from URL: {0}".format(info_url))
+ res = http.get(info_url, headers={"Referer": iframe_url})
+ data = http.json(res)
+
+ if data['status'] == 200:
+ for media in data['data']['playlist']['medialist']:
+ if media['errors']:
+ log.error(media['errors'].replace('\n', '').replace('\r', ''))
+
+ for media_type in media.get('sources', []):
+
+ if media_type == "m3u8":
+ hls_url = media['sources'][media_type]['auto']
+ for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
+ yield s
+
+ if media_type == "http":
+ for pix, url in media['sources'][media_type].items():
+ yield "{0}p".format(pix), HTTPStream(self.session, url)
+ else:
+ log.error("An error occurred: {0}".format(data['errors'].replace('\n', '').replace('\r', '')))
+ else:
+ log.error("Unable to get stream info URL")
+ else:
+ log.error("Could not find video iframe")
+
- if not iframe_result:
- self.logger.error("The requested content is unavailable.")
- return
- res = http.get(iframe_result.group(1))
- stream_url_result = re.search(self.stream_re, res.text)
- if not stream_url_result:
- self.logger.error("The requested content is unavailable.")
- return
- return HLSStream.parse_variant_playlist(self.session, stream_url_result.group(1))
-__plugin__ = LiveRussia
\ No newline at end of file
+__plugin__ = LiveRussia
| diff --git a/tests/test_plugin_liverussiatv.py b/tests/test_plugin_liverussiatv.py
--- a/tests/test_plugin_liverussiatv.py
+++ b/tests/test_plugin_liverussiatv.py
@@ -2,12 +2,16 @@
from streamlink.plugins.live_russia_tv import LiveRussia
+
class TestPluginLiveRussiaTv(unittest.TestCase):
def test_can_handle_url(self):
# should match
self.assertTrue(LiveRussia.can_handle_url('https://live.russia.tv/index/index/channel_id/1'))
self.assertTrue(LiveRussia.can_handle_url('https://live.russia.tv/index/index/channel_id/199'))
+ self.assertTrue(LiveRussia.can_handle_url('https://live.russia.tv/'))
+ self.assertTrue(LiveRussia.can_handle_url('http://live.russia.tv/somethingelse'))
+ self.assertTrue(LiveRussia.can_handle_url('https://russia.tv/fifaworldcup/games/1832668/video/1800840'))
- # shouldn't match
- self.assertFalse(LiveRussia.can_handle_url('https://live.russia.tv/'))
- self.assertFalse(LiveRussia.can_handle_url('http://live.russia.tv/wrongURI'))
\ No newline at end of file
+ def test_can_handle_url_negative(self):
+ self.assertFalse(LiveRussia.can_handle_url('http://live.france.tv/somethingelse'))
+ self.assertFalse(LiveRussia.can_handle_url('https://youtube.com/watch?v=4567uj'))
| Problem with live.russia.tv
I have Problem with the Plugin live.russia.tv :
```
#SERVICE 4097:0:1:0:0:0:224:0:0:0:http%3a//127.0.0.1%3a8088/https%3a//live.russia.tv/index/index/channel_id/76:Москва 24 HD
#DESCRIPTION Москва 24 HD
#SERVICE 4097:0:1:0:0:0:449:0:0:0:http%3a//127.0.0.1%3a8088/https%3a//live.russia.tv/index/index/channel_id/1:Rossija 1 HD
#DESCRIPTION Rossija 1 HD
#SERVICE 4097:0:1:0:0:0:445:0:0:0:http%3a//127.0.0.1%3a8088/https%3a//live.russia.tv/index/index/channel_id/82:Rossija RTR HD
#DESCRIPTION Rossija RTR HD
#SERVICE 4097:0:1:0:0:0:447:0:0:0:http%3a//127.0.0.1%3a8088/https%3a//live.russia.tv/index/index/channel_id/3:Rossija 24 HD
#DESCRIPTION Rossija 24 HD
```
The Channels not working on streamlink - from PC work the channels ok.
| You have not provided any logs, or an description of your set up. Please include the required information.
I wanted to watch the following Russian channels via streramlink available at https://live.russia.tv:
Rossija 1
Mockba24
Rossiya RTR
and others available on this page. And then I pasted into the channel list and I have neither image nor sound - channels just do not work.
You have to provide the debug log which the issue template is asking for, otherwise it is impossible for anyone else to understand your issue. What you have posted is no Streamlink log output.
Here is the issue template again:
https://raw.githubusercontent.com/streamlink/streamlink/master/ISSUE_TEMPLATE.md
> And then I pasted into the channel list and I have neither image nor sound - channels just do not work.
?
Are you even using Streamlink, or are you using something else? | 2018-06-28T23:50:29 |
streamlink/streamlink | 1,888 | streamlink__streamlink-1888 | [
"1865"
] | 0e48e2f01a370fa83cabc27b067b6f72cd1b8d9d | diff --git a/src/streamlink/plugins/youtube.py b/src/streamlink/plugins/youtube.py
--- a/src/streamlink/plugins/youtube.py
+++ b/src/streamlink/plugins/youtube.py
@@ -1,22 +1,19 @@
-import re
+from __future__ import unicode_literals
-from requests import codes
+import argparse
+import logging
+import re
-from streamlink.compat import urlparse, parse_qsl
+from streamlink.compat import parse_qsl, is_py2
from streamlink.plugin import Plugin, PluginError, PluginArguments, PluginArgument
from streamlink.plugin.api import http, validate, useragents
-from streamlink.plugin.api.utils import parse_query
+from streamlink.plugin.api.utils import parse_query, itertags
from streamlink.stream import HTTPStream, HLSStream
from streamlink.stream.ffmpegmux import MuxedStream
from streamlink.utils import parse_json, search_dict
+from streamlink.utils.encoding import maybe_decode
-API_KEY = "AIzaSyBDBi-4roGzWJN4du9TuDMLd_jVTcVkKz4"
-API_BASE = "https://www.googleapis.com/youtube/v3"
-API_SEARCH_URL = API_BASE + "/search"
-API_VIDEO_INFO = "https://youtube.com/get_video_info"
-HLS_HEADERS = {
- "User-Agent": "Mozilla/5.0"
-}
+log = logging.getLogger(__name__)
def parse_stream_map(stream_map):
@@ -80,7 +77,7 @@ def parse_fmt_list(formatsmap):
),
validate.optional("hlsvp"): validate.text,
validate.optional("live_playback"): validate.transform(bool),
- validate.optional("reason"): validate.text,
+ validate.optional("reason"): validate.all(validate.text, validate.transform(maybe_decode)),
validate.optional("livestream"): validate.text,
validate.optional("live_playback"): validate.text,
"status": validate.text
@@ -97,8 +94,6 @@ def parse_fmt_list(formatsmap):
validate.get("items")
)
-_channelid_re = re.compile(r'meta itemprop="channelId" content="([^"]+)"')
-_livechannelid_re = re.compile(r'meta property="og:video:url" content="([^"]+)')
_ytdata_re = re.compile(r'window\["ytInitialData"\]\s*=\s*({.*?});', re.DOTALL)
_url_re = re.compile(r"""
http(s)?://(\w+\.)?youtube.com
@@ -120,6 +115,7 @@ def parse_fmt_list(formatsmap):
class YouTube(Plugin):
+ _video_info_url = "https://youtube.com/get_video_info"
adp_video = {
137: "1080p",
303: "1080p60", # HFR
@@ -146,7 +142,7 @@ class YouTube(Plugin):
PluginArgument(
"api-key",
sensitive=True,
- help="API key to use for YouTube API requests"
+ help=argparse.SUPPRESS # no longer used
)
)
@@ -203,7 +199,7 @@ def _create_adaptive_streams(self, info, streams, protected):
for itag, name in self.adp_video.items():
if itag in adaptive_streams:
vurl = adaptive_streams[itag]
- self.logger.debug("MuxedStream: v {video} a {audio} = {name}".format(
+ log.debug("MuxedStream: v {video} a {audio} = {name}".format(
audio=best_audio_itag,
name=name,
video=itag,
@@ -214,84 +210,31 @@ def _create_adaptive_streams(self, info, streams, protected):
return streams, protected
- def _find_channel_video(self):
- res = http.get(self.url)
+ def _find_video_id(self, url):
+
+ m = _url_re.match(url)
+ if m.group("video_id"):
+ log.debug("Video ID from URL")
+ return m.group("video_id")
+ res = http.get(url)
datam = _ytdata_re.search(res.text)
if datam:
data = parse_json(datam.group(1))
# find the videoRenderer object, where there is a LVE NOW badge
+ for vid_ep in search_dict(data, 'currentVideoEndpoint'):
+ video_id = vid_ep.get("watchEndpoint", {}).get("videoId")
+ if video_id:
+ log.debug("Video ID from currentVideoEndpoint")
+ return video_id
for x in search_dict(data, 'videoRenderer'):
for bstyle in search_dict(x.get("badges", {}), "style"):
if bstyle == "BADGE_STYLE_TYPE_LIVE_NOW":
if x.get("videoId"):
- self.logger.debug("Found channel video ID via HTML: {0}", x["videoId"])
+ log.debug("Video ID from videoRenderer (live)")
return x["videoId"]
- else:
- # fall back on API
- self.logger.debug("No channel data, falling back to API")
- match = _channelid_re.search(res.text)
- if not match:
- return
-
- channel_id = match.group(1)
- self.logger.debug("Found channel_id: {0}".format(channel_id))
- return self._get_channel_video(channel_id)
-
- def _get_channel_video(self, channel_id):
- query = {
- "channelId": channel_id,
- "type": "video",
- "eventType": "live",
- "part": "id",
- "key": self.get_option("api_key") or API_KEY
- }
- res = http.get(API_SEARCH_URL, params=query, raise_for_status=False)
- if res.status_code == codes.ok:
- videos = http.json(res, schema=_search_schema)
-
- for video in videos:
- video_id = video["id"]["videoId"]
- self.logger.debug("Found video_id: {0}".format(video_id))
- return video_id
- else:
- try:
- errors = http.json(res, exception=ValueError)
- self.logger.error("Cloud not resolve channel video:")
- for error in errors['error']['errors']:
- self.logger.error(" {message} ({reason})".format(**error))
-
- except ValueError:
- self.logger.error("Cloud not resolve channel video: {0} error".format(res.status_code))
-
- def _find_canonical_stream_info(self):
- res = http.get(self.url)
- match = _livechannelid_re.search(res.text)
- if not match:
- return
-
- return self._get_stream_info(match.group(1))
-
- def _get_stream_info(self, url):
- match = _url_re.match(url)
- user = match.group("user")
- live_channel = match.group("liveChannel")
-
- if user:
- video_id = self._find_channel_video()
- elif live_channel:
- return self._find_canonical_stream_info()
- else:
- video_id = match.group("video_id")
- if video_id == "live_stream":
- query_info = dict(parse_qsl(urlparse(url).query))
- if "channel" in query_info:
- video_id = self._get_channel_video(query_info["channel"])
-
- if not video_id:
- return
-
+ def _get_stream_info(self, video_id):
# normal
_params_1 = {"el": "detailpage"}
# age restricted
@@ -306,14 +249,14 @@ def _get_stream_info(self, url):
params = {"video_id": video_id}
params.update(_params)
- res = http.get(API_VIDEO_INFO, params=params, headers=HLS_HEADERS)
- info_parsed = parse_query(res.text, name="config", schema=_config_schema)
+ res = http.get(self._video_info_url, params=params)
+ info_parsed = parse_query(res.content if is_py2 else res.text, name="config", schema=_config_schema)
if info_parsed.get("status") == "fail":
- self.logger.debug("get_video_info - {0}: {1}".format(
+ log.debug("get_video_info - {0}: {1}".format(
count, info_parsed.get("reason"))
)
continue
- self.logger.debug("get_video_info - {0}: Found data".format(count))
+ log.debug("get_video_info - {0}: Found data".format(count))
break
return info_parsed
@@ -322,12 +265,23 @@ def _get_streams(self):
http.headers.update({'User-Agent': useragents.CHROME})
is_live = False
- info = self._get_stream_info(self.url)
- if not info:
+ video_id = self._find_video_id(self.url)
+ if not video_id:
+ log.error("Could not find a video on this page")
+ return
+
+ log.debug("Using video ID: {0}", video_id)
+
+ info = self._get_stream_info(video_id)
+ if info and info.get("status") == "fail":
+ log.error("Could not get video info: {0}".format(info.get("reason")))
+ return
+ elif not info:
+ log.error("Could not get video info")
return
if info.get("livestream") == '1' or info.get("live_playback") == '1':
- self.logger.debug("This video is live.")
+ log.debug("This video is live.")
is_live = True
formats = info.get("fmt_list")
@@ -353,11 +307,11 @@ def _get_streams(self):
if hls_playlist:
try:
hls_streams = HLSStream.parse_variant_playlist(
- self.session, hls_playlist, headers=HLS_HEADERS, namekey="pixels"
+ self.session, hls_playlist, namekey="pixels"
)
streams.update(hls_streams)
except IOError as err:
- self.logger.warning("Failed to extract HLS streams: {0}", err)
+ log.warning("Failed to extract HLS streams: {0}", err)
if not streams and protected:
raise PluginError("This plugin does not support protected videos, "
| No playable streams with youtube live streams
- [x] This is a bug report.
- [ ] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
### Expected / Actual behavior
### Reproduction steps / Explicit stream URLs to test
1. www.youtube.com/user/euronewsde/live
2. www.youtube.com/user/deutschewelle/live
3. www.youtube.com/user/ROCKETBEANSTV/live
### Logs
streamlink www.youtube.com/user/euronewsde/live best -l debug
[cli][debug] OS: Windows 8
[cli][debug] Python: 2.7.9
[cli][debug] Streamlink: 0.14.0
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0)
[cli][info] Found matching plugin youtube for URL www.youtube.com/user/euronewsde/live
error: No playable streams found on this URL: www.youtube.com/user/euronewsde/live
Many thanks for your support
| It works just fine if you use the direct links:
for euronewsde: https://www.youtube.com/watch?v=uEiyA-V9IHM
for deutschewelle: https://www.youtube.com/watch?v=mEB8WDOOF_4
etc.
@mmetak, you are right, but this are only temporary links.
These pages seem to have slightly different layouts. The YouTube plugin is kind of a mess and could do with some major refactoring :)
Yes, that's why I did not start to fix it :)
**1. quick fix**
remove the __/live__ part
**2.**
this part could be used for the streamlink plugin
```py
'currentVideoEndpoint': {
'clickTrackingParams': 'XXX=',
'commandMetadata': {
'webCommandMetadata': {
'url': '/watch?v=uEiyA-V9IHM',
'webPageType': 'WEB_PAGE_TYPE_WATCH'
}
},
'watchEndpoint': {
'videoId': 'uEiyA-V9IHM'
}
},
```
@back-to does **2.** appear on every page with a video (it seems to be)? This could be used for a more concise implementation.
idk, only tested for `/live` urls
i would just use it as a fallback if this fails
https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugins/youtube.py#L224-L225
---
and maybe the api fallback should be removed completely
**or**
at least the `else:` or it won't work most of the time
https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugins/youtube.py#L231-L240
Yeah I was thinking that too when I looked at it again. `currentVideoEndpoint. watchEndpoint.videoId` exists for all the videos I checked, so far.
It's working to me with this build : `streamlink 0.12.1+8.ge2a5546`
```
streamlink "http://www.youtube.com/user/euronewsde/live" best
[cli][info] Found matching plugin youtube for URL http://www.youtube.com/user/euronewsde/live
[cli][info] Available streams: 144p (worst), 240p, 360p, 480p, 720p (best)
[cli][info] Opening stream: 720p (hls)
[cli][info] Starting player: "C:\Program Files\VideoLAN\VLC\vlc.exe"
[cli][info] Player closed
[cli][info] Stream ended
[cli][info] Closing currently open stream...
```
OK since I upgraded to latest streamlink build, is doesn't work for me either.
```
streamlink -l debug "https://www.youtube.com/user/euronewsde/live"
[cli][debug] OS: Windows 7
[cli][debug] Python: 2.7.13
[cli][debug] Streamlink: 0.14.2+8.g8d20fbcb
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.46.0)
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/user/e
uronewsde/live
error: No playable streams found on this URL: https://www.youtube.com/user/euronewsde/live
```
But this one is working fine :
```
streamlink -l debug "https://www.youtube.com/user/euronewsde/live?disable_polymer=1" best
[cli][debug] OS: Windows 7
[cli][debug] Python: 2.7.13
[cli][debug] Streamlink: 0.14.2+8.g8d20fbcb
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.46.0)
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/user/e
uronewsde/live?disable_polymer=1
[plugin.youtube][debug] No channel data, falling back to API
[plugin.youtube][debug] Found channel_id: UCACdxU3VrJIJc7ujxtHWs1w
[plugin.youtube][debug] Found video_id: uEiyA-V9IHM
[plugin.youtube][debug] get_video_info - 1: Found data
[plugin.youtube][debug] This video is live.
[cli][info] Available streams: 144p (worst), 240p, 360p, 480p, 720p (best)
[cli][info] Opening stream: 720p (hls)
``` | 2018-06-30T22:24:18 |
|
streamlink/streamlink | 1,926 | streamlink__streamlink-1926 | [
"1898"
] | 6bf654a291e2a792088384c7ba7c9dc9b2a14b1d | diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py
--- a/src/streamlink/stream/hls.py
+++ b/src/streamlink/stream/hls.py
@@ -295,15 +295,18 @@ class MuxedHLSStream(MuxedStream):
def __init__(self, session, video, audio, force_restart=False, ffmpeg_options=None, **args):
tracks = [video]
+ maps = ["0:v"]
if audio:
if isinstance(audio, list):
tracks.extend(audio)
else:
tracks.append(audio)
+ for i in range(1, len(tracks)):
+ maps.append("{0}:a".format(i))
substreams = map(lambda url: HLSStream(session, url, force_restart=force_restart, **args), tracks)
ffmpeg_options = ffmpeg_options or {}
- super(MuxedHLSStream, self).__init__(session, *substreams, format="mpegts", **ffmpeg_options)
+ super(MuxedHLSStream, self).__init__(session, *substreams, format="mpegts", maps=maps, **ffmpeg_options)
class HLSStream(HTTPStream):
| Audio playlist.m3u8
Can someone please tell me which command I have to execute in order to hear this video?
```
https://deswowa3player.akamaized.net/vsg/_definst_/assets2/2018/06/27/ED8FBB5B-31FD-4F6D-864C-A41F55670ED2/hls.smil/playlist.m3u8?pulse=assets2%2F2018%2F06%2F27%2FED8FBB5B-31FD-4F6D-864C-A41F55670ED2%2F%7C1530629459%7C685ee530053b51a73b454f27d0869916
```
| @DjUnknown, please use the issue template and post the commands you tried (eg. `streamlink <URL> best`? Please post `debug` logs too.
You might need `ffmpeg` installed, however with the logs we cannot help you. The templates are there so that we can help you more easily. If you don't follow the template you will not get an answer.
@beardypig
<!--
Thanks for reporting a bug!
Please read the contribution guidelines before creating a bug report:
(https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink)
Also check the list of known issues before reporting an issue!
Please fill out the following template. Be as detailed as possible.
Please see the text preview to avoid unnecessary formatting errors.
-->
## Bug Report
- [ ] I have read the contribution guidelines. <!-- Replace the space with an x to check the box: [x] -->
### Description
```
Link playlist.m3u8 extracted from https://www.atresplayer.com/antena3/series/el-secreto-de-puente-viejo/julieta-y-los-hermanos-ortega/03-07-18_5b3408497ed1a8c72cd472b5/
```
<!-- Explain the bug as clearly as you can. How is functionality impacted? Which OS/Player/Streamlink version are you using? Etc. -->
<!-- What do you expect to happen, and what is actually happening? -->
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
```
"C:\Program Files (x86)\Streamlink\bin\streamlink.exe" https://deswowa3player.akamaized.net/vsg/_definst_/assets2/2018/06/27/49029982-929F-40DA-9CDD-CB9FB71345B2/hls.smil/playlist.m3u8?pulse=assets2%2F2018%2F06%2F27%2F49029982-929F-40DA-9CDD-CB9FB71345B2%2F%7C1530649413%7C004405fd7333776cfdc52b81b35304b0 best --player "C:\Program Files\FFmpeg\ffplay.exe"
```
### Logs
```
"C:\Program Files (x86)\Streamlink\bin\streamlink.exe" h
ttps://deswowa3player.akamaized.net/vsg/_definst_/assets2/2018/06/27/49029982-92
9F-40DA-9CDD-CB9FB71345B2/hls.smil/playlist.m3u8?pulse=assets2%2F2018%2F06%2F27%
2F49029982-929F-40DA-9CDD-CB9FB71345B2%2F%7C1530649413%7C004405fd7333776cfdc52b8
1b35304b0 best --player "C:\Program Files\FFmpeg\ffplay.exe" -l debug
[cli][debug] OS: Windows 7
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin hls for URL https://deswowa3player.akamaized.n
et/vsg/_definst_/assets2/2018/06/27/49029982-929F-40DA-9CDD-CB9FB71345B2/hls.smi
l/playlist.m3u8?pulse=assets2%2F2018%2F06%2F27%2F49029982-929F-40DA-9CDD-CB9FB71
345B2%2F%7C1530649413%7C004405fd7333776cfdc52b81b35304b0
[plugin.hls][debug] URL=https://deswowa3player.akamaized.net/vsg/_definst_/asset
s2/2018/06/27/49029982-929F-40DA-9CDD-CB9FB71345B2/hls.smil/playlist.m3u8?pulse=
assets2%2F2018%2F06%2F27%2F49029982-929F-40DA-9CDD-CB9FB71345B2%2F%7C1530649413%
7C004405fd7333776cfdc52b81b35304b0; params={}
[stream.hls][debug] Using external audio tracks for stream 1080p (language=es, n
ame=Spanish)
[stream.hls][debug] Using external audio tracks for stream 720p (language=es, na
me=Spanish)
[stream.hls][debug] Using external audio tracks for stream 480p (language=es, na
me=Spanish)
[stream.hls][debug] Using external audio tracks for stream 360p (language=es, na
me=Spanish)
[stream.hls][debug] Using external audio tracks for stream 240p (language=es, na
me=Spanish)
[cli][info] Available streams: 240p (worst), 360p, 480p, 720p, 1080p (best)
[cli][info] Starting player: C:\Program Files\FFmpeg\ffplay.exe
[cli][info] Got HTTP request from Lavf/58.17.101
[cli][info] Opening stream: 1080p (hls-multi)
[stream.ffmpegmux][debug] Opening hls substream
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Segments in this playlist are encrypted
[stream.hls][debug] First Sequence: 0; Last Sequence: 319
[stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 0; End Sequ
ence: 319
[stream.hls][debug] Adding segment 0 to queue
[stream.ffmpegmux][debug] Opening hls substream
[stream.hls][debug] Adding segment 1 to queue
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 2 to queue
[stream.hls][debug] Adding segment 3 to queue
[stream.hls][debug] Adding segment 4 to queue
[stream.hls][debug] Adding segment 5 to queue
[stream.hls][debug] Adding segment 6 to queue
[stream.hls][debug] Adding segment 7 to queue
[stream.hls][debug] Adding segment 8 to queue
[stream.hls][debug] Adding segment 9 to queue
[stream.hls][debug] Adding segment 10 to queue
[stream.hls][debug] Adding segment 11 to queue
[stream.hls][debug] Adding segment 12 to queue
[stream.hls][debug] Adding segment 13 to queue
[stream.hls][debug] Adding segment 14 to queue
[stream.hls][debug] Adding segment 15 to queue
[stream.hls][debug] Adding segment 16 to queue
[stream.hls][debug] Adding segment 17 to queue
[stream.hls][debug] Adding segment 18 to queue
[stream.hls][debug] Adding segment 19 to queue
[stream.hls][debug] Adding segment 20 to queue
[stream.hls][debug] Adding segment 21 to queue
[stream.hls][debug] First Sequence: 0; Last Sequence: 319
[stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 0; End Sequ
ence: 319
[stream.hls][debug] Adding segment 0 to queue
[stream.hls][debug] Adding segment 1 to queue
[stream.hls][debug] Adding segment 2 to queue
[stream.mp4mux-ffmpeg][debug] ffmpeg command: C:\Program Files (x86)\Streamlink\
ffmpeg\ffmpeg.exe -nostats -y -i \\.\pipe\ffmpeg-2268-638 -i \\.\pipe\ffmpeg-226
8-430 -c:v copy -c:a copy -map 0 -map 1 -f mpegts pipe:1
[stream.hls][debug] Adding segment 3 to queue
[stream.ffmpegmux][debug] Starting copy to pipe: \\.\pipe\ffmpeg-2268-638
[stream.hls][debug] Adding segment 4 to queue
[stream.ffmpegmux][debug] Starting copy to pipe: \\.\pipe\ffmpeg-2268-430
[stream.hls][debug] Adding segment 5 to queue
[stream.hls][debug] Adding segment 6 to queue
[stream.hls][debug] Adding segment 7 to queue
[stream.hls][debug] Adding segment 8 to queue
[stream.hls][debug] Adding segment 9 to queue
[stream.hls][debug] Adding segment 10 to queue
[stream.hls][debug] Adding segment 11 to queue
[stream.hls][debug] Adding segment 12 to queue
[stream.hls][debug] Adding segment 13 to queue
[stream.hls][debug] Adding segment 14 to queue
[stream.hls][debug] Adding segment 15 to queue
[stream.hls][debug] Adding segment 16 to queue
[stream.hls][debug] Adding segment 17 to queue
[stream.hls][debug] Adding segment 18 to queue
[stream.hls][debug] Adding segment 19 to queue
[stream.hls][debug] Adding segment 20 to queue
[stream.hls][debug] Adding segment 21 to queue
[cli][debug] Pre-buffering 8192 bytes
[stream.hls][debug] Download of segment 0 complete
[stream.hls][debug] Adding segment 22 to queue
[stream.hls][debug] Download of segment 1 complete
[stream.hls][debug] Adding segment 23 to queue
[stream.hls][debug] Download of segment 2 complete
[stream.hls][debug] Adding segment 24 to queue
[stream.hls][debug] Download of segment 3 complete
[stream.hls][debug] Adding segment 25 to queue
[stream.hls][debug] Download of segment 4 complete
[stream.hls][debug] Adding segment 26 to queue
[stream.hls][debug] Download of segment 5 complete
[stream.hls][debug] Adding segment 27 to queue
[stream.hls][debug] Download of segment 6 complete
[stream.hls][debug] Adding segment 28 to queue
[stream.hls][debug] Download of segment 7 complete
[stream.hls][debug] Adding segment 29 to queue
[stream.hls][debug] Download of segment 8 complete
[stream.hls][debug] Adding segment 30 to queue
[stream.hls][debug] Download of segment 9 complete
[stream.hls][debug] Adding segment 31 to queue
[stream.hls][debug] Download of segment 0 complete
[stream.hls][debug] Adding segment 22 to queue
[stream.hls][debug] Download of segment 10 complete
[stream.hls][debug] Adding segment 32 to queue
[stream.hls][debug] Download of segment 11 complete
[stream.hls][debug] Adding segment 33 to queue
[stream.hls][debug] Download of segment 12 complete
[stream.hls][debug] Adding segment 34 to queue
[stream.hls][debug] Download of segment 13 complete
[stream.hls][debug] Adding segment 35 to queue
[stream.hls][debug] Download of segment 14 complete
[stream.hls][debug] Adding segment 36 to queue
[stream.hls][debug] Download of segment 15 complete
[stream.hls][debug] Adding segment 37 to queue
[stream.hls][debug] Download of segment 16 complete
[stream.hls][debug] Adding segment 38 to queue
[stream.hls][debug] Download of segment 17 complete
[stream.hls][debug] Adding segment 39 to queue
[stream.hls][debug] Download of segment 18 complete
[stream.hls][debug] Adding segment 40 to queue
[stream.hls][debug] Download of segment 19 complete
[stream.hls][debug] Adding segment 41 to queue
[stream.hls][debug] Download of segment 1 complete
[stream.hls][debug] Adding segment 23 to queue
[stream.hls][debug] Download of segment 20 complete
[stream.hls][debug] Adding segment 42 to queue
[cli][debug] Writing stream to player
[stream.hls][debug] Download of segment 21 complete
[stream.hls][debug] Adding segment 43 to queue
[stream.hls][debug] Download of segment 22 complete
[stream.hls][debug] Adding segment 44 to queue
[stream.hls][debug] Download of segment 23 complete
[stream.hls][debug] Adding segment 45 to queue
[stream.hls][debug] Download of segment 24 complete
[stream.hls][debug] Adding segment 46 to queue
[stream.hls][debug] Download of segment 25 complete
[stream.hls][debug] Adding segment 47 to queue
[stream.hls][debug] Download of segment 26 complete
[stream.hls][debug] Adding segment 48 to queue
[stream.hls][debug] Download of segment 27 complete
[stream.hls][debug] Adding segment 49 to queue
[stream.hls][debug] Download of segment 28 complete
[stream.hls][debug] Adding segment 50 to queue
[stream.hls][debug] Download of segment 29 complete
[stream.hls][debug] Adding segment 51 to queue
[stream.hls][debug] Download of segment 30 complete
[stream.hls][debug] Adding segment 52 to queue
[stream.hls][debug] Download of segment 2 complete
[stream.hls][debug] Adding segment 24 to queue
[stream.hls][debug] Download of segment 31 complete
[stream.hls][debug] Adding segment 53 to queue
[stream.hls][debug] Download of segment 32 complete
[stream.hls][debug] Adding segment 54 to queue
[stream.hls][debug] Download of segment 33 complete
[stream.hls][debug] Adding segment 55 to queue
[stream.hls][debug] Download of segment 34 complete
[stream.hls][debug] Adding segment 56 to queue
[stream.hls][debug] Download of segment 35 complete
[stream.hls][debug] Adding segment 57 to queue
[stream.hls][debug] Download of segment 36 complete
[stream.hls][debug] Adding segment 58 to queue
[stream.hls][debug] Download of segment 37 complete
[stream.hls][debug] Adding segment 59 to queue
[stream.hls][debug] Download of segment 38 complete
[stream.hls][debug] Adding segment 60 to queue
[stream.hls][debug] Download of segment 39 complete
[stream.hls][debug] Adding segment 61 to queue
[stream.hls][debug] Download of segment 40 complete
[stream.hls][debug] Adding segment 62 to queue
[stream.hls][debug] Download of segment 41 complete
[stream.hls][debug] Adding segment 63 to queue
[stream.hls][debug] Download of segment 42 complete
[stream.hls][debug] Adding segment 64 to queue
[stream.hls][debug] Download of segment 3 complete
[stream.hls][debug] Adding segment 25 to queue
[stream.hls][debug] Download of segment 43 complete
[stream.hls][debug] Adding segment 65 to queue
[stream.hls][debug] Download of segment 44 complete
[stream.hls][debug] Adding segment 66 to queue
[stream.hls][debug] Download of segment 45 complete
[stream.hls][debug] Adding segment 67 to queue
[stream.hls][debug] Download of segment 46 complete
[stream.hls][debug] Adding segment 68 to queue
[stream.hls][debug] Download of segment 47 complete
[stream.hls][debug] Adding segment 69 to queue
[stream.hls][debug] Download of segment 48 complete
[stream.hls][debug] Adding segment 70 to queue
[stream.hls][debug] Download of segment 49 complete
[stream.hls][debug] Adding segment 71 to queue
[stream.hls][debug] Download of segment 50 complete
[stream.hls][debug] Adding segment 72 to queue
[stream.hls][debug] Download of segment 51 complete
[stream.hls][debug] Adding segment 73 to queue
[stream.hls][debug] Download of segment 52 complete
[stream.hls][debug] Adding segment 74 to queue
[stream.hls][debug] Download of segment 53 complete
[stream.hls][debug] Adding segment 75 to queue
[stream.hls][debug] Download of segment 54 complete
[stream.hls][debug] Adding segment 76 to queue
[stream.hls][debug] Download of segment 55 complete
[stream.hls][debug] Adding segment 77 to queue
[stream.hls][debug] Download of segment 56 complete
[stream.hls][debug] Adding segment 78 to queue
[stream.hls][debug] Download of segment 57 complete
[stream.hls][debug] Adding segment 79 to queue
[stream.hls][debug] Download of segment 58 complete
[stream.hls][debug] Adding segment 80 to queue
[stream.hls][debug] Download of segment 59 complete
[stream.hls][debug] Adding segment 81 to queue
[stream.hls][debug] Download of segment 60 complete
[stream.hls][debug] Adding segment 82 to queue
[stream.hls][debug] Download of segment 61 complete
[stream.hls][debug] Adding segment 83 to queue
[stream.hls][debug] Download of segment 62 complete
[stream.hls][debug] Adding segment 84 to queue
[stream.hls][debug] Download of segment 63 complete
[stream.hls][debug] Adding segment 85 to queue
[stream.hls][debug] Download of segment 64 complete
[stream.hls][debug] Adding segment 86 to queue
[stream.hls][debug] Download of segment 65 complete
[stream.hls][debug] Adding segment 87 to queue
[stream.hls][debug] Download of segment 66 complete
[stream.hls][debug] Adding segment 88 to queue
[stream.hls][debug] Download of segment 67 complete
[stream.hls][debug] Adding segment 89 to queue
[stream.hls][debug] Download of segment 68 complete
[stream.hls][debug] Adding segment 90 to queue
[stream.hls][debug] Download of segment 69 complete
[stream.hls][debug] Adding segment 91 to queue
[stream.hls][debug] Download of segment 70 complete
[stream.hls][debug] Adding segment 92 to queue
[stream.hls][debug] Download of segment 71 complete
[stream.hls][debug] Adding segment 93 to queue
[stream.hls][debug] Download of segment 72 complete
[stream.hls][debug] Adding segment 94 to queue
[stream.hls][debug] Download of segment 73 complete
[stream.hls][debug] Adding segment 95 to queue
[stream.hls][debug] Download of segment 74 complete
[stream.hls][debug] Adding segment 96 to queue
[stream.hls][debug] Download of segment 75 complete
[stream.hls][debug] Adding segment 97 to queue
[stream.hls][debug] Download of segment 76 complete
[stream.hls][debug] Adding segment 98 to queue
[stream.hls][debug] Download of segment 77 complete
[stream.hls][debug] Adding segment 99 to queue
[stream.hls][debug] Download of segment 78 complete
[stream.hls][debug] Adding segment 100 to queue
[stream.hls][debug] Download of segment 79 complete
[stream.hls][debug] Adding segment 101 to queue
[stream.hls][debug] Download of segment 80 complete
[stream.hls][debug] Adding segment 102 to queue
[stream.hls][debug] Download of segment 81 complete
[stream.hls][debug] Adding segment 103 to queue
[stream.hls][debug] Download of segment 82 complete
[stream.hls][debug] Adding segment 104 to queue
[stream.hls][debug] Download of segment 83 complete
[stream.hls][debug] Adding segment 105 to queue
[stream.hls][debug] Download of segment 84 complete
[stream.hls][debug] Adding segment 106 to queue
[stream.hls][debug] Download of segment 85 complete
[stream.hls][debug] Adding segment 107 to queue
[stream.hls][debug] Download of segment 86 complete
[stream.hls][debug] Adding segment 108 to queue
[stream.hls][debug] Download of segment 87 complete
[stream.hls][debug] Adding segment 109 to queue
[stream.hls][debug] Download of segment 88 complete
[stream.hls][debug] Adding segment 110 to queue
[stream.hls][debug] Download of segment 89 complete
[stream.hls][debug] Adding segment 111 to queue
[cli][info] HTTP connection closed
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.segmented][debug] Closing worker thread
[stream.segmented][debug] Closing writer thread
[stream.segmented][debug] Closing worker thread
[stream.hls][debug] Download of segment 4 complete
[stream.segmented][debug] Closing writer thread
[stream.hls][debug] Download of segment 90 complete
[stream.ffmpegmux][debug] Closed all the substreams
[cli][info] Stream ended
[stream.ffmpegmux][debug] Pipe copy complete: \\.\pipe\ffmpeg-2268-430
[stream.ffmpegmux][debug] Pipe copy complete: \\.\pipe\ffmpeg-2268-638
[cli][info] Closing currently open stream...
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.ffmpegmux][debug] Closed all the substreams
```
<!--
Logs are always required for a bug report, use `-l debug` [(help)](https://streamlink.github.io/cli.html#cmdoption-l) and avoid using `--stream-url` as that will suppress log output.
Make sure to **remove username and password**
You can upload your logs to https://gist.github.com/ or place your logs below.
-->
### Additional comments, screenshots, etc.
I do not hear the video
same as https://github.com/streamlink/streamlink/pull/1853#issuecomment-401041683
there streams are invalid
It seemed to work for me with `ffmpeg 4.0.1` and `mpv 0.28.2` - just takes a while to start. As @back-to said, their streams are a bit broken.
The direct URL works for me using ffplay or MPC-HC, no delay to start either, but using the dash stream, HLS-Multi stream i have issues on this website, command used :
`Streamlink --player "M:\FFMPEG\ffplay.exe" --stream-priority=dash https://www.atresplayer.com/antena3/series/el-secreto-de-puente-viejo/julieta-y-los-hermanos-ortega/03-07-18_5b3408497ed1a8c72cd472b5/ best`
M3u URL seems like i have issues too.
**Edit :** for ffplay i forgot to say that i have to use an older version of it as last ones are broken and send back an error message " WASAPI can't initialize audio client" , apparently reported few times according to google searches and the only solution if to go back to an older version , I'm using ffplay version N-82143-gbf14393, last ones are messed up, this said np with MPC-HC, only have the LAV splitter source Network setting set to 2000ms there.
**Edit again :**
For FFplay the trick explained here "set SDL_AUDIODRIVER=directsound" might work if you encounter the " WASAPI can't initialize audio clients error displayed on new versions :
https://forum.videohelp.com/threads/388189-ffplay-WASAPI-can-t-initialize-audio-client-error
The mpd, f4m and link atresplayer.com...... I can see and hear it without any problem, the only one that does not work properly is the m3u8, I see it without sound. | 2018-07-12T10:48:18 |
|
streamlink/streamlink | 1,927 | streamlink__streamlink-1927 | [
"1917"
] | 6bf654a291e2a792088384c7ba7c9dc9b2a14b1d | diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py
--- a/src/streamlink/stream/dash.py
+++ b/src/streamlink/stream/dash.py
@@ -11,6 +11,7 @@
from streamlink.stream.dash_manifest import MPD, sleeper, sleep_until, utc, freeze_timeline
from streamlink.stream.ffmpegmux import FFMPEGMuxer
from streamlink.stream.segmented import SegmentedStreamReader, SegmentedStreamWorker, SegmentedStreamWriter
+from streamlink.utils.l10n import Language
log = logging.getLogger(__name__)
@@ -196,6 +197,31 @@ def parse_manifest(cls, session, url, **args):
if not audio:
audio = [None]
+ locale = session.localization
+ locale_lang = locale.language
+ lang = None
+ available_languages = set()
+
+ # if the locale is explicitly set, prefer that language over others
+ for aud in audio:
+ if aud and aud.lang:
+ available_languages.add(aud.lang)
+ try:
+ if locale.explicit and aud.lang and Language.get(aud.lang) == locale_lang:
+ lang = aud.lang
+ except LookupError:
+ continue
+
+ if not lang:
+ # filter by the first language that appears
+ lang = audio[0] and audio[0].lang
+
+ log.debug("Available languages for DASH audio streams: {0} (using: {1})".format(", ".join(available_languages) or "NONE", lang or "n/a"))
+
+ # if the language is given by the stream, filter out other languages that do not match
+ if len(available_languages) > 1:
+ audio = list(filter(lambda a: a.lang is None or a.lang == lang, audio))
+
for vid, aud in itertools.product(video, audio):
stream = DASHStream(session, mpd, vid, aud, **args)
stream_name = []
| diff --git a/tests/streams/test_dash.py b/tests/streams/test_dash.py
--- a/tests/streams/test_dash.py
+++ b/tests/streams/test_dash.py
@@ -1,7 +1,4 @@
import unittest
-import unittest
-from streamlink.stream.dash import DASHStreamWorker
-from tests.mock import MagicMock, patch, ANY, Mock, call
from streamlink import PluginError
from streamlink.stream import *
@@ -41,8 +38,8 @@ def test_parse_manifest_audio_only(self, mpdClass):
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
- Mock(id=1, mimeType="audio/mp4", bandwidth=128.0),
- Mock(id=2, mimeType="audio/mp4", bandwidth=256.0)
+ Mock(id=1, mimeType="audio/mp4", bandwidth=128.0, lang='en'),
+ Mock(id=2, mimeType="audio/mp4", bandwidth=256.0, lang='en')
])
])
])
@@ -63,7 +60,7 @@ def test_parse_manifest_audio_single(self, mpdClass):
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
- Mock(id=3, mimeType="audio/aac", bandwidth=128.0)
+ Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en')
])
])
])
@@ -84,8 +81,8 @@ def test_parse_manifest_audio_multi(self, mpdClass):
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
- Mock(id=3, mimeType="audio/aac", bandwidth=128.0),
- Mock(id=4, mimeType="audio/aac", bandwidth=256.0)
+ Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'),
+ Mock(id=4, mimeType="audio/aac", bandwidth=256.0, lang='en')
])
])
])
@@ -98,6 +95,108 @@ def test_parse_manifest_audio_multi(self, mpdClass):
sorted(["720p+a128k", "1080p+a128k", "720p+a256k", "1080p+a256k"])
)
+ @patch('streamlink.stream.dash.MPD')
+ def test_parse_manifest_audio_multi_lang(self, mpdClass):
+ mpd = mpdClass.return_value = Mock(periods=[
+ Mock(adaptationSets=[
+ Mock(contentProtection=None,
+ representations=[
+ Mock(id=1, mimeType="video/mp4", height=720),
+ Mock(id=2, mimeType="video/mp4", height=1080),
+ Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'),
+ Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='es')
+ ])
+ ])
+ ])
+
+ streams = DASHStream.parse_manifest(self.session, self.test_url)
+ mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+
+ self.assertSequenceEqual(
+ sorted(list(streams.keys())),
+ sorted(["720p", "1080p"])
+ )
+
+ self.assertEqual(streams["720p"].audio_representation.lang, "en")
+ self.assertEqual(streams["1080p"].audio_representation.lang, "en")
+
+ @patch('streamlink.stream.dash.MPD')
+ def test_parse_manifest_audio_multi_lang_alpha3(self, mpdClass):
+ mpd = mpdClass.return_value = Mock(periods=[
+ Mock(adaptationSets=[
+ Mock(contentProtection=None,
+ representations=[
+ Mock(id=1, mimeType="video/mp4", height=720),
+ Mock(id=2, mimeType="video/mp4", height=1080),
+ Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='eng'),
+ Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='spa')
+ ])
+ ])
+ ])
+
+ streams = DASHStream.parse_manifest(self.session, self.test_url)
+ mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+
+ self.assertSequenceEqual(
+ sorted(list(streams.keys())),
+ sorted(["720p", "1080p"])
+ )
+
+ self.assertEqual(streams["720p"].audio_representation.lang, "eng")
+ self.assertEqual(streams["1080p"].audio_representation.lang, "eng")
+
+ @patch('streamlink.stream.dash.MPD')
+ def test_parse_manifest_audio_invalid_lang(self, mpdClass):
+ mpd = mpdClass.return_value = Mock(periods=[
+ Mock(adaptationSets=[
+ Mock(contentProtection=None,
+ representations=[
+ Mock(id=1, mimeType="video/mp4", height=720),
+ Mock(id=2, mimeType="video/mp4", height=1080),
+ Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en_no_voice'),
+ ])
+ ])
+ ])
+
+ streams = DASHStream.parse_manifest(self.session, self.test_url)
+ mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+
+ self.assertSequenceEqual(
+ sorted(list(streams.keys())),
+ sorted(["720p", "1080p"])
+ )
+
+ self.assertEqual(streams["720p"].audio_representation.lang, "en_no_voice")
+ self.assertEqual(streams["1080p"].audio_representation.lang, "en_no_voice")
+
+ @patch('streamlink.stream.dash.MPD')
+ def test_parse_manifest_audio_multi_lang_locale(self, mpdClass):
+ self.session.localization.language.alpha2 = "es"
+ self.session.localization.explicit = True
+
+ mpd = mpdClass.return_value = Mock(periods=[
+ Mock(adaptationSets=[
+ Mock(contentProtection=None,
+ representations=[
+ Mock(id=1, mimeType="video/mp4", height=720),
+ Mock(id=2, mimeType="video/mp4", height=1080),
+ Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'),
+ Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='es')
+ ])
+ ])
+ ])
+
+ streams = DASHStream.parse_manifest(self.session, self.test_url)
+ mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+
+ self.assertSequenceEqual(
+ sorted(list(streams.keys())),
+ sorted(["720p", "1080p"])
+ )
+
+ self.assertEqual(streams["720p"].audio_representation.lang, "es")
+ self.assertEqual(streams["1080p"].audio_representation.lang, "es")
+
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_drm(self, mpdClass):
mpd = mpdClass.return_value = Mock(periods=[Mock(adaptationSets=[Mock(contentProtection="DRM")])])
@@ -122,7 +221,7 @@ def test_stream_open_video_only(self, muxer, reader):
@patch('streamlink.stream.dash.DASHStreamReader')
@patch('streamlink.stream.dash.FFMPEGMuxer')
def test_stream_open_video_audio(self, muxer, reader):
- stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4"), Mock(id=2, mimeType="audio/mp3"))
+ stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4"), Mock(id=2, mimeType="audio/mp3", lang='en'))
open_reader = reader.return_value = Mock()
stream.open()
@@ -202,7 +301,7 @@ def test_static(self, sleep):
@patch("streamlink.stream.dash_manifest.time.sleep")
def test_duplicate_rep_id(self, sleep):
representation_vid = Mock(id=1, mimeType="video/mp4", height=720)
- representation_aud = Mock(id=1, mimeType="audio/aac")
+ representation_aud = Mock(id=1, mimeType="audio/aac", lang='en')
mpd = Mock(dynamic=False,
publishTime=1,
| Audio Spanish
I don't hear this video in Spanish, why?, Is there any way I can keep it from being heard in English?
```
https://www.atresplayer.com/antena3/series/el-cuento-de-la-criada/temporada-1/capitulo-6-el-lugar-de-la-mujer_5b364bee7ed1a8dd360b5b7b/
```
### Logs
```
"C:\Program Files (x86)\Streamlink\bin\streamlink.exe" h
ttps://www.atresplayer.com/antena3/series/el-cuento-de-la-criada/temporada-1/cap
itulo-6-el-lugar-de-la-mujer_5b364bee7ed1a8dd360b5b7b/ best --player ffplay -l d
ebug
[cli][debug] OS: Windows 7
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin atresplayer for URL https://www.atresplayer.co
m/antena3/series/el-cuento-de-la-criada/temporada-1/capitulo-6-el-lugar-de-la-mu
jer_5b364bee7ed1a8dd360b5b7b/
[plugin.atresplayer][debug] API URL: https://api.atresplayer.com/client/v1/playe
r/episode/5b364bee7ed1a8dd360b5b7b
[plugin.atresplayer][debug] Stream source: https://geodeswowa3player.akamaized.n
et/vcg/_definst_/assets4/2018/06/29/7875368D-BF45-4012-9EBC-C4F78984B672/hls.smi
l/playlist.m3u8?pulse=assets4%2F2018%2F06%2F29%2F7875368D-BF45-4012-9EBC-C4F7898
4B672%2F%7C1531195580%7Cb6e79f7291966a25070a79138cd19cb9 (application/vnd.apple.
mpegurl)
[stream.hls][debug] Using external audio tracks for stream 1080p (language=es, n
ame=Spanish)
[stream.hls][debug] Using external audio tracks for stream 720p (language=es, na
me=Spanish)
[stream.hls][debug] Using external audio tracks for stream 480p (language=es, na
me=Spanish)
[stream.hls][debug] Using external audio tracks for stream 360p (language=es, na
me=Spanish)
[stream.hls][debug] Using external audio tracks for stream 240p (language=es, na
me=Spanish)
[plugin.atresplayer][debug] Stream source: https://geodeswowa3player.akamaized.n
et/vcg/_definst_/assets4/2018/06/29/7875368D-BF45-4012-9EBC-C4F78984B672/dash.sm
il/manifest_mvlist.mpd (application/dash+xml)
[cli][info] Available streams: 240p (worst), 240p+a128k, 360p, 360p+a128k, 480p,
480p+a128k, 720p, 720p+a128k, 1080p, 1080p+a128k (best)
[cli][info] Starting player: ffplay
....................
....................
....................
```
| You are using the `dash stream (.mpd)`, I think streamlink does not support audio channels there.
You could use the `hls stream (.m3u8)`, it should work there
`streamlink URL 1080p`
but you might encounter Audio Issues, because there streams are a bit broken
https://github.com/streamlink/streamlink/issues/1898
Does not work with m3u8
@Toni195 try adding the `--locale es_ES` option.
@beardypig
It doesn't work.
MPD: English.
M3U8: Without audio.
Link atresplayer.com: English.
F4M: Spanish.
> M3U8
```
[stream.hls][debug] Download of segment 17 complete
[stream.hls][debug] Adding segment 39 to queue
[stream.hls][debug] Download of segment 18 complete
[stream.hls][debug] Adding segment 40 to queue
[stream.hls][debug] Cutting off 12 bytes of garbage before decrypting
Exception in thread Thread-HLSStreamWriter:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "src/streamlink/stream/segmented.py", line 167, in run
self.write(segment, result)
File "src/streamlink/stream/hls.py", line 135, in write
self.reader.buffer.write(pkcs7_decode(decrypted_chunk))
File "src/streamlink/stream/hls.py", line 31, in pkcs7_decode
raise StreamError("Input is not padded or padding is corrupt, got padding size of {0}".format(val))
streamlink.exceptions.StreamError: Input is not padded or padding is corrupt, got padding size of 188
```
that may be because of my geographical location,
could you post a log of your Issue with the m3u8 stream.
but they are probably not fixable https://github.com/streamlink/streamlink/issues/1898
---
> MPD
it is english because the first stream gets overwritten by the 2nd with the same name.
https://github.com/streamlink/streamlink/blob/577617a2383cc75c6c94160b36aeccd7bd3b4bcf/src/streamlink/stream/dash.py#L207
this could be easily added, there are some solutions
- **ugly** , `_alt` for the 2nd stream
- **better**, `--locale` only show the first stream or your selected language
---
you could also use the mpd url directly in VLC, it works there.
We should consider the locale when picking the audio stream :)
@Toni195 can you try the `m3u8` version and add the `--ffmpeg-verbose` option? | 2018-07-12T11:27:40 |
streamlink/streamlink | 1,935 | streamlink__streamlink-1935 | [
"1932"
] | 33f677b6fe43582d1789884253ccde96705376eb | diff --git a/src/streamlink/plugins/picarto.py b/src/streamlink/plugins/picarto.py
--- a/src/streamlink/plugins/picarto.py
+++ b/src/streamlink/plugins/picarto.py
@@ -4,8 +4,10 @@
import json
from streamlink.plugin import Plugin
+from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.stream import RTMPStream
+from streamlink.utils import parse_json
class Picarto(Plugin):
@@ -15,13 +17,29 @@ class Picarto(Plugin):
RTMP_PLAYPATH = "golive+{channel}?token={token}"
HLS_URL = "https://{server}/hls/{channel}/index.m3u8?token={token}"
+
# Regex for all usable URLs
_url_re = re.compile(r"""
https?://(?:\w+\.)?picarto\.tv/(?:videopopout/)?([^&?/]+)
""", re.VERBOSE)
# Regex for VOD extraction
- _vod_re = re.compile(r'''vod: "(https?://[\S]+?/index.m3u8)",''')
+ _vod_re = re.compile(r'''(?<=#vod-player", )(\{.*?\})''')
+
+ data_schema = validate.Schema(
+ validate.transform(_vod_re.search),
+ validate.any(
+ None,
+ validate.all(
+ validate.get(0),
+ validate.transform(parse_json),
+ {
+ "vod": validate.url(),
+ }
+ )
+ )
+ )
+
@classmethod
def can_handle_url(cls, url):
@@ -52,9 +70,10 @@ def _create_flash_stream(self, server, channel, token):
return RTMPStream(self.session, params=params)
def _get_vod_stream(self, page):
- m = self._vod_re.search(page.text)
- if m:
- return HLSStream.parse_variant_playlist(self.session, m.group(1))
+ data = self.data_schema.validate(page.text)
+
+ if data:
+ return HLSStream.parse_variant_playlist(self.session, data["vod"])
def _get_streams(self):
url_channel_name = self._url_re.match(self.url).group(1)
| Can't Download Picarto Video
## Bug Report
- [X ] I have read the contribution guidelines.
### Description
Picarto.tv plugin doesn't seem to download any recorded streams anymore
### Expected / Actual behavior
Expected it to download video, didn't
### Reproduction steps / Explicit stream URLs to test
1. streamlink -o Amarynceus.flv https://picarto.tv/videopopout/Amarynceus_2018.07.04.22.55.48.flv
### Logs
```
streamlink -o Amarynceus.flv https://picarto.tv/videopopout/Amarynceus_2018.07.04.22.55.48.flv -l debug
[cli][debug] OS: Linux-4.15.0-24-generic-x86_64-with-Ubuntu-18.04-bionic
[cli][debug] Python: 2.7.15rc1
[cli][debug] Streamlink: 0.14.2+24.g6bf654a2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin picarto for URL https://picarto.tv/videopopout/Amarynceus_2018.07.04.22.55.48.flv
[plugin.picarto][debug] Possible VOD stream...
[plugin.picarto][warning] Probably a VOD stream but no VOD found?
[plugin.picarto][error] The channel Amarynceus_2018.07.04.22.55.48.flv does not exist
error: No playable streams found on this URL: https://picarto.tv/videopopout/Amarynceus_2018.07.04.22.55.48.flv
```
| 2018-07-13T22:34:22 |
||
streamlink/streamlink | 1,941 | streamlink__streamlink-1941 | [
"1938"
] | cac78e43e0f1ab632cb6796a758c10d876e36ed5 | diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py
--- a/src/streamlink/stream/hls.py
+++ b/src/streamlink/stream/hls.py
@@ -295,7 +295,7 @@ class MuxedHLSStream(MuxedStream):
def __init__(self, session, video, audio, force_restart=False, ffmpeg_options=None, **args):
tracks = [video]
- maps = ["0:v"]
+ maps = ["0:v?", "0:a?"]
if audio:
if isinstance(audio, list):
tracks.extend(audio)
| hls-audio-select option preclude downloading of default audio
This does not happen in streamlink 0.14.2, but issue is present in git version of streamlink.
I am downloading mlb games using streamlink. There are usually 3 audio streams. One default called "English" and two additional ones called "English radio" and "Natural sound". Without using hls-audio-select it downloads video with default stream as expected. If I add --hls-audio-select "English Radio", it does not download default stream. Using --hls-audio-select "*" downloads English Radio and Natural Sound audio. Default audio is still not present.
| probably related to https://github.com/streamlink/streamlink/pull/1926
the default `LANGUAGE="en",NAME="English"` does not have an `URI`
and is most likely coupled with the video URI
I think the issue is that streamlink only accepts the video URI as a video instead of video/audio in this case
```
#EXTM3U
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aac",LANGUAGE="en",NAME="English",AUTOSELECT=YES,DEFAULT=YES
#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID="cc",LANGUAGE="en",NAME="English",INSTREAM-ID="CC1"
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aac",NAME="Natural Sound",LANGUAGE="zxx",AUTOSELECT=NO,URI="ballpark_48K/48_complete-trimmed.m3u8"
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aac",NAME="English Radio",LANGUAGE="en",AUTOSELECT=NO,URI="eng_48K/48_complete-trimmed.m3u8"
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aac",NAME="Radio Española",LANGUAGE="es",AUTOSELECT=NO,URI="spa_48K/48_complete-trimmed.m3u8"
#EXT-X-STREAM-INF:BANDWIDTH=2120000,RESOLUTION=896x504,FRAME-RATE=29.97,CODECS="mp4a.40.2,avc1.4d001f",CLOSED-CAPTIONS="cc",AUDIO="aac"
1800K/1800_complete-trimmed.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=620000,RESOLUTION=400x224,FRAME-RATE=29.97,CODECS="mp4a.40.2,avc1.4d001f",CLOSED-CAPTIONS="cc",AUDIO="aac"
514K/514_complete-trimmed.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=960000,RESOLUTION=512x288,FRAME-RATE=29.97,CODECS="mp4a.40.2,avc1.4d001f",CLOSED-CAPTIONS="cc",AUDIO="aac"
800K/800_complete-trimmed.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1400000,RESOLUTION=640x360,FRAME-RATE=29.97,CODECS="mp4a.40.2,avc1.4d001f",CLOSED-CAPTIONS="cc",AUDIO="aac"
1200K/1200_complete-trimmed.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2950000,RESOLUTION=960x540,FRAME-RATE=29.97,CODECS="mp4a.40.2,avc1.4d001f",CLOSED-CAPTIONS="cc",AUDIO="aac"
2500K/2500_complete-trimmed.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=4160000,RESOLUTION=1280x720,FRAME-RATE=29.97,CODECS="mp4a.40.2,avc1.640028",CLOSED-CAPTIONS="cc",AUDIO="aac"
3500K/3500_complete-trimmed.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=6600000,RESOLUTION=1280x720,FRAME-RATE=59.94,CODECS="mp4a.40.2,avc1.640028",CLOSED-CAPTIONS="cc",AUDIO="aac"
5600K/5600_complete-trimmed.m3u8
#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=62000,RESOLUTION=400x224,CODECS="avc1.4d001f,mp4a.40.2",URI="514K/514_complete_iframe-trimmed.m3u8"
#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=295000,RESOLUTION=960x540,CODECS="avc1.4d001f,mp4a.40.2",URI="2500K/2500_complete_iframe-trimmed.m3u8"
``` | 2018-07-17T09:40:31 |
|
streamlink/streamlink | 1,968 | streamlink__streamlink-1968 | [
"1960"
] | 5d1f4521e0cb0636d7b075454e259eb2fbfca6c5 | diff --git a/src/streamlink/plugins/openrectv.py b/src/streamlink/plugins/openrectv.py
--- a/src/streamlink/plugins/openrectv.py
+++ b/src/streamlink/plugins/openrectv.py
@@ -1,61 +1,154 @@
+import logging
import re
-from streamlink.plugin import Plugin
+from streamlink.plugin import Plugin, PluginArgument, PluginArguments
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.utils import parse_json
-_url_re = re.compile(r"https?://(?:www\.)?openrec.tv/(live|movie)/")
-_playlist_url_re = re.compile(r"data-(source)?file=\"(?P<url>[^\"]+)\"")
-_movie_data_re = re.compile(r'''<script type="application/ld\+json">(.*?)</script>''', re.DOTALL | re.M)
-_live_schema = validate.Schema(
- validate.transform(_playlist_url_re.findall),
- [
- validate.union({
- "isSource": validate.all(validate.get(0), validate.transform(lambda s: s == "source")),
- "url": validate.all(validate.get(1), validate.url(scheme="http",
- path=validate.endswith(".m3u8")))
- })
- ]
-)
-_movie_schema = validate.Schema(
- validate.transform(_movie_data_re.search),
- validate.any(
- None,
- validate.all(
- validate.get(1),
- validate.transform(parse_json),
- validate.get("contentUrl")
- )
- )
-)
+log = logging.getLogger(__name__)
class OPENRECtv(Plugin):
+ _url_re = re.compile(r"https?://(?:www\.)?openrec.tv/(?:live|movie)/(?P<id>[^/]+)")
+ _stores_re = re.compile(r"window.stores\s*=\s*({.*?});", re.DOTALL | re.MULTILINE)
+ _config_re = re.compile(r"window.sharedConfig\s*=\s*({.*?});", re.DOTALL | re.MULTILINE)
+
+ api_url = "https://apiv5.openrec.tv/api/v5/movies/{id}/detail"
+ login_url = "https://www.openrec.tv/viewapp/v4/mobile/user/login"
+
+ _config_schema = validate.Schema({
+ "urls": {
+ "apiv5Authorized": validate.url()
+ }
+ })
+ _stores_schema = validate.Schema({
+ "moviePageStore": {
+ "movieStore": {
+ "id": validate.text,
+ "title": validate.text,
+ "media": {
+ "url": validate.any(None, '', validate.url())
+ }
+ }
+ }
+ }, validate.get("moviePageStore"), validate.get("movieStore"))
+
+ _detail_schema = validate.Schema({
+ validate.optional("error_message"): validate.text,
+ "status": int,
+ validate.optional("data"): {
+ "type": validate.text,
+ "items": [{
+ "media": {
+ "url": validate.any(None, validate.url()),
+ "url_dvr": validate.any(None, validate.url())
+ }
+ }]
+ }
+ })
+
+ _login_schema = validate.Schema({
+ validate.optional("error_message"): validate.text,
+ "status": int,
+ validate.optional("data"): object
+ })
+
+ arguments = PluginArguments(
+ PluginArgument(
+ "email",
+ requires=["password"],
+ metavar="EMAIL",
+ help="""
+ The email associated with your openrectv account,
+ required to access any openrectv stream.
+ """),
+ PluginArgument(
+ "password",
+ sensitive=True,
+ metavar="PASSWORD",
+ help="""
+ An openrectv account password to use with --openrectv-email.
+ """)
+ )
+
+ def __init__(self, url):
+ super(OPENRECtv, self).__init__(url)
+ self._pdata = None
+ self._pres = None
+ self._pconfig = None
+
@classmethod
def can_handle_url(cls, url):
- return _url_re.match(url) is not None
+ return cls._url_re.match(url) is not None
- @classmethod
- def stream_weight(cls, stream):
- if stream == "source":
- return 1080 + 1, "openrectv"
- return Plugin.stream_weight(stream)
+ def login(self, email, password):
+ res = self.session.http.post(self.login_url, data={"mail": email, "password": password})
+ data = self.session.http.json(res, self._login_schema)
+ if data["status"] == 0:
+ log.debug("Logged in as {0}".format(data["data"]["user_name"]))
+ else:
+ log.error("Failed to login: {0}".format(data["error_message"]))
+ return data["status"] == 0
+
+ def _get_page(self):
+ if not self._pres:
+ self._pres = self.session.http.get(self.url)
+ return self._pres
+
+ def _get_movie_data(self):
+ pres = self._get_page()
+ match = self._stores_re.search(pres.text)
+ if match:
+ self._pdata = parse_json(match.group(1), schema=self._stores_schema)
+
+ return self._pdata
+
+ def _get_page_config(self):
+ pres = self._get_page()
+ match = self._config_re.search(pres.text)
+ if match:
+ self._pconfig = parse_json(match.group(1))
+
+ return self._pconfig
+
+ def _get_details(self, id):
+ config = self._get_page_config()
+ api_url = config["urls"]["apiv5Authorized"]
+ url = "{base}/movies/{id}/detail".format(base=api_url, id=id)
+ res = self.session.http.get(url, headers={
+ "access-token": self.session.http.cookies.get("access_token"),
+ "uuid": self.session.http.cookies.get("uuid")
+ })
+ data = self.session.http.json(res, schema=self._detail_schema)
+
+ if data["status"] == 0:
+ log.debug("Got valid detail response")
+ return data["data"]
+ else:
+ log.error("Failed to get video stream: {0}".format(data["error_message"]))
+
+ def get_title(self):
+ mdata = self._get_movie_data()
+ if mdata:
+ return mdata["title"]
def _get_streams(self):
- stype = _url_re.match(self.url).group(1)
- if stype.lower() == "live":
- self.logger.debug("Searching the page for live stream URLs")
- playlists = self.session.http.get(self.url, schema=_live_schema)
- for playlist in playlists:
- for q, s in HLSStream.parse_variant_playlist(self.session, playlist["url"]).items():
- yield "source" if playlist["isSource"] else q, s
- elif stype.lower() == "movie":
- self.logger.debug("Searching the page for VOD stream URLs")
- playlist = self.session.http.get(self.url, schema=_movie_schema)
- if playlist:
- for s in HLSStream.parse_variant_playlist(self.session, playlist).items():
+ mdata = self._get_movie_data()
+ if mdata:
+ log.debug("Found video: {0} ({1})".format(mdata["title"], mdata["id"]))
+ if mdata["media"]["url"]:
+ for s in HLSStream.parse_variant_playlist(self.session, mdata["media"]["url"]).items():
yield s
+ elif self.get_option("email") and self.get_option("password"):
+ if self.login(self.get_option("email"), self.get_option("password")):
+ details = self._get_details(mdata["id"])
+ if details:
+ for item in details["items"]:
+ for s in HLSStream.parse_variant_playlist(self.session, item["media"]["url"]).items():
+ yield s
+ else:
+ log.error("You must login to access this stream")
__plugin__ = OPENRECtv
| OPENREC plugin broken
The following command no longer works:
streamlink openrec.tv/live/ddsEf14ETTVFl <-- random url
Even though the stream is live it will say "no playable streams found".
It seems like openrec has changed something. Could someone please take a look?
Thank you
| @jstrat231 This does not conform to the Plugin issue template
> Logs are always required for a plugin issue, use `-l debug` [(help)](https://streamlink.github.io/cli.html#cmdoption-l) and avoid using `--stream-url` as that will suppress log output.
What's that in scrub terms :D? I have no idea how to code any of this stuff
I'm not quite sure what these -1 debug options mean.
If I was to modify the link mention in the OP how would I do it with your recommendation?
`-l debug` will not give you any useful information. Openrec recently updated their site and that must've broken the plugin. There are no recent commits or pull requests addressing this issue.
@happapa `-l debug` will give useful information to us, that is why we ask for it. For example version of streamlink, operating system, various library versions, and perhaps some information about the plugin error.
@jstrat231 run streamlink again but add `-l debug` to the command: eg. `streamlink -l debug http://... best`.
@beardypig Seem to be getting the following error:
https://imgur.com/a/dgF7cX2
That streamer is currently live but no whatever what I type, it keeps saying "no playable streams found"/
OpenRec recently made big changes to their website and player so I wouldn't be surprised if it somehow broke the previous plugin. Everything was working fine before the website changes.
I have the latest version of streamlink installed. Windows 7 Ultimate 64 bit.
@jstrat231
It's not `-1` (one), it's `-l` (lowercase L), the shorthand parameter for `--loglevel`
https://streamlink.github.io/cli.html#cmdoption-l
And don't use images to show log output.
My bad.
Just tried this livestream of PUBG with the -l and got the same no playable streams found:
https://www.openrec.tv/live/Ved7VSqUVVC
Doesn't seem to provide any additional info. Just says "searching the page for live stream URLS" followed by no playable streams found.
@jstrat231 it may not look like it provides any useful information, but it does for us. So please include the logs :)
```
[root@localhost ~]$ streamlink -l debug https://www.openrec.tv/live/4jbzAvK5Or8 best
[cli][info] Found matching plugin openrectv for URL https://www.openrec.tv/live/4jbzAvK5Or8
[plugin.openrectv][debug] Searching the page for live stream URLs
error: No playable streams found on this URL: https://www.openrec.tv/live/4jbzAvK5Or8
```
I think they have just updated the website such that you need to login before you can watch the videos. There is no hlsvariant or m3u8 url in the page source.
@ydixon you’re using a pretty old version of streamlink, you should update it. However, the last change was February 2017 so I imagine it’s stillness broken. Always best to use the latest version though.
```
[root@localhost ~]$ streamlink -l debug https://www.openrec.tv/live/4jbzAvK5Or8 best
[cli][debug] OS: Linux-4.14.18-300.fc27.x86_64-x86_64-with-fedora-27-Twenty_Seven
[cli][debug] Python: 2.7.14
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin openrectv for URL https://www.openrec.tv/live/4jbzAvK5Or8
[plugin.openrectv][debug] Searching the page for live stream URLs
error: No playable streams found on this URL: https://www.openrec.tv/live/4jbzAvK5Or8
```
My apologies, I was using my own script for this work before it failed. When it failed, i stumbled upon this repo, looking for solution. Anyways, I just updated streamlink, this is the log.
@ydixon thanks. I’ll take a look tomorrow and let you know. | 2018-07-30T09:46:17 |
|
streamlink/streamlink | 1,978 | streamlink__streamlink-1978 | [
"1977"
] | a7b6b0db1cad200288b163628b380f0ccc947f07 | diff --git a/src/streamlink/plugins/steam.py b/src/streamlink/plugins/steam.py
--- a/src/streamlink/plugins/steam.py
+++ b/src/streamlink/plugins/steam.py
@@ -69,7 +69,7 @@ class SteamBroadcastPlugin(Plugin):
help="""
A Steam account password to use with --steam-email.
"""
- ))
+ ))
def __init__(self, url):
super(SteamBroadcastPlugin, self).__init__(url)
@@ -175,11 +175,13 @@ def login(self, email, password):
log.info("Attempting to login to Steam as {}".format(email))
return self.dologin(email, password)
- def _get_broadcast_stream(self, steamid, viewertoken=0):
+ def _get_broadcast_stream(self, steamid, viewertoken=0, sessionid=None):
+ log.debug("Getting broadcast stream: sessionid={0}".format(sessionid))
res = self.session.http.get(self._get_broadcast_url,
- params=dict(broadcastid=0,
- steamid=steamid,
- viewertoken=viewertoken))
+ params=dict(broadcastid=0,
+ steamid=steamid,
+ viewertoken=viewertoken,
+ sessionid=sessionid))
return self.session.http.json(res, schema=self._broadcast_schema)
def _get_streams(self):
@@ -191,9 +193,12 @@ def _get_streams(self):
# extract the steam ID from the URL
steamid = self._url_re.match(self.url).group(1)
+ res = self.session.http.get(self.url) # get the page to set some cookies
+ sessionid = res.cookies.get('sessionid')
while streamdata is None or streamdata[u"success"] in ("waiting", "waiting_for_start"):
- streamdata = self._get_broadcast_stream(steamid)
+ streamdata = self._get_broadcast_stream(steamid,
+ sessionid=sessionid)
if streamdata[u"success"] == "ready":
return DASHStream.parse_manifest(self.session, streamdata["url"])
| Issue with Steam Broadcasting plugin
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
<!-- Explain the plugin issue as thoroughly as you can. -->
Whenever I try to open a public stream from the list of "https://steamcommunity.com/?subsection=broadcasts" I get an error and stream doesn't open
### Reproduction steps / Explicit stream URLs to test
Example URL:
* https://steamcommunity.com/broadcast/watch/76561198046964848
* https://steamcommunity.com/broadcast/watch/76561198835282120
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. Open CMD/Powershell
2. Type streamlink linktostream best
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
PS C:\WINDOWS\system32> streamlink steamcommunity.com/broadcast/watch/76561198046964848 best --loglevel debug
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin steam for URL steamcommunity.com/broadcast/watch/76561198046964848
error: Unable to open URL: https://steamcommunity.com/broadcast/getbroadcastmpd/ (403 Client Error: Forbidden for url: https://steamcommunity.com/broadcast/getbroadcastmpd/?viewertoken=0&steamid=76561198046964848&broadcastid=0)
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-08-01T23:35:58 |
||
streamlink/streamlink | 1,995 | streamlink__streamlink-1995 | [
"1984"
] | ed40b45ddb02c361ec24117a06b99b5ab0817a88 | diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py
--- a/src/streamlink/stream/dash.py
+++ b/src/streamlink/stream/dash.py
@@ -227,7 +227,7 @@ def parse_manifest(cls, session, url, **args):
stream_name = []
if vid:
- stream_name.append("{:0.0f}{}".format(vid.height or vid.bandwidth, "p" if vid.height else "k"))
+ stream_name.append("{:0.0f}{}".format(vid.height or vid.bandwidth_rounded, "p" if vid.height else "k"))
if audio and len(audio) > 1:
stream_name.append("a{:0.0f}k".format(aud.bandwidth))
ret['+'.join(stream_name)] = stream
diff --git a/src/streamlink/stream/dash_manifest.py b/src/streamlink/stream/dash_manifest.py
--- a/src/streamlink/stream/dash_manifest.py
+++ b/src/streamlink/stream/dash_manifest.py
@@ -8,6 +8,8 @@
from collections import defaultdict, namedtuple
from itertools import repeat, count
+
+import math
from isodate import parse_datetime, parse_duration, Duration
from contextlib import contextmanager
from streamlink.compat import urlparse, urljoin, urlunparse, izip, urlsplit, urlunsplit
@@ -580,6 +582,10 @@ def __init__(self, node, root=None, parent=None, *args, **kwargs):
self.segmentList = self.children(SegmentList)
self.segmentTemplate = self.only_child(SegmentTemplate)
+ @property
+ def bandwidth_rounded(self):
+ return round(self.bandwidth, 1 - int(math.log10(self.bandwidth)))
+
def segments(self, **kwargs):
"""
Segments are yielded when they are available
| diff --git a/tests/resources/dash/test_9.mpd b/tests/resources/dash/test_9.mpd
new file mode 100644
--- /dev/null
+++ b/tests/resources/dash/test_9.mpd
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns="urn:mpeg:dash:schema:mpd:2011"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd"
+ profiles="urn:mpeg:dash:profile:isoff-live:2011"
+ type="dynamic"
+ minimumUpdatePeriod="PT3.502S"
+ publishTime="2018-08-06T10:14:52Z"
+ availabilityStartTime="2018-07-19T09:10:45Z"
+ timeShiftBufferDepth="PT50.0S"
+ suggestedPresentationDelay="PT20.0S"
+ minBufferTime="PT6.0S">
+<ProgramInformation>
+ <Title>ltv9</Title>
+</ProgramInformation>
+<Location>https://595ac1e01d44e.streamlock.net/ltv9/ltv9/manifest_TOKEN.mpd</Location>
+<Period id="0" start="PT0.0S">
+ <AdaptationSet id="0" group="1" mimeType="video/mp4" width="848" height="480" par="16:9" frameRate="25" segmentAlignment="true" startWithSAP="1" subsegmentAlignment="true" subsegmentStartsWithSAP="1">
+ <SegmentTemplate timescale="90000" media="chunk_ctvideo_cfm4s_rid$RepresentationID$_cs$Time$_TOKEN_mpd.m4s" initialization="chunk_ctvideo_cfm4s_rid$RepresentationID$_cinit_TOKEN_mpd.m4s">
+ <SegmentTimeline>
+ <S t="140309188560" d="900000"/>
+ <S d="900000"/>
+ <S d="900000"/>
+ <S d="900000"/>
+ <S d="900000"/>
+ </SegmentTimeline>
+ </SegmentTemplate>
+ <Representation id="p0va0br2467130" codecs="avc1.42c01e" sar="1:1" bandwidth="2467130" />
+ </AdaptationSet>
+ <AdaptationSet id="1" group="2" mimeType="audio/mp4" lang="eng" segmentAlignment="true" startWithSAP="1" subsegmentAlignment="true" subsegmentStartsWithSAP="1">
+ <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
+ <SegmentTemplate timescale="48000" media="chunk_ctaudio_cfm4s_rid$RepresentationID$_cs$Time$_TOKEN_mpd.m4s" initialization="chunk_ctaudio_cfm4s_rid$RepresentationID$_cinit_TOKEN_mpd.m4s">
+ <SegmentTimeline>
+ <S t="74831568240" d="479232"/>
+ <S d="480240"/>
+ <S d="480288"/>
+ <S d="480240"/>
+ <S d="479232"/>
+ </SegmentTimeline>
+ </SegmentTemplate>
+ <Representation id="p0aa0br61417" codecs="mp4a.40.2" audioSamplingRate="48000" bandwidth="61417">
+ </Representation>
+ </AdaptationSet>
+</Period>
+<UTCTiming schemeIdUri="urn:mpeg:dash:utc:direct:2014" value="2018-08-06T10:14:52Z"/>
+</MPD>
diff --git a/tests/streams/test_dash.py b/tests/streams/test_dash.py
--- a/tests/streams/test_dash.py
+++ b/tests/streams/test_dash.py
@@ -3,7 +3,9 @@
from streamlink import PluginError
from streamlink.stream import *
from streamlink.stream.dash import DASHStreamWorker
+from streamlink.stream.dash_manifest import MPD
from tests.mock import MagicMock, patch, ANY, Mock, call
+from tests.resources import xml
class TestDASHStream(unittest.TestCase):
@@ -233,6 +235,16 @@ def test_stream_open_video_audio(self, muxer, reader):
self.assertSequenceEqual(muxer.mock_calls, [call(self.session, open_reader, open_reader, copyts=True),
call().open()])
+ @patch('streamlink.stream.dash.MPD')
+ def test_segments_number_time(self, mpdClass):
+ with xml("dash/test_9.mpd") as mpd_xml:
+ mpdClass.return_value = MPD(mpd_xml, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+
+ streams = DASHStream.parse_manifest(self.session, self.test_url)
+ mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+
+ self.assertSequenceEqual(list(streams.keys()), ['2500k'])
+
class TestDASHStreamWorker(unittest.TestCase):
@patch("streamlink.stream.dash_manifest.time.sleep")
@@ -322,5 +334,7 @@ def test_duplicate_rep_id(self, sleep):
self.assertEqual(representation_aud, DASHStreamWorker.get_representation(mpd, 1, "audio/aac"))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/streams/test_dash_parser.py b/tests/streams/test_dash_parser.py
--- a/tests/streams/test_dash_parser.py
+++ b/tests/streams/test_dash_parser.py
@@ -7,8 +7,9 @@
from freezegun import freeze_time
from freezegun.api import FakeDatetime
+from tests.mock import MagicMock, Mock
-from streamlink.stream.dash_manifest import MPD, MPDParsers, MPDParsingError, utc
+from streamlink.stream.dash_manifest import MPD, MPDParsers, MPDParsingError, utc, Representation
from tests.resources import xml
@@ -220,3 +221,20 @@ def test_tsegment_t_is_none_1895(self):
'http://test.se/video-time=8000-2799000-0.m4s?z32=CENSORED_SESSION',
])
+ def test_bitrate_rounded(self):
+ def mock_rep(bandwidth):
+ node = Mock(
+ tag="Representation",
+ attrib={
+ "id": "test",
+ "bandwidth": bandwidth,
+ "mimeType": "video/mp4"
+ }
+ )
+ node.findall.return_value = []
+ return Representation(node)
+
+ self.assertEqual(mock_rep(1.2*1000.0).bandwidth_rounded, 1.2)
+ self.assertEqual(mock_rep(45.6*1000.0).bandwidth_rounded, 46.0)
+ self.assertEqual(mock_rep(134.0*1000.0).bandwidth_rounded, 130.0)
+ self.assertEqual(mock_rep(1324.0*1000.0).bandwidth_rounded, 1300.0)
| stream name is inconsistent for dash dynamic playlists
## Bug / Feature Report
- [x] This is a bug report and I have read the contribution guidelines.
### Description
A dash dynamic playlist has **different bandwidths** all the time,
which makes the stream name inconsistent.
If you want to switch to the dash stream you can't guess the stream name.
`streamlink URL 2500k,2400k` would be easier than `2500k,2499k,2498k ...`
It is not a big issue for streams with only one stream,
but if you want the lower stream there is a big chance that you won't guess the right stream name.
### Expected / Actual behavior
**V**ideo and **A**udio bandwidth from `self.bandwidth`
https://github.com/streamlink/streamlink/blob/71a327ae4c053ddda0f842c3f0e38ddac3e31c4f/src/streamlink/stream/dash_manifest.py#L559
1. Actual behavior
```
V 2514.252
A 61.436
[cli][info] Available streams: 2514k
```
1. **Expected**
```
V 2500.0
A 60.0
[cli][info] Available streams: 2500k
```
---
2. Actual behavior
```
V 2433.165
A 61.439
[cli][info] Available streams: 2433k
```
2. **Expected**
```
V 2400.0
A 60.0
[cli][info] Available streams: 2400k
```
### Reproduction steps / Explicit stream URLs to test
1. DASHStream from https://ltv.lsm.lv/lv/tieshraide/visiemltv.lv/live.1480/
### Additional comments, screenshots, etc.
**The bandwidth should be rounded,**
here is an **example** of how it could be rounded,
but it is a bit long and maybe it could be shortened.
```py
x = self.bandwidth
if x >= 1000:
x = round(x, -2)
elif 1000 > x <= 100:
x = round(x, -1)
else:
x = round(x)
```
it could be added to
https://github.com/streamlink/streamlink/blob/71a327ae4c053ddda0f842c3f0e38ddac3e31c4f/src/streamlink/stream/dash_manifest.py#L559
or
https://github.com/streamlink/streamlink/blob/71a327ae4c053ddda0f842c3f0e38ddac3e31c4f/src/streamlink/stream/dash.py#L204-L206
| I'll added a rounded bandwidth attribute or something. | 2018-08-06T10:58:37 |
streamlink/streamlink | 2,010 | streamlink__streamlink-2010 | [
"1683"
] | 2c9cfe84084eaec51a1dcd37a6bf0280bcdd195e | diff --git a/src/streamlink/plugins/schoolism.py b/src/streamlink/plugins/schoolism.py
--- a/src/streamlink/plugins/schoolism.py
+++ b/src/streamlink/plugins/schoolism.py
@@ -1,20 +1,23 @@
from __future__ import print_function
+import logging
import re
from functools import partial
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import useragents
from streamlink.plugin.api import validate
-from streamlink.stream import HLSStream
+from streamlink.stream import HLSStream, HTTPStream
from streamlink.utils import parse_json
+log = logging.getLogger(__name__)
+
class Schoolism(Plugin):
- url_re = re.compile(r"https?://(?:www\.)?schoolism\.com/watchLesson.php")
+ url_re = re.compile(r"https?://(?:www\.)?schoolism\.com/(viewAssignment|watchLesson).php")
login_url = "https://www.schoolism.com/index.php"
key_time_url = "https://www.schoolism.com/video-html/key-time.php"
- playlist_re = re.compile(r"var allVideos=(\[\{.*\}]);", re.DOTALL)
+ playlist_re = re.compile(r"var allVideos\s*=\s*(\[\{.*\}]);", re.DOTALL)
js_to_json = partial(re.compile(r'(?!<")(\w+):(?!/)').sub, r'"\1":')
playlist_schema = validate.Schema(
validate.transform(playlist_re.search),
@@ -27,13 +30,13 @@ class Schoolism(Plugin):
validate.transform(parse_json),
[{
"sources": validate.all([{
- "playlistTitle": validate.text,
+ validate.optional("playlistTitle"): validate.text,
"title": validate.text,
"src": validate.text,
"type": validate.text,
}],
# only include HLS streams
- validate.filter(lambda s: s["type"] == "application/x-mpegurl")
+ # validate.filter(lambda s: s["type"] == "application/x-mpegurl")
)
}]
)
@@ -63,7 +66,7 @@ class Schoolism(Plugin):
default=1,
metavar="PART",
help="""
- Play part number PART of the lesson.
+ Play part number PART of the lesson, or assignment feedback video.
Defaults is 1.
"""
@@ -83,44 +86,50 @@ def login(self, email, password):
"""
if self.options.get("email") and self.options.get("password"):
res = self.session.http.post(self.login_url, data={"email": email,
- "password": password,
- "redirect": None,
- "submit": "Login"})
+ "password": password,
+ "redirect": None,
+ "submit": "Login"})
if res.cookies.get("password") and res.cookies.get("email"):
return res.cookies.get("email")
else:
- self.logger.error("Failed to login to Schoolism, incorrect email/password combination")
+ log.error("Failed to login to Schoolism, incorrect email/password combination")
else:
- self.logger.error("An email and password are required to access Schoolism streams")
+ log.error("An email and password are required to access Schoolism streams")
def _get_streams(self):
user = self.login(self.options.get("email"), self.options.get("password"))
if user:
- self.logger.debug("Logged in to Schoolism as {0}", user)
+ log.debug("Logged in to Schoolism as {0}", user)
res = self.session.http.get(self.url, headers={"User-Agent": useragents.SAFARI_8})
lesson_playlist = self.playlist_schema.validate(res.text)
part = self.options.get("part")
+ video_type = "Lesson" if "lesson" in self.url_re.match(self.url).group(1).lower() else "Assignment Feedback"
- self.logger.info("Attempting to play lesson Part {0}", part)
+ log.info("Attempting to play {0} Part {1}", video_type, part)
found = False
# make request to key-time api, to get key specific headers
- res = self.session.http.get(self.key_time_url, headers={"User-Agent": useragents.SAFARI_8})
+ _ = self.session.http.get(self.key_time_url, headers={"User-Agent": useragents.SAFARI_8})
for i, video in enumerate(lesson_playlist, 1):
if video["sources"] and i == part:
found = True
for source in video["sources"]:
- for s in HLSStream.parse_variant_playlist(self.session,
- source["src"],
- headers={"User-Agent": useragents.SAFARI_8,
- "Referer": self.url}).items():
- yield s
+ if source['type'] == "video/mp4":
+ yield "live", HTTPStream(self.session, source["src"],
+ headers={"User-Agent": useragents.SAFARI_8,
+ "Referer": self.url})
+ elif source['type'] == "application/x-mpegurl":
+ for s in HLSStream.parse_variant_playlist(self.session,
+ source["src"],
+ headers={"User-Agent": useragents.SAFARI_8,
+ "Referer": self.url}).items():
+ yield s
if not found:
- self.logger.error("Could not find lesson Part {0}", part)
+ log.error("Could not find {0} Part {1}", video_type, part)
__plugin__ = Schoolism
| Schoolism Video Feedbacks Plugins Compatibility?
Checklist
- [ ] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
With the Schoolism plugin, you can download lessons with Streamlink.exe --schoolism-email XXXX --schoolism-password XXXX --schoolism-part 1 -v "https://www.schoolism.com/watchLesson.php?type=st&id=506" best -o "LOCATION"
Is there a way to download the video feedbacks from urls such as https://www.schoolism.com/viewAssignment.php?type=st&courseID=44&id=506¬Submitted=true as well? If there isn't, I'd greatly appreciate a modification to the plugin to allow for one to download the video feedbacks.
| It's not supported by the plugin, it could be added - but I don't have access to schoolism, when I wrote it the first time I borrowed someones credentials.
You can check using your browsers dev tools to find the m3u8 URL and use that along with the auth cookies (not sure of the their names though) with streamlink.
**just for your interest, nobody here has an account**
if someone wants this feature,
the person must share it with someone who wants to add this feature
---
**at some point** it's not worth to have an **unfixable issue** open
like some of the other Schoolism issues https://github.com/streamlink/streamlink/issues/1046#issuecomment-386712317 _(over one year)_
and it will be closed, so it can disappear in the shadows
No response received. | 2018-08-13T00:10:56 |
|
streamlink/streamlink | 2,048 | streamlink__streamlink-2048 | [
"2047"
] | c7bef14b2aed576777cc538ade1fbd2ad4047f08 | diff --git a/src/streamlink/plugins/euronews.py b/src/streamlink/plugins/euronews.py
--- a/src/streamlink/plugins/euronews.py
+++ b/src/streamlink/plugins/euronews.py
@@ -3,10 +3,11 @@
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream, HTTPStream
+from streamlink.utils.url import update_scheme
class Euronews(Plugin):
- _url_re = re.compile(r"http(?:s)?://(\w+)\.?euronews.com/(live|.*)")
+ _url_re = re.compile(r'(?P<scheme>https?)://(?P<subdomain>\w+)\.?euronews.com/(?P<path>live|.*)')
_re_vod = re.compile(r'<meta\s+property="og:video"\s+content="(http.*?)"\s*/>')
_live_api_url = "http://{0}.euronews.com/api/watchlive.json"
_live_schema = validate.Schema({
@@ -32,28 +33,29 @@ def _get_vod_stream(self):
if len(video_urls):
return dict(vod=HTTPStream(self.session, video_urls[0]))
- def _get_live_streams(self, subdomain):
+ def _get_live_streams(self, match):
"""
Get the live stream in a particular language
- :param subdomain:
+ :param match:
:return:
"""
- res = self.session.http.get(self._live_api_url.format(subdomain))
- live_res = self.session.http.json(res, schema=self._live_schema)
- api_res = self.session.http.get(live_res[u"url"])
- stream_data = self.session.http.json(api_res, schema=self._stream_api_schema)
- return HLSStream.parse_variant_playlist(self.session, stream_data[u'primary'])
+ live_url = self._live_api_url.format(match.get("subdomain"))
+ live_res = self.session.http.json(self.session.http.get(live_url), schema=self._live_schema)
+
+ api_url = update_scheme("{0}:///".format(match.get("scheme")), live_res["url"])
+ api_res = self.session.http.json(self.session.http.get(api_url), schema=self._stream_api_schema)
+
+ return HLSStream.parse_variant_playlist(self.session, api_res["primary"])
def _get_streams(self):
"""
Find the streams for euronews
:return:
"""
- match = self._url_re.match(self.url)
- subdomain, path = match.groups()
+ match = self._url_re.match(self.url).groupdict()
- if path == "live":
- return self._get_live_streams(subdomain)
+ if match.get("path") == "live":
+ return self._get_live_streams(match)
else:
return self._get_vod_stream()
| Euronews error, unable to open URL
<!--
Thanks for reporting a bug!
USE THE TEMPLATE. Otherwise your bug report may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed bug reports:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Bug Report
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a bug report and I have read the contribution guidelines.
### Description
<!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. -->
I'm unable to open Euronews live stream.
### Expected / Actual behavior
<!-- What do you expect to happen, and what is actually happening? -->
I expect the stream to open in my media player.
Instead I get this:
```
marco@vbox-ubuntu1804:~$ streamlink http://it.euronews.com/live
[cli][info] Found matching plugin euronews for URL http://it.euronews.com/live
error: Unable to open URL: //euronews-it-p-api.hexaglobe.net/1c903a19de71387485a0f6f74d7923f5/5b8a5583/euronews/euronews-euronews-website-web-responsive-2/it/stream_info.php?format=hls (Invalid URL '//euronews-it-p-api.hexaglobe.net/1c903a19de71387485a0f6f74d7923f5/5b8a5583/euronews/euronews-euronews-website-web-responsive-2/it/stream_info.php?format=hls': No schema supplied. Perhaps you meant http:////euronews-it-p-api.hexaglobe.net/1c903a19de71387485a0f6f74d7923f5/5b8a5583/euronews/euronews-euronews-website-web-responsive-2/it/stream_info.php?format=hls?)
```
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
Run this command:
```
streamlink http://it.euronews.com/live
```
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a bug report!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
marco@vbox-ubuntu1804:~$ streamlink --loglevel debug http://it.euronews.com/live
[cli][debug] OS: Linux-4.15.0-33-generic-x86_64-with-Ubuntu-18.04-bionic
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 0.14.2+92.gc7bef14b
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.51.0)
[cli][info] Found matching plugin euronews for URL http://it.euronews.com/live
error: Unable to open URL: //euronews-it-p-api.hexaglobe.net/688afb391d4325cad6765c6dc61585a4/5b8a7b36/euronews/euronews-euronews-website-web-responsive-2/it/stream_info.php?format=hls (Invalid URL '//euronews-it-p-api.hexaglobe.net/688afb391d4325cad6765c6dc61585a4/5b8a7b36/euronews/euronews-euronews-website-web-responsive-2/it/stream_info.php?format=hls': No schema supplied. Perhaps you meant http:////euronews-it-p-api.hexaglobe.net/688afb391d4325cad6765c6dc61585a4/5b8a7b36/euronews/euronews-euronews-website-web-responsive-2/it/stream_info.php?format=hls?)
```
### Additional comments, screenshots, etc.
Streamlink versions tested: 0.9.0, 0.14.2 from pip, master from git
Same error with all of them.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-09-01T12:41:33 |
||
streamlink/streamlink | 2,084 | streamlink__streamlink-2084 | [
"1188"
] | 4e4a5a97b5eed3ddc11d11daf8368b6317695858 | diff --git a/src/streamlink/plugins/stadium.py b/src/streamlink/plugins/stadium.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/stadium.py
@@ -0,0 +1,42 @@
+import re
+import logging
+
+from streamlink.plugin import Plugin
+from streamlink.stream import HLSStream
+from streamlink.utils import parse_json
+
+log = logging.getLogger(__name__)
+
+
+class Stadium(Plugin):
+ url_re = re.compile(r"""https?://(?:www\.)?watchstadium\.com/live""")
+ API_URL = "https://player-api.new.livestream.com/accounts/{account_id}/events/{event_id}/stream_info"
+ _stream_data_re = re.compile(r"var StadiumSiteData = (\{.*?});", re.M | re.DOTALL)
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls.url_re.match(url) is not None
+
+ def _get_streams(self):
+ res = self.session.http.get(self.url)
+ m = self._stream_data_re.search(res.text)
+ if m:
+ data = parse_json(m.group(1))
+ if data['LivestreamEnabled'] == '1':
+ account_id = data['LivestreamArgs']['account_id']
+ event_id = data['LivestreamArgs']['event_id']
+ log.debug("Found account_id={account_id} and event_id={event_id}".format(account_id=account_id, event_id=event_id))
+
+ url = self.API_URL.format(account_id=account_id, event_id=event_id)
+ api_res = self.session.http.get(url)
+ api_data = self.session.http.json(api_res)
+ stream_url = api_data.get('secure_m3u8_url') or api_data.get('m3u8_url')
+ if stream_url:
+ return HLSStream.parse_variant_playlist(self.session, stream_url)
+ else:
+ log.error("Could not find m3u8_url")
+ else:
+ log.error("Stream is offline")
+
+
+__plugin__ = Stadium
| diff --git a/tests/plugins/test_stadium.py b/tests/plugins/test_stadium.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_stadium.py
@@ -0,0 +1,16 @@
+from streamlink.plugins.stadium import Stadium
+import unittest
+
+
+class TestPluginStadium(unittest.TestCase):
+ def test_can_handle_url(self):
+ # should match
+ self.assertTrue(Stadium.can_handle_url("http://www.watchstadium.com/live"))
+ self.assertTrue(Stadium.can_handle_url("https://www.watchstadium.com/live"))
+ self.assertTrue(Stadium.can_handle_url("https://watchstadium.com/live"))
+ self.assertTrue(Stadium.can_handle_url("http://watchstadium.com/live"))
+
+ # shouldn't match
+ self.assertFalse(Stadium.can_handle_url("http://www.watchstadium.com/anything/else"))
+ self.assertFalse(Stadium.can_handle_url("http://www.tvcatchup.com/"))
+ self.assertFalse(Stadium.can_handle_url("http://www.youtube.com/"))
| Stadium plugin request
### Checklist
- [x ] This is a feature request.
### Description
Can anyone help with a plugin for Stadium TV here:
https://watchstadium.com/live/
Cheers!
| Can you provide more details on the streams or what the network connection looks like etc.?
https://04476b7c682c4da8b8b4bfe23ef879c1.midas.us-east-1.amazonaws.com/v1/manifest
m3u8 from amazonaws ends up to this playable:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:7
#EXT-X-MEDIA-SEQUENCE:35988
#EXT-X-PROGRAM-DATE-TIME:2017-08-26T22:07:22.133Z
#EXTINF:6.006,
https://stadiumlivein-i.akamaihd.net/hls/live/522512/mux_4/20170824T060520/master_3000/00071/master_3000_00488.ts
https://04476b7c682c4da8b8b4bfe23ef879c1.midas.us-east-1.amazonaws.com/v1/manifest/61a556f78e4547c8ab5c6297ea291d6350767ca2/Mux/ffe7bfb2-e4dc-4d43-8f8c-48868174d97c/0.m3u8
Already have that but when the stream changes a plugin will be able to get the correct stream again.
Did you mean to close this?
Actually no, not sure how that happened.. I only just noticed.. can you please look into this new plugin. Thanks.
Just to let folks know, this is the exact same issue as this:
https://github.com/streamlink/streamlink/issues/687
It's a channel run by Sinclair and bearybig stated #EXT-X-DISCONTINUITY is an issue when the "We'll be right back" shows up instead of commercials.
I mean I realize the other channels use "uplynk" while this one uses "amazonaws" but it appears to be run very similar to the other 3 channels.
@RedPenguin2
What do you mean, this channel has been playing fine when you grab the end stream. I think you made a comment on the wrong issue.
I just wanted to know if a plugin was possible as the stream changes.
| 2018-10-02T09:37:46 |
streamlink/streamlink | 2,085 | streamlink__streamlink-2085 | [
"2042"
] | 4e4a5a97b5eed3ddc11d11daf8368b6317695858 | diff --git a/src/streamlink/plugins/senategov.py b/src/streamlink/plugins/senategov.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/senategov.py
@@ -0,0 +1,113 @@
+import re
+import logging
+
+from streamlink.plugin import Plugin
+from streamlink.plugin.api import useragents
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
+from streamlink.utils import parse_json
+from streamlink.compat import urlparse, parse_qsl
+from streamlink.utils.times import hours_minutes_seconds
+
+log = logging.getLogger(__name__)
+
+
+class SenateGov(Plugin):
+ url_re = re.compile(r"""https?://(?:.+\.)?senate\.gov/(isvp)?""")
+ streaminfo_re = re.compile(r"""var\s+streamInfo\s+=\s+new\s+Array\s*\(\s*(\[.*\])\);""")
+ stt_re = re.compile(r"""^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$""")
+ url_lookup = {
+ "ag": ["76440", "https://ag-f.akamaihd.net"],
+ "aging": ["76442", "https://aging-f.akamaihd.net"],
+ "approps": ["76441", "https://approps-f.akamaihd.net"],
+ "armed": ["76445", "https://armed-f.akamaihd.net"],
+ "banking": ["76446", "https://banking-f.akamaihd.net"],
+ "budget": ["76447", "https://budget-f.akamaihd.net"],
+ "cecc": ["76486", "https://srs-f.akamaihd.net"],
+ "commerce": ["80177", "https://commerce1-f.akamaihd.net"],
+ "csce": ["75229", "https://srs-f.akamaihd.net"],
+ "dpc": ["76590", "https://dpc-f.akamaihd.net"],
+ "energy": ["76448", "https://energy-f.akamaihd.net"],
+ "epw": ["76478", "https://epw-f.akamaihd.net"],
+ "ethics": ["76449", "https://ethics-f.akamaihd.net"],
+ "finance": ["76450", "https://finance-f.akamaihd.net"],
+ "foreign": ["76451", "https://foreign-f.akamaihd.net"],
+ "govtaff": ["76453", "https://govtaff-f.akamaihd.net"],
+ "help": ["76452", "https://help-f.akamaihd.net"],
+ "indian": ["76455", "https://indian-f.akamaihd.net"],
+ "intel": ["76456", "https://intel-f.akamaihd.net"],
+ "intlnarc": ["76457", "https://intlnarc-f.akamaihd.net"],
+ "jccic": ["85180", "https://jccic-f.akamaihd.net"],
+ "jec": ["76458", "https://jec-f.akamaihd.net"],
+ "judiciary": ["76459", "https://judiciary-f.akamaihd.net"],
+ "rpc": ["76591", "https://rpc-f.akamaihd.net"],
+ "rules": ["76460", "https://rules-f.akamaihd.net"],
+ "saa": ["76489", "https://srs-f.akamaihd.net"],
+ "smbiz": ["76461", "https://smbiz-f.akamaihd.net"],
+ "srs": ["75229", "https://srs-f.akamaihd.net"],
+ "uscc": ["76487", "https://srs-f.akamaihd.net"],
+ "vetaff": ["76462", "https://vetaff-f.akamaihd.net"],
+ }
+
+ hls_url = "{base}/i/{filename}_1@{number}/master.m3u8?"
+ hlsarch_url = "https://ussenate-f.akamaihd.net/i/{filename}.mp4/master.m3u8"
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls.url_re.match(url) is not None
+
+ def _isvp_to_m3u8(self, url):
+ qs = dict(parse_qsl(urlparse(url).query))
+ if "comm" not in qs:
+ log.error("Missing `comm` value")
+ if "filename" not in qs:
+ log.error("Missing `filename` value")
+
+ d = self.url_lookup.get(qs['comm'])
+ if d:
+ snumber, baseurl = d
+ stream_url = self.hls_url.format(filename=qs['filename'], number=snumber, base=baseurl)
+ else:
+ stream_url = self.hlsarch_url.format(filename=qs['filename'])
+
+ return stream_url, self.parse_stt(qs.get('stt', 0))
+
+ def _get_streams(self):
+ self.session.http.headers.update({
+ "User-Agent": useragents.CHROME,
+ })
+ m = self.url_re.match(self.url)
+ if m and not m.group(1):
+ log.debug("Searching for ISVP URL")
+ isvp_url = self._get_isvp_url()
+ else:
+ isvp_url = self.url
+
+ if not isvp_url:
+ log.error("Could not find the ISVP URL")
+ return
+ else:
+ log.debug("ISVP URL: {0}".format(isvp_url))
+
+ stream_url, start_offset = self._isvp_to_m3u8(isvp_url)
+ log.debug("Start offset is: {0}s".format(start_offset))
+ return HLSStream.parse_variant_playlist(self.session, stream_url, start_offset=start_offset)
+
+ def _get_isvp_url(self):
+ res = self.session.http.get(self.url)
+ for iframe in itertags(res.text, 'iframe'):
+ m = self.url_re.match(iframe.attributes.get('src'))
+ return m and m.group(1) is not None and iframe.attributes.get('src')
+
+ @classmethod
+ def parse_stt(cls, param):
+ m = cls.stt_re.match(param)
+ if m:
+ return int(m.group('hours') or 0) * 3600 + \
+ int(m.group('minutes')) * 60 + \
+ int(m.group('seconds'))
+ else:
+ return 0
+
+
+__plugin__ = SenateGov
| diff --git a/tests/plugins/test_senategov.py b/tests/plugins/test_senategov.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_senategov.py
@@ -0,0 +1,18 @@
+from streamlink.plugins.senategov import SenateGov
+import unittest
+
+
+class TestPluginSenateGov(unittest.TestCase):
+ def test_can_handle_url(self):
+ # should match
+ self.assertTrue(SenateGov.can_handle_url("https://www.foreign.senate.gov/hearings/business-meeting-082218"))
+ self.assertTrue(SenateGov.can_handle_url("https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo-poster-flash-fit%2Epng"))
+
+ # shouldn't match
+ self.assertFalse(SenateGov.can_handle_url("http://www.tvcatchup.com/"))
+ self.assertFalse(SenateGov.can_handle_url("http://www.youtube.com/"))
+
+ def test_stt_parse(self):
+ self.assertEqual(600, SenateGov.parse_stt("10:00"))
+ self.assertEqual(3600, SenateGov.parse_stt("01:00:00"))
+ self.assertEqual(70, SenateGov.parse_stt("1:10"))
| How to Stream Akamai (?) Video from Senate Foreign Relations Committee Website
## Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is not a bug report, feature request, or plugin issue/request.
- [x] I have read the contribution guidelines.
### Description
I am attempting to load archived video and live video streams of the US Senate Foreign Relations Committee ([Example](https://www.foreign.senate.gov/hearings/business-meeting-082218)) in VLC via streamlink. It appears their video streaming is done via Akamai and AMP v4.90.9 from right-clicking the player embedded in provided examples.
### Expected / Actual behavior
Ideally, pointing streamlink to the hearing page containing an embedded player would automagically identify available streams and open the best quality stream in VLC:
`streamlink "https://www.foreign.senate.gov/hearings/business-meeting-082218" best`
What actually happens is that streamlink fails with an error `error: No plugin can handle URL: https://www.foreign.senate.gov/hearings/business-meeting-082218`
### Reproduction steps / Explicit stream URLs to test
I have discovered that the URL for their embedded player gets a little closer ([Example](http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218)), but streamlink still doesn't find any streams at this URL. That is, until I replace https:// with *akamaihd://*:
`streamlink "akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218"`
Results in:
```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218
Available streams: live (worst, best)
```
When I specify "best" and run the command again, the result is:
```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218
[cli][info] Available streams: live (worst, best)
[cli][info] Opening stream: live (akamaihd)
[cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=PPJRC&g=VFVQOIITOQRF&v=2.5.8))
error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting
```
### Logs
```
[cli][debug] OS: macOS 10.13.6
[cli][debug] Python: 2.7.15
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218
[plugin.akamaihd][debug] URL=http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218; params={}
[cli][info] Available streams: live (worst, best)
[cli][info] Opening stream: live (akamaihd)
[stream.akamaihd][debug] Opening host=http://www.senate.gov streamname=isvp/
[cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=VREJP&g=JOHWJGPLHFNA&v=2.5.8))
error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting
```
### Additional comments, screenshots, etc.
It appears the Senate Foreign Relations Committee uses the date of the hearing as the main reference ID. Since the committee only meets once a day, there's only ever one stream on any given day.
There's possibly useful information in the source of each player page. In the source code for the example link I've used above, there's this snippet:
```
<a id="watch-live-now" class="small btn" href="javascript:openVideoWin('/hearings/watch?hearingid=AA0FF459-5056-A066-60A0-8B11F704E85E');">Open New Window</a>
```
Also, from the source code the video player code can have a lot of parameters specified:
```
https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo%2Dposter%2Dflash%2Dfit%2Epng
```
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| You can watch this directly, stream url appears to be static.
https://foreign-f.akamaihd.net/i/foreign082218_1@76451/master.m3u8?
```
[cli][info] Found matching plugin hls for URL https://foreign-f.akamaihd.net/i/foreign082218_1@76451/master.m3u8?" best
Available streams: 360p_alt (worst), 360p (best)
```
```
C:\>youtube-dl.exe -v --hls-prefer-native --no-check-certificate --no-overwrites "https://foreign-f.akamaihd.net/i/foreign082218_1@76451/master.m3u8?"
[debug] System config: []
[debug] User config: []
[debug] Custom config: []
[debug] Command-line args: ['-v', '--hls-prefer-native', '--no-check-certificate', '--no-overwrites', 'https://foreign-f.akamaihd.net/i/foreign082218_1@76451/master.m3u8?']
[debug] Encodings: locale cp1252, fs mbcs, out cp850, pref cp1252
[debug] youtube-dl version 2018.08.28
[debug] Python version 3.4.4 (CPython) - Windows-10-10.0.17134
[debug] exe versions: ffmpeg n4.0.2-ffmpeg-windows-build-helpers, ffprobe n4.0.2-ffmpeg-windows-build-helpers, rtmpdump 2.4
[debug] Proxy map: {}
[generic] master: Requesting header
WARNING: Could not send HEAD request to https://foreign-f.akamaihd.net/i/foreign082218_1@76451/master.m3u8?: HTTP Error 405: Method Not Allowed
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[debug] Default format spec: bestvideo+bestaudio/best
[debug] Invoking downloader on 'https://foreign-f.akamaihd.net/i/foreign082218_1@76451/index_356_av-b.m3u8?sd=10&rebase=on'
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 734
[download] Destination: master-master.mp4
[download] 2.5% of ~300.16MiB at 1.77MiB/s ETA 04:51 [download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 1 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 2 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 3 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 4 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 5 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 6 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 7 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 8 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 9 of 10)...
[download] Got server HTTP error: HTTP Error 404: Not Found. Retrying fragment 19 (attempt 10 of 10)...
[download] Skipping fragment 19...
[download] 7.5% of ~300.27MiB at 1.59MiB/s ETA 05:02
```
<a href='https://postimg.cc/image/ehaqjlf5t/' target='_blank'><img src='https://s8.postimg.cc/ehaqjlf5t/Screen_Shot.jpg' border='0' alt='Screen_Shot'/></a>
This is helpful and works—could you explain how you arrived at this being the static URL? I want to reverse engineer this into an Automator action if possible—to convert a URL of pages with the embedded player into the appropriate stream URL to load in VLC via streamlink. Specifically, where does "76451" come from in your working URL? What function does that serve in loading the stream? And the _01 after the date of the hearing? Why does the URL end with master.m3u8?
I played the video in the morning and later in the afternoon, url was the same so it must be static.
To get stream url run firefox and install extension HLS stream detector,
https://addons.mozilla.org/en-GB/firefox/addon/hls-stream-detector/
Open main url, start video in embeded player and stream detector will politely pop up with stream url.
This is as simple as you can get. As you said it works, so I didn't look more into that. | 2018-10-02T13:49:25 |
streamlink/streamlink | 2,090 | streamlink__streamlink-2090 | [
"1770"
] | b21df07689023f1f6fc79b228da4faa76c617667 | diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py
--- a/src/streamlink_cli/main.py
+++ b/src/streamlink_cli/main.py
@@ -57,10 +57,14 @@ def check_file_output(filename, force):
log.debug("Checking file output")
if os.path.isfile(filename) and not force:
- answer = console.ask("File {0} already exists! Overwrite it? [y/N] ",
- filename)
+ if sys.stdin.isatty():
+ answer = console.ask("File {0} already exists! Overwrite it? [y/N] ",
+ filename)
- if answer.lower() != "y":
+ if answer.lower() != "y":
+ sys.exit()
+ else:
+ log.error("File {0} already exists, use --force to overwrite it.".format(filename))
sys.exit()
return FileOutput(filename)
@@ -322,7 +326,7 @@ def read_stream(stream, output, prebuffer, chunk_size=8192):
is_player = isinstance(output, PlayerOutput)
is_http = isinstance(output, HTTPServer)
is_fifo = is_player and output.namedpipe
- show_progress = isinstance(output, FileOutput) and output.fd is not stdout
+ show_progress = isinstance(output, FileOutput) and output.fd is not stdout and sys.stdout.isatty()
stream_iterator = chain(
[prebuffer],
| diff --git a/tests/test_cli_main.py b/tests/test_cli_main.py
--- a/tests/test_cli_main.py
+++ b/tests/test_cli_main.py
@@ -18,12 +18,25 @@ def test_check_file_output_exists(self):
tmpfile = tempfile.NamedTemporaryFile()
try:
streamlink_cli.main.console = console = Mock()
+ streamlink_cli.main.sys.stdin = stdin = Mock()
+ stdin.isatty.return_value = True
console.ask.return_value = "y"
self.assertTrue(os.path.exists(tmpfile.name))
self.assertIsInstance(check_file_output(tmpfile.name, False), FileOutput)
finally:
tmpfile.close()
+ def test_check_file_output_exists_notty(self):
+ tmpfile = tempfile.NamedTemporaryFile()
+ try:
+ streamlink_cli.main.console = console = Mock()
+ streamlink_cli.main.sys.stdin = stdin = Mock()
+ stdin.isatty.return_value = False
+ self.assertTrue(os.path.exists(tmpfile.name))
+ self.assertRaises(SystemExit, check_file_output, tmpfile.name, False)
+ finally:
+ tmpfile.close()
+
def test_check_file_output_exists_force(self):
tmpfile = tempfile.NamedTemporaryFile()
try:
| Add an option to disable the download progress log message
### Checklist
- [ ] This is a bug report.
- [x] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [x] I have read the contribution guidelines.
### Description
Apart from regular console use, I also run Streamlink from Java (through a Java Process) and redirect the system output & error streams to Java. If I tell Streamlink to use a player, all is fine. However, if I tell Streamlink to save the file, it stops writing to the file after less than 1 minute. It appears to still be capturing as there are no new log messages to indicate an error but the file doesn't get any bigger.
After some investigating, it turns out to be the "[download] ??? Written ???" log message that clears the current line in order to print the new value that is causing the problem (the print_inplace function in progress.py). That log message isn't printed in Java which was a clue to the problem.
I've tried the none loglevel option but the download progress log message still appears. My only option ATM without modifying the Streamlink code myself is to turn the loglevel up to debug level causing no line clearing, just a whole lot of logspam, BUT a successful recording.
TLDR;
When I specify -Q option for quiet logging, can it NOT print the download progress as well please.
Or maybe an extra CLI argument to disable the download progress message altogether (or disable current line clearing and just write the new value on a new line). Ideally, I'd still like to get the error/warning/info log messages and just disable the constantly updating download progress.
### Comments, screenshots, etc.
Thanks to all the contributors for this awesome software.
| I think the best thing here would be to only show that progress counter when there is a valid terminal to write to (can also remove it when using -q). Then you can set the log level to warning and still get those messages.
Same problem with python | 2018-10-03T08:32:41 |
streamlink/streamlink | 2,100 | streamlink__streamlink-2100 | [
"2079"
] | e29c8b75e664671216abc8c660f2dec21310cec9 | diff --git a/src/streamlink/plugins/cubetv.py b/src/streamlink/plugins/cubetv.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/cubetv.py
@@ -0,0 +1,59 @@
+import re
+
+from streamlink.plugin import Plugin
+from streamlink.plugin.api import validate
+from streamlink.stream import HLSStream
+from streamlink import NoStreamsError
+from streamlink.utils import parse_json
+
+class CubeTV(Plugin):
+
+ _url_re = re.compile(r"https?://(www\.)?cubetv\.sg/(?P<channel>[^/]{2,})")
+
+ _channel_info_api_url_base = "https://www.cubetv.sg/studio/info?cube_id={channel}"
+ _stream_data_api_url_base = "https://www.cubetv.sg/studioApi/getStudioSrcBySid?sid={gid}&videoType=1&https=1"
+
+ _channel_info_schema = validate.Schema({
+ u"code" : 1,
+ u"msg": u"success",
+ u"data": {
+ u"gid": validate.text,
+ u"cube_id": validate.text
+ }
+ })
+
+ _stream_data_schema = validate.Schema({
+ u"code" : 1,
+ u"msg": u"success",
+ u"data": {
+ u"video": u"hls",
+ u"video_src": validate.url()
+ }
+ })
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_api_res(self, user_id):
+ try:
+ res = self.session.http.get(self._channel_info_api_url_base.format(channel=user_id))
+ return res
+ except Exception as e:
+ raise NoStreamsError(self.url)
+
+ def _get_streams(self):
+ user_id = self._url_re.match(self.url).group(2)
+ res = self._get_api_res(user_id)
+ user_gid = self.session.http.json(res, schema=self._channel_info_schema)['data']['gid']
+
+ try:
+ stream_data = self.session.http.get(self._stream_data_api_url_base.format(gid=user_gid))
+ hls = self.session.http.json(stream_data, schema=self._stream_data_schema)['data']['video_src']
+ except Exception as e:
+ raise NoStreamsError(self.url)
+
+ return HLSStream.parse_variant_playlist(self.session, hls)
+
+
+__plugin__ = CubeTV
| diff --git a/tests/plugins/test_cubetv.py b/tests/plugins/test_cubetv.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_cubetv.py
@@ -0,0 +1,15 @@
+from streamlink.plugins.cubetv import CubeTV
+import unittest
+
+class TestPluginCubeTV(unittest.TestCase):
+ def test_can_handle_url(self):
+ # should match
+ self.assertTrue(CubeTV.can_handle_url("https://www.cubetv.sg/Tecnosh"))
+ self.assertTrue(CubeTV.can_handle_url("https://www.cubetv.sg/letsgodroid"))
+ self.assertTrue(CubeTV.can_handle_url("https://www.cubetv.sg/14939646"))
+ self.assertTrue(CubeTV.can_handle_url("https://www.cubetv.sg/Luladopub"))
+ # shouldn't match
+ self.assertFalse(CubeTV.can_handle_url("https://www.cubetv.sg/g/PUBG"))
+ self.assertFalse(CubeTV.can_handle_url("https://www.cubetv.sg/c"))
+ self.assertFalse(CubeTV.can_handle_url("http://www.twitch.tv/"))
+ self.assertFalse(CubeTV.can_handle_url("http://www.qoo10.sg/"))
| Cube.TV Plugin
## Plugin Request
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
https://www.cubetv.sg/
**Cube.TV** is a chinese company live streaming plataform that focous on PC and Mobile Games. They are expanding their business worldwide (huge in Brazil right now) with great reward system for streamers and viewers.
Like Twitch, streamers can interact with their viewers in a chat box, and also get donate by viewers using their currency called "diamonds".
Also, viewers can get prices with daily rewards system and many other features.
Cube.TV literally pays you by how many viewers you got. It depends on the fifth highest number of viewers you got montly.
### Example stream URLs
1. https://www.cubetv.sg/Tecnosh
2. https://www.cubetv.sg/letsgodroid
3. https://www.cubetv.sg/14939646
4. https://www.cubetv.sg/Luladopub
### Additional comments, screenshots, etc.
I'm sure adding cube.tv plugin to streamlink would increase its users.
Thank you for your time!
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-10-06T12:53:44 |
|
streamlink/streamlink | 2,102 | streamlink__streamlink-2102 | [
"2095"
] | e29c8b75e664671216abc8c660f2dec21310cec9 | diff --git a/src/streamlink/plugins/ok_live.py b/src/streamlink/plugins/ok_live.py
--- a/src/streamlink/plugins/ok_live.py
+++ b/src/streamlink/plugins/ok_live.py
@@ -5,7 +5,7 @@
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
-_url_re = re.compile(r"https?://(www\.)?ok\.ru/live/\d+")
+_url_re = re.compile(r"https?://(www\.)?ok\.ru/(live|video)/\d+")
_vod_re = re.compile(r";(?P<hlsurl>[^;]+video\.m3u8.+?)\\"")
_schema = validate.Schema(
@@ -21,7 +21,7 @@
class OK_live(Plugin):
"""
- Support for ok.ru live stream: http://www.ok.ru/live/
+ Support for ok.ru live stream: http://www.ok.ru/live/ and for ok.ru VoDs: http://www.ok.ru/video/
"""
@classmethod
def can_handle_url(cls, url):
| diff --git a/tests/plugins/test_ok_live.py b/tests/plugins/test_ok_live.py
--- a/tests/plugins/test_ok_live.py
+++ b/tests/plugins/test_ok_live.py
@@ -9,6 +9,7 @@ def test_can_handle_url(self):
self.assertTrue(OK_live.can_handle_url("https://ok.ru/live/12345"))
self.assertTrue(OK_live.can_handle_url("http://ok.ru/live/12345"))
self.assertTrue(OK_live.can_handle_url("http://www.ok.ru/live/12345"))
+ self.assertTrue(OK_live.can_handle_url("https://ok.ru/video/266205792931"))
# shouldn't match
self.assertFalse(OK_live.can_handle_url("http://www.tvcatchup.com/"))
| ok.ru VODs
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x ] This is a plugin issue and I have read the contribution guidelines.
### Description
i enter link in #1884 but "https://raw.githubusercontent.com/back-to/plugins/master/plugins/ok_live.py" 404: Not Found. Thanks
<!-- Explain the plugin issue as thoroughly as you can. -->
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. D:\my\Streamlinkl\bin>streamlink -l debug "https://ok.ru/video/266205792931" best
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
[cli][debug] OS: Windows 8.1
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
error: No plugin can handle URL: https://ok.ru/video/266205792931
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| > No plugin can handle URL
As already mentioned in #1884, Streamlink's ok.ru plugin doesn't support VODs.
> 404: Not Found
This was a link to a custom version of the plugin from an external repository maintained by @back-to, which is not (publicly) available anymore, hence the 404 error message. I don't know why, but he will have his reasons. I'll tag this thread as plugin enhancement request.
@bastimeyer
Thanks for the support
So now what can I do to run the code without error?
| 2018-10-07T00:44:28 |
streamlink/streamlink | 2,108 | streamlink__streamlink-2108 | [
"2071"
] | 934ad3f0eb39cdc2d07b683756544ccca174916c | diff --git a/src/streamlink/plugins/tamago.py b/src/streamlink/plugins/tamago.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/tamago.py
@@ -0,0 +1,52 @@
+import re
+
+from streamlink.plugin import Plugin
+from streamlink.plugin.api import validate
+from streamlink.stream import HTTPStream
+from streamlink import NoStreamsError
+
+
+class Tamago(Plugin):
+
+ _url_re = re.compile(r"https?://(?:player\.)?tamago\.live/w/(?P<id>\d+)")
+
+ _api_url_base = "https://player.tamago.live/api/rooms/{id}"
+
+ _api_response_schema = validate.Schema({
+ u"status": 200,
+ u"message": u"Success",
+ u"data": {
+ u"room_number": validate.text,
+ u"stream": {validate.text: validate.url()}
+ }
+ })
+
+ _stream_qualities = {
+ u"150": "144p",
+ u"350": "360p",
+ u"550": "540p",
+ u"900": "720p",
+ }
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_streams(self):
+ user_id = self._url_re.match(self.url).group('id')
+
+ try:
+ api_response = self.session.http.get(self._api_url_base.format(id=user_id))
+ streams = self.session.http.json(api_response, schema=self._api_response_schema)['data']['stream']
+ except Exception:
+ raise NoStreamsError(self.url)
+
+ unique_stream_urls = []
+ for stream in streams.keys():
+ if streams[stream] not in unique_stream_urls:
+ unique_stream_urls.append(streams[stream])
+ quality = self._stream_qualities[stream] if stream in self._stream_qualities.keys() else "720p+"
+ yield quality, HTTPStream(self.session, streams[stream])
+
+
+__plugin__ = Tamago
| diff --git a/tests/plugins/test_tamago.py b/tests/plugins/test_tamago.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_tamago.py
@@ -0,0 +1,24 @@
+import unittest
+
+from streamlink.plugins.tamago import Tamago
+
+
+class TestPluginTamago(unittest.TestCase):
+ def test_can_handle_url(self):
+ should_match = [
+ 'https://player.tamago.live/w/2009642',
+ 'https://player.tamago.live/w/1882066',
+ 'https://player.tamago.live/w/1870142',
+ 'https://player.tamago.live/w/1729968',
+ ]
+ for url in should_match:
+ self.assertTrue(Tamago.can_handle_url(url))
+
+ def test_can_handle_url_negative(self):
+ should_not_match = [
+ 'https://download.tamago.live/faq',
+ 'https://player.tamago.live/gaming/pubg',
+ 'https://www.twitch.tv/twitch'
+ ]
+ for url in should_not_match:
+ self.assertFalse(Tamago.can_handle_url(url))
| player.tamago.live Plugin
<!--
Thanks for requesting a plugin!
USE THE TEMPLATE. Otherwise your plugin request may be rejected.
First, see the contribution guidelines and plugin request requirements:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Plugin requests which fall into the categories we will not implement will be closed immediately.
Also check the list of open and closed plugin requests:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+request%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Request
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
https://player.tamago.live
**Tamago** is a live streaming social network that lets you watch or broadcast live video anytime, anywhere. Like *Twitch*, streamers can interact with their viewers in a chat box. Get exclusive content, from your favourite TV shows and concerts, to the hottest e-sports leagues and more, get front row seats or go behind the scenes with Tamago.
Showcase your talent to a wide audience of viewers and fellow broadcasters. Live video streaming is spontaneous and does not have to be perfect, so anyone can be a broadcaster! You can get rewarded for broadcasting too! Collect gifts during your live streams and keep the profits when you cash out.
https://download.tamago.live/faq
### Example stream URLs
<!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. -->
1. https://player.tamago.live/w/2009642
2. https://player.tamago.live/w/1882066
3. https://player.tamago.live/w/1870142
4. https://player.tamago.live/w/1729968
5. ...
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-10-10T20:38:57 |
|
streamlink/streamlink | 2,112 | streamlink__streamlink-2112 | [
"2031"
] | 1961201e6e4dd74f4c1d0f9fecf8a4ed87a60e66 | diff --git a/src/streamlink/plugins/metube.py b/src/streamlink/plugins/metube.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/metube.py
@@ -0,0 +1,58 @@
+import re
+
+from streamlink.plugin import Plugin
+from streamlink.plugin.api import useragents
+from streamlink.stream import HLSStream
+
+
+class MeTube(Plugin):
+
+ _url_re = re.compile(r"""https?://(?:www\.)?metube\.id/
+ (?P<type>live|videos)/\w+(?:/.*)?""", re.VERBOSE)
+
+ # extracted from webpage source
+ _VOD_STREAM_NAMES = {
+ "3000k": "1080p",
+ "1800k": "720p",
+ "800k": "480p",
+ "300k": "240p"
+ }
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_streams(self):
+ stream_type = self._url_re.match(self.url).group("type")
+ hls_re = re.compile(r"""["'](?P<url>[^"']+\.m3u8[^"']*?)["']""")
+
+ headers = {
+ "Origin": "https://www.metube.id",
+ "User-Agent": useragents.FIREFOX
+ }
+
+ res = self.session.http.get(self.url)
+ match = hls_re.search(res.text)
+
+ if not match:
+ return
+
+ stream_url = match.group("url")
+
+ if stream_type == "live":
+ return HLSStream.parse_variant_playlist(self.session, stream_url,
+ headers=headers)
+ else:
+ streams = {}
+
+ for quality, stream in HLSStream.parse_variant_playlist(
+ self.session,
+ stream_url,
+ headers=headers).items():
+ name = self._VOD_STREAM_NAMES.get(quality, quality)
+ streams[name] = stream
+
+ return streams
+
+
+__plugin__ = MeTube
| diff --git a/tests/plugins/test_metube.py b/tests/plugins/test_metube.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_metube.py
@@ -0,0 +1,24 @@
+import unittest
+
+from streamlink.plugins.metube import MeTube
+
+
+class TestPluginMeTube(unittest.TestCase):
+ def test_can_handle_url(self):
+ should_match = [
+ 'https://www.metube.id/live/METROTV',
+ 'https://www.metube.id/live/GTV',
+ 'https://www.metube.id/videos/16881738/yudi_28_bogor_-amazingakak',
+ 'https://www.metube.id/videos/16873428/liverpool-vs-psg-3-2-goals-and-highlights-2018',
+ ]
+ for url in should_match:
+ self.assertTrue(MeTube.can_handle_url(url))
+
+ def test_can_handle_url_negative(self):
+ should_not_match = [
+ 'https://www.metube.id/me/IMAA2018',
+ 'https://www.metube.id/auditions',
+ 'https://www.twitch.tv/twitch'
+ ]
+ for url in should_not_match:
+ self.assertFalse(MeTube.can_handle_url(url))
| metube.id plugin request
## Plugin Request
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
www.metube.id
- serveral Indonesia TV channels / legal streaming portal, see TERMS & CONDITIONS
link to live channel selection:
- https://www.metube.id/live
### Example stream URLs
1. https://www.metube.id/live/METROTV
2. https://www.metube.id/live/GTV
3. https://www.metube.id/live/RCTI
4. https://www.metube.id/live/TRANS7
5. ...
### Additional comments, screenshots, etc.
sample embeded stream: m3u8 / accessing: HTTP 502 bad Gateway
1. https://cdn-livetv1.metube.id/hls/metrotv.m3u8 /
https://cdn-livetv1.metube.id/hls/metrotv_480/index.m3u8
2. https://cdn-livetv2.metube.id/hls/globaltv.m3u8 /
https://cdn-livetv2.metube.id/hls/globaltv_480/index.m3u8
3. https://cdn-livetv2.metube.id/hls/rcti.m3u8
https://cdn-livetv2.metube.id/hls/rcti_480/index.m3u8
4. https://cdn-livetv1.metube.id/hls/trans7.m3u8
https://cdn-livetv1.metube.id/hls/trans7_480/index.m3u8
5. .....
######
| I think there is some indonesian want plugin for this site, Hope someone could help us to make plugin for us. High demand please consider it. Thank You So Much.
@akiwatti
> HTTP 502 bad Gateway
if you send a **User-Agent** and **Origin** http header, it should work
```
streamlink https://cdn-livetv1.metube.id/hls/metrotv.m3u8 best --http-header "Origin=https://www.metube.id" --http-header "User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"
``` | 2018-10-12T00:30:49 |
streamlink/streamlink | 2,127 | streamlink__streamlink-2127 | [
"1055"
] | 7b5f4f775b70281c0970af9048e556258da11582 | diff --git a/src/streamlink/plugin/plugin.py b/src/streamlink/plugin/plugin.py
--- a/src/streamlink/plugin/plugin.py
+++ b/src/streamlink/plugin/plugin.py
@@ -384,6 +384,7 @@ def stream_weight_only(s):
stream_names = filter(stream_weight_only, streams.keys())
sorted_streams = sorted(stream_names, key=stream_weight_only)
+ unfiltered_sorted_streams = sorted_streams
if isinstance(sorting_excludes, list):
for expr in sorting_excludes:
@@ -402,6 +403,11 @@ def stream_weight_only(s):
worst = sorted_streams[0]
final_sorted_streams["worst"] = streams[worst]
final_sorted_streams["best"] = streams[best]
+ elif len(unfiltered_sorted_streams) > 0:
+ best = unfiltered_sorted_streams[-1]
+ worst = unfiltered_sorted_streams[0]
+ final_sorted_streams["worst-unfiltered"] = streams[worst]
+ final_sorted_streams["best-unfiltered"] = streams[best]
return final_sorted_streams
diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py
--- a/src/streamlink_cli/argparser.py
+++ b/src/streamlink_cli/argparser.py
@@ -107,7 +107,7 @@ def build_parser():
help="""
Stream to play.
- Use "best" or "worst" for selecting the highest or lowest available
+ Use ``best`` or ``worst`` for selecting the highest or lowest available
quality.
Fallback streams can be specified by using a comma-separated list:
@@ -523,7 +523,7 @@ def build_parser():
help="""
Stream to play.
- Use "best" or "worst" for selecting the highest or lowest available
+ Use ``best`` or ``worst`` for selecting the highest or lowest available
quality.
Fallback streams can be specified by using a comma-separated list:
@@ -590,13 +590,17 @@ def build_parser():
metavar="STREAMS",
type=comma_list,
help="""
- Fine tune best/worst synonyms by excluding unwanted streams.
+ Fine tune the ``best`` and ``worst`` stream name synonyms by excluding unwanted streams.
+
+ If all of the available streams get excluded, ``best`` and ``worst`` will become
+ inaccessible and new special stream synonyms ``best-unfiltered`` and ``worst-unfiltered``
+ can be used as a fallback selection method.
Uses a filter expression in the format:
[operator]<value>
- Valid operators are >, >=, < and <=. If no operator is specified then
+ Valid operators are ``>``, ``>=``, ``<`` and ``<=``. If no operator is specified then
equality is tested.
For example this will exclude streams ranked higher than "480p":
diff --git a/src/streamlink_cli/constants.py b/src/streamlink_cli/constants.py
--- a/src/streamlink_cli/constants.py
+++ b/src/streamlink_cli/constants.py
@@ -28,7 +28,7 @@
]
PLUGINS_DIR = os.path.expanduser(XDG_CONFIG_HOME + "/streamlink/plugins")
-STREAM_SYNONYMS = ["best", "worst"]
+STREAM_SYNONYMS = ["best", "worst", "best-unfiltered", "worst-unfiltered"]
STREAM_PASSTHROUGH = ["hls", "http", "rtmp"]
__all__ = [
| diff --git a/tests/plugins/testplugin.py b/tests/plugins/testplugin.py
--- a/tests/plugins/testplugin.py
+++ b/tests/plugins/testplugin.py
@@ -37,6 +37,14 @@ def get_category(self):
def _get_streams(self):
if "empty" in self.url:
return
+
+ if "UnsortableStreamNames" in self.url:
+ def gen():
+ for i in range(3):
+ yield "vod", HTTPStream(self.session, "http://test.se/stream")
+
+ return gen()
+
if "NoStreamsError" in self.url:
raise NoStreamsError(self.url)
diff --git a/tests/test_cli_main.py b/tests/test_cli_main.py
--- a/tests/test_cli_main.py
+++ b/tests/test_cli_main.py
@@ -3,8 +3,9 @@
import tempfile
import streamlink_cli.main
-from streamlink_cli.main import resolve_stream_name, check_file_output
+from streamlink_cli.main import resolve_stream_name, format_valid_streams, check_file_output
from streamlink_cli.output import FileOutput
+from streamlink.plugin.plugin import Plugin
import unittest
from tests.mock import Mock, patch
@@ -46,19 +47,71 @@ def test_check_file_output_exists_no(self, sys_exit):
tmpfile.close()
def test_resolve_stream_name(self):
- high = Mock()
- medium = Mock()
- low = Mock()
+ a = Mock()
+ b = Mock()
+ c = Mock()
+ d = Mock()
+ e = Mock()
streams = {
- "low": low,
- "medium": medium,
- "high": high,
- "worst": low,
- "best": high
+ "160p": a,
+ "360p": b,
+ "480p": c,
+ "720p": d,
+ "1080p": e,
+ "worst": b,
+ "best": d,
+ "worst-unfiltered": a,
+ "best-unfiltered": e
}
- self.assertEqual("high", resolve_stream_name(streams, "best"))
- self.assertEqual("low", resolve_stream_name(streams, "worst"))
- self.assertEqual("medium", resolve_stream_name(streams, "medium"))
- self.assertEqual("high", resolve_stream_name(streams, "high"))
- self.assertEqual("low", resolve_stream_name(streams, "low"))
+ self.assertEqual(resolve_stream_name(streams, "unknown"), "unknown")
+ self.assertEqual(resolve_stream_name(streams, "160p"), "160p")
+ self.assertEqual(resolve_stream_name(streams, "360p"), "360p")
+ self.assertEqual(resolve_stream_name(streams, "480p"), "480p")
+ self.assertEqual(resolve_stream_name(streams, "720p"), "720p")
+ self.assertEqual(resolve_stream_name(streams, "1080p"), "1080p")
+ self.assertEqual(resolve_stream_name(streams, "worst"), "360p")
+ self.assertEqual(resolve_stream_name(streams, "best"), "720p")
+ self.assertEqual(resolve_stream_name(streams, "worst-unfiltered"), "160p")
+ self.assertEqual(resolve_stream_name(streams, "best-unfiltered"), "1080p")
+
+ def test_format_valid_streams(self):
+ class FakePlugin:
+ @classmethod
+ def stream_weight(cls, stream):
+ return Plugin.stream_weight(stream)
+ a = Mock()
+ b = Mock()
+ c = Mock()
+
+ streams = {
+ "audio": a,
+ "720p": b,
+ "1080p": c,
+ "worst": b,
+ "best": c
+ }
+ self.assertEqual(
+ format_valid_streams(FakePlugin, streams),
+ ", ".join([
+ "audio",
+ "720p (worst)",
+ "1080p (best)"
+ ])
+ )
+
+ streams = {
+ "audio": a,
+ "720p": b,
+ "1080p": c,
+ "worst-unfiltered": b,
+ "best-unfiltered": c
+ }
+ self.assertEqual(
+ format_valid_streams(FakePlugin, streams),
+ ", ".join([
+ "audio",
+ "720p (worst-unfiltered)",
+ "1080p (best-unfiltered)"
+ ])
+ )
diff --git a/tests/test_session.py b/tests/test_session.py
--- a/tests/test_session.py
+++ b/tests/test_session.py
@@ -99,12 +99,23 @@ def test_plugin_stream_types(self):
self.assertTrue(isinstance(streams["480p"], RTMPStream))
self.assertTrue(isinstance(streams["480p_http"], HTTPStream))
- def test_plugin_stream_sorted_excludes(self):
+ def test_plugin_stream_sorting_excludes(self):
channel = self.session.resolve_url("http://test.se/channel")
- streams = channel.streams(sorting_excludes=["1080p", "3000k"])
+ streams = channel.streams(sorting_excludes=[])
self.assertTrue("best" in streams)
self.assertTrue("worst" in streams)
+ self.assertFalse("best-unfiltered" in streams)
+ self.assertFalse("worst-unfiltered" in streams)
+ self.assertTrue(streams["worst"] is streams["350k"])
+ self.assertTrue(streams["best"] is streams["1080p"])
+
+ streams = channel.streams(sorting_excludes=["1080p", "3000k"])
+ self.assertTrue("best" in streams)
+ self.assertTrue("worst" in streams)
+ self.assertFalse("best-unfiltered" in streams)
+ self.assertFalse("worst-unfiltered" in streams)
+ self.assertTrue(streams["worst"] is streams["350k"])
self.assertTrue(streams["best"] is streams["1500k"])
streams = channel.streams(sorting_excludes=[">=1080p", ">1500k"])
@@ -113,6 +124,24 @@ def test_plugin_stream_sorted_excludes(self):
streams = channel.streams(sorting_excludes=lambda q: not q.endswith("p"))
self.assertTrue(streams["best"] is streams["3000k"])
+ streams = channel.streams(sorting_excludes=lambda q: False)
+ self.assertFalse("best" in streams)
+ self.assertFalse("worst" in streams)
+ self.assertTrue("best-unfiltered" in streams)
+ self.assertTrue("worst-unfiltered" in streams)
+ self.assertTrue(streams["worst-unfiltered"] is streams["350k"])
+ self.assertTrue(streams["best-unfiltered"] is streams["1080p"])
+
+ channel = self.session.resolve_url("http://test.se/UnsortableStreamNames")
+ streams = channel.streams()
+ self.assertFalse("best" in streams)
+ self.assertFalse("worst" in streams)
+ self.assertFalse("best-unfiltered" in streams)
+ self.assertFalse("worst-unfiltered" in streams)
+ self.assertTrue("vod" in streams)
+ self.assertTrue("vod_alt" in streams)
+ self.assertTrue("vod_alt2" in streams)
+
def test_plugin_support(self):
channel = self.session.resolve_url("http://test.se/channel")
streams = channel.streams()
| Fallback selection for --stream-sorting-excludes
### Checklist
- [ ] This is a bug report.
- [x] This is a feature request.
- [ ] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
### Description
Related issue:
https://github.com/streamlink/streamlink-twitch-gui/issues/481
In certain situations, the usage of `--stream-sorting-excludes` can lead to an empty stream selection. This is an issue for applications which try to map the available streams to a custom list of qualities.
The Streamlink Twitch GUI needs to do this stream quality mapping because of Twitch's inconsistent quality naming. This is an example of trying to find the "low" quality:
```
# available: 160p, 360p, 480p, 720p, 1080p
streamlink --stream-sorting-excludes ">360p" twitch.tv/CHANNEL low,best
# will open 360p
# available: low, medium, high, source
streamlink --stream-sorting-excludes ">360p" twitch.tv/CHANNEL low,best
# will open low
# available: 720p
streamlink --stream-sorting-excludes ">360p" twitch.tv/CHANNEL low,best
# returns an empty selection (channel doesn't have re-encoded qualities)
```
Having a fallback parameter (eg. `--stream-sorting-excludes-fallback`) with a list of streams that will be opened if no matching stream could be found would fix this situation.
Another solution could be having a different notation in the actual quality selection, but this is probably a bit too complex.
```
# 1. try to find the quality labeled "medium"
# 2. look for qualities named by video resolution matching the defined range
# 3. fall back to lower qualities
# 4. use any available quality
streamlink twitch.tv/CHANNEL "medium||>360p&&<=480p||<=360p||best"
streamlink twitch.tv/CHANNEL "medium,>360p<=480p,<=360p,best"
```
| To be honest I prefer the complex solution, let's call it more complete - logical operators would be nice :-) | 2018-10-22T12:13:43 |
streamlink/streamlink | 2,130 | streamlink__streamlink-2130 | [
"2125"
] | b21df07689023f1f6fc79b228da4faa76c617667 | diff --git a/src/streamlink/plugins/tvibo.py b/src/streamlink/plugins/tvibo.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/tvibo.py
@@ -0,0 +1,34 @@
+import logging
+import re
+
+from streamlink.plugin import Plugin
+from streamlink.stream import HLSStream
+
+log = logging.getLogger(__name__)
+
+
+class Tvibo(Plugin):
+
+ _url_re = re.compile(r"https?://player\.tvibo\.com/\w+/(?P<id>\d+)")
+ _api_url = "http://panel.tvibo.com/api/player/streamurl/{id}"
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_streams(self):
+ channel_id = self._url_re.match(self.url).group("id")
+
+ api_response = self.session.http.get(
+ self._api_url.format(id=channel_id),
+ acceptable_status=(200, 404))
+
+ data = self.session.http.json(api_response)
+ log.trace("{0!r}".format(data))
+ if data.get("st"):
+ yield "source", HLSStream(self.session, data["st"])
+ elif data.get("error"):
+ log.error(data["error"]["message"])
+
+
+__plugin__ = Tvibo
| diff --git a/tests/plugins/test_tvibo.py b/tests/plugins/test_tvibo.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_tvibo.py
@@ -0,0 +1,22 @@
+import unittest
+
+from streamlink.plugins.tvibo import Tvibo
+
+
+class TestPluginTvibo(unittest.TestCase):
+ def test_can_handle_url(self):
+ should_match = [
+ 'http://player.tvibo.com/aztv/5929820',
+ 'http://player.tvibo.com/aztv/6858270/',
+ 'http://player.tvibo.com/aztv/3977238/',
+ ]
+ for url in should_match:
+ self.assertTrue(Tvibo.can_handle_url(url))
+
+ def test_can_handle_url_negative(self):
+ should_not_match = [
+ 'http://www.idmantv.az/',
+ 'https://www.twitch.tv/twitch'
+ ]
+ for url in should_not_match:
+ self.assertFalse(Tvibo.can_handle_url(url))
| Azerbaycan stations
## Feature Request
- [x ] This is a feature request and I have read the contribution guidelines.
### Description
I want see the LiveStream over Streamlink Plugin
### Expected / Actual behavior
The livestreams can be played on the page http://www.idmantv.az via the Firefox browser.
The site includes the broadcasters AZTV, Idman TV and Medeniyet TV
About the VLC player, it is not possible because the transmitter permanently tokens changes, the Streamlinkplugin should be able to handle it.
### Additional comments, screenshots, etc.
![idman tv](https://user-images.githubusercontent.com/36420635/47272680-7bdb3700-d589-11e8-99ec-39b7a683bedc.JPG)
AZ TV
http://185.102.219.82/5929820/tracks-v1a1/index.m3u8?token=
http://player.tvibo.com/aztv/5929820
Medeniyet
http://185.102.219.82/6858270/tracks-v1a1/index.m3u8?token=
http://player.tvibo.com/aztv/6858270/
Idman TV
http://185.102.219.82/3977238/tracks-v1a1/index.m3u8?token=
http://player.tvibo.com/aztv/3977238/
| Are there different URLs for these three channels? How would a user choose which channel to watch?
Also, if you extract `.m3u8` URL from your browser, running `streamlink http://185.102.219.82/6858270/index.m3u8?token=... best` can play the stream without dropping.
in first Post now with the stream links | 2018-10-23T16:59:19 |
streamlink/streamlink | 2,134 | streamlink__streamlink-2134 | [
"2132"
] | c1a2962d992be93da495aa82627b9a736377380f | diff --git a/src/streamlink/plugins/huomao.py b/src/streamlink/plugins/huomao.py
--- a/src/streamlink/plugins/huomao.py
+++ b/src/streamlink/plugins/huomao.py
@@ -4,8 +4,8 @@
scraping the HTML and JS of one of Huomaos mobile webpages.
When viewing a stream on huomao.com, the base URL references a room_id. This
-room_id is mapped one-to-one to a stream_id which references the actual .flv
-video. Both stream_id, stream_url and stream_quality can be found in the
+room_id is mapped one-to-one to a stream_id which references the actual .m3u8
+file. Both stream_id, stream_url and stream_quality can be found in the
HTML and JS source of the mobile_page. Since one stream can occur in many
different qualities, we scrape all stream_url and stream_quality occurrences
and return each option to the user.
@@ -14,7 +14,7 @@
import re
from streamlink.plugin import Plugin
-from streamlink.stream import HTTPStream
+from streamlink.stream import HLSStream
# URL pattern for recognizing inputed Huomao.tv / Huomao.com URL.
url_re = re.compile(r"""
@@ -35,18 +35,15 @@
# <input id="html_stream" value="efmrCH" type="hidden">
stream_id_pattern = re.compile(r'id=\"html_stream\" value=\"(?P<stream_id>\w+)\"')
-# Pattern for extracting each stream_url, stream_quality_url and a prettified
+# Pattern for extracting each stream_url and
# stream_quality_name used for quality naming.
#
# Example from HTML:
-# "2: 'http://live-ws.huomaotv.cn/live/'+stream+'_720/playlist.m3u8'"
+# src="http://live-ws-hls.huomaotv.cn/live/<stream_id>_720/playlist.m3u8"
stream_info_pattern = re.compile(r"""
- [1-9]:
- \s+
- '(?P<stream_url>(?:\w|\.|:|-|/)+)
- '\+stream\+'
- (?P<stream_quality_url>_?(?P<stream_quality_name>\d*))
- /playlist.m3u8'
+ (?P<stream_url>(?:[\w\/\.\-:]+)
+ \/[^_\"]+(?:_(?P<stream_quality_name>\d+))
+ ?/playlist.m3u8)
""", re.VERBOSE)
@@ -65,11 +62,11 @@ def get_stream_id(self, html):
return stream_id.group("stream_id")
def get_stream_info(self, html):
- """Returns a nested list of different stream options.
+ """
+ Returns a nested list of different stream options.
- Each entry in the list will contain a stream_url, stream_quality_url
- and stream_quality_name for each stream occurrence that was found in
- the JS.
+ Each entry in the list will contain a stream_url and stream_quality_name
+ for each stream occurrence that was found in the JS.
"""
stream_info = stream_info_pattern.findall(html)
@@ -80,8 +77,8 @@ def get_stream_info(self, html):
# list and reassigning.
stream_info_list = []
for info in stream_info:
- if not info[2]:
- stream_info_list.append([info[0], info[1], "source"])
+ if not info[1]:
+ stream_info_list.append([info[0], "source"])
else:
stream_info_list.append(list(info))
@@ -95,8 +92,8 @@ def _get_streams(self):
streams = {}
for info in stream_info:
- streams[info[2]] = HTTPStream(self.session,
- info[0] + stream_id + info[1] + ".flv")
+ if stream_id in info[0]:
+ streams[info[1]] = HLSStream(self.session, info[0])
return streams
| diff --git a/tests/plugins/test_huomao.py b/tests/plugins/test_huomao.py
--- a/tests/plugins/test_huomao.py
+++ b/tests/plugins/test_huomao.py
@@ -15,15 +15,12 @@ def setUp(self):
# room_id = 123456
# stream_id = 9qsvyF24659
# stream_url = http://live-ws.huomaotv.cn/live/
- # stream_quality = source, _720 and _480
# stream_quality_name = source, 720 and 480
self.mock_html = """
<input id="html_stream" value="9qsvyF24659" type="hidden">
- <!-- urls:{-->
- <!-- 1: 'http://live-ws.huomaotv.cn/live/'+stream+'/playlist.m3u8',-->
- <!-- 2: 'http://live-ws.huomaotv.cn/live/'+stream+'_720/playlist.m3u8',-->
- <!-- 3: 'http://live-ws.huomaotv.cn/live/'+stream+'_480/playlist.m3u8'-->
- <!-- },-->
+ <source src="http://live-ws-hls.huomaotv.cn/live/9qsvyF24659/playlist.m3u8">
+ <source src="http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_720/playlist.m3u8">
+ <source src="http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_480/playlist.m3u8">
"""
# Create a mock Huomao object.
@@ -43,9 +40,9 @@ def test_get_stream_quality(self):
# Assert that the stream_url, stream_quality and stream_quality_name
# is correctly extracted from the mock HTML.
self.assertEqual(self.mock_huomao.get_stream_info(self.mock_html), [
- ["http://live-ws.huomaotv.cn/live/", "", "source"],
- ["http://live-ws.huomaotv.cn/live/", "_720", "720"],
- ["http://live-ws.huomaotv.cn/live/", "_480", "480"]
+ ["http://live-ws-hls.huomaotv.cn/live/9qsvyF24659/playlist.m3u8", "source"],
+ ["http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_720/playlist.m3u8", "720"],
+ ["http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_480/playlist.m3u8", "480"]
])
def test_can_handle_url(self):
| Huomao plugin not work
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
I found huomao plugin seems not work, i can use browser to watch stream but
streamlink says no playable stream
<!-- Explain the plugin issue as thoroughly as you can. -->
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. https://www.huomao.com/9755
2. https://www.huomao.com/777777
3. https://www.huomao.com/888
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
[cli][info] Found matching plugin huomao for URL https://www.huomao.com/888
[plugin.huomao][error] Failed to extract stream_info.
error: No playable streams found on this URL: https://www.huomao.com/888
```
| 2018-10-23T20:47:35 |
|
streamlink/streamlink | 2,160 | streamlink__streamlink-2160 | [
"2159"
] | 649f483ab3b4906a6c4b352c0b21d08efb40d700 | diff --git a/src/streamlink/plugins/skai.py b/src/streamlink/plugins/skai.py
--- a/src/streamlink/plugins/skai.py
+++ b/src/streamlink/plugins/skai.py
@@ -3,20 +3,15 @@
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
-YOUTUBE_URL = "https://www.youtube.com/watch?v={0}"
-_url_re = re.compile(r'http(s)?://www\.skai.gr/.*')
-_youtube_id = re.compile(r'<span\s+itemprop="contentUrl"\s+href="(.*)"></span>', re.MULTILINE)
-_youtube_url_schema = validate.Schema(
- validate.all(
- validate.transform(_youtube_id.search),
- validate.any(
- None,
- validate.all(
- validate.get(1),
- validate.text
- )
- )
- )
+
+_url_re = re.compile(r'http(s)?://www\.skai(?:tv)?.gr/.*')
+_api_url = "http://www.skaitv.gr/json/live.php"
+_api_res_schema = validate.Schema(validate.all(
+ validate.get("now"),
+ {
+ "livestream": validate.url()
+ },
+ validate.get("livestream"))
)
@@ -26,9 +21,10 @@ def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
- channel_id = self.session.http.get(self.url, schema=_youtube_url_schema)
- if channel_id:
- return self.session.streams(YOUTUBE_URL.format(channel_id))
+ api_res = self.session.http.get(_api_url)
+ yt_url = self.session.http.json(api_res, schema=_api_res_schema)
+ if yt_url:
+ return self.session.streams(yt_url)
__plugin__ = Skai
| diff --git a/tests/plugins/test_skai.py b/tests/plugins/test_skai.py
--- a/tests/plugins/test_skai.py
+++ b/tests/plugins/test_skai.py
@@ -7,6 +7,7 @@ class TestPluginSkai(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'http://www.skai.gr/player/tvlive/',
+ 'http://www.skaitv.gr/live',
]
for url in should_match:
self.assertTrue(Skai.can_handle_url(url))
| Skai plugin broken
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
Skai plugin is broken since yesterday, but actually it is no longer needed because they provide a lot more stable stream (they don't change stream three or so times a day). **Imho it can be removed.**
New live url as follows:
http://www.skaitv.gr/live
| 2018-11-09T19:15:05 |
|
streamlink/streamlink | 2,171 | streamlink__streamlink-2171 | [
"2170",
"2170"
] | 649f483ab3b4906a6c4b352c0b21d08efb40d700 | diff --git a/src/streamlink/plugins/ine.py b/src/streamlink/plugins/ine.py
--- a/src/streamlink/plugins/ine.py
+++ b/src/streamlink/plugins/ine.py
@@ -23,7 +23,7 @@ class INE(Plugin):
validate.all(
validate.get(1),
validate.transform(json.loads),
- {"playlist": str},
+ {"playlist": validate.text},
validate.get("playlist")
)
)
| INE Plugin
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [X] This is a plugin issue and I have read the contribution guidelines.
### Description
The INE plugin doesn't appear to work on any videos I try.
### Reproduction steps / Explicit stream URLs to test
Try do download a video
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
streamlink https://streaming.ine.com/play/419cdc1a-a4a8-4eba-b8b3-5dda324daa94/day-1-part-1#/ --http-cookie laravel_session=<Removed> --loglevel debug
[cli][debug] OS: macOS 10.14.1
[cli][debug] Python: 2.7.10
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.54.0)
[cli][info] Found matching plugin ine for URL https://streaming.ine.com/play/419cdc1a-a4a8-4eba-b8b3-5dda324daa94/day-1-part-1#/
[plugin.ine][debug] Found video ID: 419cdc1a-a4a8-4eba-b8b3-5dda324daa94
[plugin.ine][debug] Loading player JS: https://content.jwplatform.com/players/yyYIR4k9-p4NBeNN0.js?exp=1543579899&sig=5e0058876669be2e2aafc7e52d067b78
error: Unable to validate result: <_sre.SRE_Match object at 0x106564dc8> does not equal None or Unable to validate key 'playlist': Type of u'//content.jwplatform.com/v2/media/yyYIR4k9?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZWNvbW1lbmRhdGlvbnNfcGxheWxpc3RfaWQiOiJ5cHQwdDR4aCIsInJlc291cmNlIjoiL3YyL21lZGlhL3l5WUlSNGs5IiwiZXhwIjoxNTQzNTc5OTIwfQ.pHEgoDYzc219-S_slfWRhyEoCsyCZt74BiL8RNs5IJ8' should be 'str' but is 'unicode'
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
INE Plugin
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [X] This is a plugin issue and I have read the contribution guidelines.
### Description
The INE plugin doesn't appear to work on any videos I try.
### Reproduction steps / Explicit stream URLs to test
Try do download a video
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
streamlink https://streaming.ine.com/play/419cdc1a-a4a8-4eba-b8b3-5dda324daa94/day-1-part-1#/ --http-cookie laravel_session=<Removed> --loglevel debug
[cli][debug] OS: macOS 10.14.1
[cli][debug] Python: 2.7.10
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.54.0)
[cli][info] Found matching plugin ine for URL https://streaming.ine.com/play/419cdc1a-a4a8-4eba-b8b3-5dda324daa94/day-1-part-1#/
[plugin.ine][debug] Found video ID: 419cdc1a-a4a8-4eba-b8b3-5dda324daa94
[plugin.ine][debug] Loading player JS: https://content.jwplatform.com/players/yyYIR4k9-p4NBeNN0.js?exp=1543579899&sig=5e0058876669be2e2aafc7e52d067b78
error: Unable to validate result: <_sre.SRE_Match object at 0x106564dc8> does not equal None or Unable to validate key 'playlist': Type of u'//content.jwplatform.com/v2/media/yyYIR4k9?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZWNvbW1lbmRhdGlvbnNfcGxheWxpc3RfaWQiOiJ5cHQwdDR4aCIsInJlc291cmNlIjoiL3YyL21lZGlhL3l5WUlSNGs5IiwiZXhwIjoxNTQzNTc5OTIwfQ.pHEgoDYzc219-S_slfWRhyEoCsyCZt74BiL8RNs5IJ8' should be 'str' but is 'unicode'
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2018-11-16T13:08:59 |
||
streamlink/streamlink | 2,182 | streamlink__streamlink-2182 | [
"2172"
] | 30043408c74ddbb152e694b5afe1f185e6664b26 | diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -45,11 +45,11 @@ class BBCiPlayer(Plugin):
mediator_schema = validate.Schema(
{
- "episode": {
+ "appStoreState": {
"versions": [{"id": validate.text}]
}
},
- validate.get("episode"), validate.get("versions"), validate.get(0),
+ validate.get("appStoreState"), validate.get("versions"), validate.get(0),
validate.get("id")
)
mediaselector_schema = validate.Schema(
| BBC iPlayer plugin broken (can no longer validate JSON)
<!--
Thanks for reporting a bug!
USE THE TEMPLATE. Otherwise your bug report may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed bug reports:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Bug Report
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a bug report and I have read the contribution guidelines.
### Description
<!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. -->
As of 15th Nov 2018, attempting to stream any bbc iplayer url gives: "error: Unable to validate JSON" (see full log below). It would seem the BBC has changed the format of their JSON output, because everything worked fine up until that day.
### Expected / Actual behavior
<!-- What do you expect to happen, and what is actually happening? -->
It should stream the content, instead of giving an error.
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
`streamlink --bbciplayer-username 'user' --bbciplayer-password 'pass' https://www.bbc.co.uk/iplayer/episode/b0074mhp/the-blue-planet-1-introduction`
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a bug report!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
$ streamlink --bbciplayer-username 'user' --bbciplayer-password 'pass' https://www.bbc.co.uk/iplayer/episode/b0074mhp/the-blue-planet-1-introduction
[cli][info] Found matching plugin bbciplayer for URL https://www.bbc.co.uk/iplayer/episode/b0074mhp/the-blue-planet-1-introduction
[plugin.bbciplayer][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
error: Unable to validate JSON: Key 'episode' not found in {'appBundleSrc': 'https://iplayer-web.files.bbci.co.uk/iplayer-web-app-playback-v2/1.0.0-216/js/app.bundle.js', 'appStoreState': {'translations': {'page_title_version_ad': 'Audio Described', 'page_title_version_sign': 'Signed', 'related_episodes_this_episode_label': 'This episode', 'related_episodes_title': 'More episodes', 'related_episodes_view_all': 'View all', 'msi_modal_title': "You need to sign in. It's quick & easy.", 'msi_modal_text': "And we'll keep you signed in.", 'msi_modal_why_sign_in': 'Why sign in to the BBC?', 'duration': 'Duration', 'next_episode': 'Next episode', 'next_recommended': 'Recommended for you', 'cancel': 'Cancel', 'cancel_autoplay': 'Cancel autoplay of %s', 'programme_ended_aria_label': 'The current programme has ended. %s will autoplay in %s seconds. Activate the cancel button to stop it playing', 'showhide_button_show': 'Show more', 'showhide_button_hide': 'Hide', 'showhide_button_aria_show': 'Show more programmes', 'showhide_button_aria_hide': 'Return to the player', 'skip_trailer': 'Skip Trailer', 'restart_programme': 'Restart programme', 'accessibility_banner_sign': 'This is a Signed version of this programme.', 'accessibility_banner_sign_non_available': "The non-Signed version isn't available.", 'accessibility_banner_sign_turn_off': 'Turn off Sign Language', 'accessibility_banner_ad': 'This is an Audio Described version of this programme.', 'accessibility_banner_ad_non_available': "The non-Audio Described version isn't available.", 'accessibility_banner_ad_turn_off': 'Turn off Audio Description', 'accessibility_banner_find_out_why': 'Find out why', 'expand_synopsis': 'More', 'collapse_synopsis': 'Less', 'first_shown': 'First shown', 'version_button_ad': 'Audio Described', 'version_button_ad_aria': 'Watch Audio Described version', 'version_button_ad_turn_off_aria': 'Watch non-Audio Described version', 'version_button_sign': 'Sign Language', 'version_button_sign_aria': 'Watch Sign Language version', 'version_button_sign_turn_off_aria': 'Watch non-Sign Language version', 'learn_more_about_availability': 'Learn more about availability', 'download': 'Download', 'add': 'Add', 'added': 'Added', 'remove': 'Remove', 'added_banner_message': ':episodeTitle has been added to', 'my_programmes': 'My Programmes', 'download_not_available_why_aria_label': "Why can't I download?", 'download_modal_title': 'Programme Downloads', 'download_modal_have_you_installed': 'Have you installed BBC iPlayer Downloads?', 'download_modal_help_faq': 'Help & FAQ', 'download_button_hd': 'Yes, download in HD', 'download_button_sd': 'Yes, download in SD', 'download_button_install_now': 'No, install now', 'rrc_why_aria_label': 'More information about revisions, revocations and corrections', 'programme_footer_link_label': 'Programme links', 'programme_footer_link_programme_website': 'Programme website', 'programme_footer_link_credits': 'Credits', 'programme_footer_link_more_from_bbc_three': 'More from BBC Three', 'preroll_available_now': 'Available now on BBC iPlayer', 'preroll_coming_soon': 'Coming soon on BBC iPlayer', 'foreign_region_banner': 'BBC iPlayer only works in the UK. Sorry, it’s due to rights issues.', 'foreign_region_banner_advice': "In the UK? Here's some advice."}, 'episode': {'status': 'success', 'resumeOffset': None, 'added': None, 'addSuccess': None, 'id': 'b0074mhp', 'live': False, 'title': 'The Blue Planet', 'subtitle': '1. Introduction', 'synopses': {'large': 'Although 70 per cent of our planet is covered by water, the oceans and many of their inhabitants - such as the blue whale - remain an unexplored mystery. This edition travels to the very depths of the seas to reveal a spectacular variety of life - from alien monsters of the deep to pack-hunting killer whales attacking a grey whale calf.', 'small': 'This travels to the very depths of the seas, to reveal a spectacular variety of life.', 'medium': 'David Attenborough narrates a natural history of the oceans. We travel to the depths of the seas to reveal a spectacular variety of life, some never filmed before.', 'editorial': "Giant creatures, alien lifeforms, microscopic colonies - it's all here under the waves."}, 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p06mnw3k.jpg'}, 'masterBrand': {'id': 'bbc_one', 'titles': {'large': 'BBC One', 'small': 'BBC One', 'medium': 'BBC One'}, 'ident_id': 'p06g87jc', 'attribution': 'bbc_one'}, 'requiresSignIn': True, 'tleoId': 'b008044n', 'tleoType': 'series', 'guidance': False, 'labels': {'category': 'Science & Nature'}, 'hasCredits': True, 'currentVersion': 'standard'}, 'relatedEpisodes': {'episodes': [{'id': 'b0074mhp', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p06mnw3k.jpg'}, 'subtitle': '1. Introduction', 'synopses': {'large': 'Although 70 per cent of our planet is covered by water, the oceans and many of their inhabitants - such as the blue whale - remain an unexplored mystery. This edition travels to the very depths of the seas to reveal a spectacular variety of life - from alien monsters of the deep to pack-hunting killer whales attacking a grey whale calf.', 'small': 'This travels to the very depths of the seas, to reveal a spectacular variety of life.', 'medium': 'David Attenborough narrates a natural history of the oceans. We travel to the depths of the seas to reveal a spectacular variety of life, some never filmed before.', 'editorial': "Giant creatures, alien lifeforms, microscopic colonies - it's all here under the waves."}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, {'id': 'b0074mjc', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr2wn.jpg'}, 'subtitle': '2. The Deep', 'synopses': {'large': 'More people have walked on the moon than have travelled to the very depths of the deep ocean. David Attenborough journeys into the abyss to show us, for the very first time, strange creatures straight out of the film Alien, many of which are new to science. Terrifying fish with massive teeth that eat prey twice their size and weird jellyfish that flash in the darkness. And deep sea sharks never filmed before and submerged mountain ranges and volcanoes far larger than anything on land.', 'small': 'David Attenborough looks at the strange creatures that live in the depths of the ocean.', 'medium': 'David Attenborough narrates a natural history of the oceans to uncover the strange, otherworldly creatures living in the depths of the ocean.'}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}, {'duration': {'text': '58 mins'}, 'kind': 'audio-described', 'download': False, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, {'id': 'b0080pjz', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr3ds.jpg'}, 'subtitle': '3. Open Ocean', 'synopses': {'large': "This programme focuses on the predatory skills of some of the most charismatic hunters found on the planet: whales, dolphins, tuna, shark and rapier-nosed billfish. The open ocean is unimaginably immense - it covers more than 360 million square kilometres of the Earth's surface. Much of this huge expanse of seawater is marine desert with virtually no sign of life. Yet the fastest and most powerful survive, playing a deadly game of hide-and-seek with their prey. This charts how they track down prey in the seemingly featureless seas, following the extraordinary life of yellowfin tuna from a minute egg to a 200 kilogram, voracious predatory giant.", 'small': 'Looking at the hunting skills of whales, dolphins, tuna, shark and rapier-nosed billfish.', 'medium': "David Attenborough narrates a natural history of the oceans. The deadly game of hide-and-seek played by the sea's charismatic hunters - whales, shark and billfish."}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}, {'duration': {'text': '58 mins'}, 'kind': 'audio-described', 'download': False, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, {'id': 'b00818zy', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr5cm.jpg'}, 'subtitle': '4. Frozen Seas', 'synopses': {'large': 'A look at the survival techniques of creatures that endure the harsh conditions of the Arctic and Antarctic. For animals at both poles, life is dominated by the annual retreat and advance of the freezing sea ice and the challenge of surviving winters when temperatures drop.\n\nIn the Arctic the polar bear is the top predator, catching seals on the ice and forcing seabirds to nest high up on cliffs. In Antarctica the flightless penguins have no ground-based predators to deal with but lurking in the water is the constant threat from leopard seals.\n\nNarrated by David Attenborough.', 'small': 'A look at the survival techniques of creatures in the Arctic and Antarctic.', 'medium': 'A natural history of the oceans. A look at the survival techniques of creatures that endure the harsh conditions of the Arctic and Antarctic.'}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Nature'}}], 'count': 9}, 'recommendations': None, 'versions': [{'id': 'b001fkdj', 'kind': 'original', 'download': True, 'hd': False, 'guidance': False, 'rrc': False, 'events': [{'name': 'started', 'offset': 30, 'system': 'uas'}, {'name': 'iplxp-ep-started', 'offset': 30, 'system': 'optimizely'}, {'name': 'iplxp-ep-started', 'offset': 30, 'system': 'dax'}, {'name': 'iplxp-ep-watched', 'offset': 3123, 'system': 'optimizely'}, {'name': 'iplxp-ep-watched', 'offset': 3123, 'system': 'dax'}, {'name': 'ended', 'offset': 3380, 'system': 'uas'}], 'firstBroadcast': '9pm 12 Sep 2001', 'duration': {'text': '58 mins', 'seconds': 3470}, 'availability': {'remaining': {'text': 'Available for 4 months'}}, 'creditsStart': 3464, 'startTime': None, 'endTime': 1554278400}], 'player': {'status': 'loading', 'playingState': None, 'volume': 0.6, 'subtitles': False, 'continuousPlay': None}, 'config': {'staticAssetsPath': 'https://iplayer-web.files.bbci.co.uk/iplayer-web-app-playback-v2/1.0.0-216', 'host': 'www.bbc.co.uk', 'iblBaseUrl': 'https://ibl.api.bbc.co.uk/ibl/v1', 'tipBaseUrl': 'https://iplayer-web.files.bbci.co.uk/iplayer-web-tip-playback/7.1.1'}, 'stats': {'countername': 'iplayer.tv.episode.the_blue_planet.1_introduction.b0074mhp.page', 'firedEvents': []}, 'id': {'status': 'green', 'signedIn': False, 'ageBracket': None, 'enablePersonalisation': False, 'ctaMarkup': "%3Cp%20class%3D%22id4-cta%22%20id%3D%22id4-cta-d73a0a66-62f8-49be-bfe8-b293b61f035e%22%3E%3Cspan%20class%3D%22id5-cta%20id4-cta-size-medium%20id4-cta-color-mixed%20id4-cta-medium-mixed%22%3E%3Ca%20href%3D%22https%3A%2F%2Fsession.bbc.co.uk%2Fsession%3Fptrt%3Dhttps%253A%252F%252Fwww.bbc.co.uk%252Fiplayer%252Fepisode%252Fb0074mhp%252Fthe-blue-planet-1-introduction%26context%3Dtvandiplayer%26userOrigin%3Dtvandiplayer%22%20class%3D%22id4-cta-signin%20id4-cta-button%22%3ESign%20in%3C%2Fa%3E%3Cspan%20class%3D%22id4-cta-with%22%3E%20to%20the%20BBC%2C%3C%2Fspan%3E%20or%20%3Ca%20href%3D%22https%3A%2F%2Fsession.bbc.co.uk%2Fsession%3Faction%3Dregister%26ptrt%3Dhttps%253A%252F%252Fwww.bbc.co.uk%252Fiplayer%252Fepisode%252Fb0074mhp%252Fthe-blue-planet-1-introduction%26context%3Dtvandiplayer%26userOrigin%3Dtvandiplayer%22%20class%3D%22id4-cta-register%22%3ERegister%3C%2Fa%3E%3Cscript%20type%3D%22text%2Fjavascript%22%3Eif%20(require.s.contexts._.config.paths%5B'idcta-v2'%5D)%20%7Brequire(%5B'idcta-v2%2Fidcta-1'%5D%2C%20function(idcta)%20%7Bif%20(idcta%20%26%26%20typeof%20idcta.addUserOrigin%20%3D%3D%3D%20'function')%20%7Bidcta.addUserOrigin('id4-cta-d73a0a66-62f8-49be-bfe8-b293b61f035e')%3B%7D%7D)%3B%7D%3C%2Fscript%3E%3C%2Fspan%3E%3C%2Fp%3E%3Cscript%20type%3D%22text%2Fjavascript%22%3Erequire(%5B'idcta-v2%2Fidcta-1'%5D%2C%20function(idcta)%20%7Bnew%20idcta.Cta(%7Bid%3A%20'id4-cta-d73a0a66-62f8-49be-bfe8-b293b61f035e'%2C%20states%3A%20%7B%7D%2C%20policyname%3A%20''%7D)%3B%7D)%3B%3C%2Fscript%3E"}, 'user': {'hasPolyfills': None, 'supportsDownloads': None, 'isForeignRegion': None}, 'nextEpisode': {'id': 'b0074mjc', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr2wn.jpg'}, 'subtitle': '2. The Deep', 'synopses': {'large': 'More people have walked on the moon than have travelled to the very depths of the deep ocean. David Attenborough journeys into the abyss to show us, for the very first time, strange creatures straight out of the film Alien, many of which are new to science. Terrifying fish with massive teeth that eat prey twice their size and weird jellyfish that flash in the darkness. And deep sea sharks never filmed before and submerged mountain ranges and volcanoes far larger than anything on land.', 'small': 'David Attenborough looks at the strange creatures that live in the depths of the ocean.', 'medium': 'David Attenborough narrates a natural history of the oceans to uncover the strange, otherworldly creatures living in the depths of the ocean.'}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}, {'duration': {'text': '58 mins'}, 'kind': 'audio-described', 'download': False, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, 'journey': {'status': 'success'}, 'modal': {'msi': False, 'download': False}, 'preroll': None, 'variants': {'iplxp_pb15_trailers': None}}}
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| @kachelaqa I'm not sure what the difference is in how they detect the video, but I just tried this application and the Dr Who episode I was after showed the error you described with Streamlink but could be downloaded via get_iplayer.
https://github.com/get-iplayer/get_iplayer
Doesn't seem quite as efficient as this ... but hey it's working!
@hogarthj That isn't really relevant, because get_iplayer doesn't support streaming any more. I only use streamlink for streaming iplayer content, so this bug is a complete show-stopper for me.
@kachelaqa can you include a debug log? Add `-l debug` to you command, to help debug/reproduce your issue. Thanks.
@beardypig Sorry - I thought I'd done that. Does that mean you weren't able to reproduce the problem?
**LOG OUTPUT**:
```
[cli][debug] OS: Linux-4.19.2-arch1-1-ARCH-x86_64-with-arch
[cli][debug] Python: 3.7.1
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.20.1), Socks(1.6.7), Websocket(0.54.0)
[cli][info] Found matching plugin bbciplayer for URL https://www.bbc.co.uk/iplayer/episode/b0074mhp/the-blue-planet-1-introduction
[cli][debug] Plugin specific arguments:
[cli][debug] [email protected] (username)
[cli][debug] --bbciplayer-password=******** (password)
[plugin.bbciplayer][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
[plugin.bbciplayer][debug] Loading streams for episode: b0074mhp
[plugin.bbciplayer][debug] Looking for vpid on https://www.bbc.co.uk/iplayer/episode/b0074mhp/the-blue-planet-1-introduction
error: Unable to validate JSON: Key 'episode' not found in {'appBundleSrc': 'https://iplayer-web.files.bbci.co.uk/iplayer-web-app-playback-v2/1.0.0-245/js/app.bundle.js', 'appStoreState': {'translations': {'page_title_version_ad': 'Audio Described', 'page_title_version_sign': 'Signed', 'related_episodes_this_episode_label': 'This episode', 'related_episodes_title': 'More episodes', 'related_episodes_view_all': 'View all', 'msi_modal_title': "You need to sign in. It's quick & easy.", 'msi_modal_text': "And we'll keep you signed in.", 'msi_modal_why_sign_in': 'Why sign in to the BBC?', 'childrens_modal_why_sign_in': 'Why sign in to the BBC?', 'duration': 'Duration', 'next_episode': 'Next episode', 'next_recommended': 'Recommended for you', 'cancel': 'Cancel', 'cancel_autoplay': 'Cancel autoplay of %s', 'programme_ended_aria_label': 'The current programme has ended. %s will autoplay in %s seconds. Activate the cancel button to stop it playing', 'showhide_button_show': 'Show more', 'showhide_button_hide': 'Hide', 'showhide_button_aria_show': 'Show more programmes', 'showhide_button_aria_hide': 'Return to the player', 'skip_trailer': 'Skip Trailer', 'restart_programme': 'Restart programme', 'accessibility_banner_sign': 'This is a Signed version of this programme.', 'accessibility_banner_sign_non_available': "The non-Signed version isn't available.", 'accessibility_banner_sign_turn_off': 'Turn off Sign Language', 'accessibility_banner_ad': 'This is an Audio Described version of this programme.', 'accessibility_banner_ad_non_available': "The non-Audio Described version isn't available.", 'accessibility_banner_ad_turn_off': 'Turn off Audio Description', 'accessibility_banner_find_out_why': 'Find out why', 'expand_synopsis': 'More', 'collapse_synopsis': 'Less', 'first_shown': 'First shown', 'version_button_ad': 'Audio Described', 'version_button_ad_aria': 'Watch Audio Described version', 'version_button_ad_turn_off_aria': 'Watch non-Audio Described version', 'version_button_sign': 'Sign Language', 'version_button_sign_aria': 'Watch Sign Language version', 'version_button_sign_turn_off_aria': 'Watch non-Sign Language version', 'learn_more_about_availability': 'Learn more about availability', 'download': 'Download', 'add': 'Add', 'added': 'Added', 'remove': 'Remove', 'added_banner_message': ':episodeTitle has been added to', 'my_programmes': 'My Programmes', 'download_not_available_why_aria_label': "Why can't I download?", 'download_modal_title': 'Programme Downloads', 'download_modal_have_you_installed': 'Have you installed BBC iPlayer Downloads?', 'download_modal_help_faq': 'Help & FAQ', 'download_button_hd': 'Yes, download in HD', 'download_button_sd': 'Yes, download in SD', 'download_button_install_now': 'No, install now', 'rrc_why_aria_label': 'More information about revisions, revocations and corrections', 'programme_footer_link_label': 'Programme links', 'programme_footer_link_programme_website': 'Programme website', 'programme_footer_link_credits': 'Credits', 'programme_footer_link_more_from_bbc_three': 'More from BBC Three', 'preroll_available_now': 'Available now on BBC iPlayer', 'preroll_coming_soon': 'Coming soon on BBC iPlayer', 'foreign_region_banner': 'BBC iPlayer only works in the UK. Sorry, it’s due to rights issues.', 'foreign_region_banner_advice': "In the UK? Here's some advice."}, 'episode': {'status': 'success', 'resumeOffset': None, 'added': None, 'addSuccess': None, 'id': 'b0074mhp', 'live': False, 'title': 'The Blue Planet', 'subtitle': '1. Introduction', 'synopses': {'large': 'Although 70 per cent of our planet is covered by water, the oceans and many of their inhabitants - such as the blue whale - remain an unexplored mystery. This edition travels to the very depths of the seas to reveal a spectacular variety of life - from alien monsters of the deep to pack-hunting killer whales attacking a grey whale calf.', 'small': 'This travels to the very depths of the seas, to reveal a spectacular variety of life.', 'medium': 'David Attenborough narrates a natural history of the oceans. We travel to the depths of the seas to reveal a spectacular variety of life, some never filmed before.', 'editorial': "Giant creatures, alien lifeforms, microscopic colonies - it's all here under the waves."}, 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p06mnw3k.jpg'}, 'masterBrand': {'id': 'bbc_one', 'titles': {'large': 'BBC One', 'small': 'BBC One', 'medium': 'BBC One'}, 'ident_id': 'p06g87jc', 'attribution': 'bbc_one'}, 'requiresSignIn': True, 'tleoId': 'b008044n', 'tleoType': 'series', 'guidance': False, 'labels': {'category': 'Science & Nature'}, 'hasCredits': True, 'currentVersion': 'standard'}, 'relatedEpisodes': {'episodes': [{'id': 'b0074mhp', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p06mnw3k.jpg'}, 'subtitle': '1. Introduction', 'synopses': {'large': 'Although 70 per cent of our planet is covered by water, the oceans and many of their inhabitants - such as the blue whale - remain an unexplored mystery. This edition travels to the very depths of the seas to reveal a spectacular variety of life - from alien monsters of the deep to pack-hunting killer whales attacking a grey whale calf.', 'small': 'This travels to the very depths of the seas, to reveal a spectacular variety of life.', 'medium': 'David Attenborough narrates a natural history of the oceans. We travel to the depths of the seas to reveal a spectacular variety of life, some never filmed before.', 'editorial': "Giant creatures, alien lifeforms, microscopic colonies - it's all here under the waves."}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, {'id': 'b0074mjc', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr2wn.jpg'}, 'subtitle': '2. The Deep', 'synopses': {'large': 'More people have walked on the moon than have travelled to the very depths of the deep ocean. David Attenborough journeys into the abyss to show us, for the very first time, strange creatures straight out of the film Alien, many of which are new to science. Terrifying fish with massive teeth that eat prey twice their size and weird jellyfish that flash in the darkness. And deep sea sharks never filmed before and submerged mountain ranges and volcanoes far larger than anything on land.', 'small': 'David Attenborough looks at the strange creatures that live in the depths of the ocean.', 'medium': 'David Attenborough narrates a natural history of the oceans to uncover the strange, otherworldly creatures living in the depths of the ocean.'}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}, {'duration': {'text': '58 mins'}, 'kind': 'audio-described', 'download': False, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, {'id': 'b0080pjz', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr3ds.jpg'}, 'subtitle': '3. Open Ocean', 'synopses': {'large': "This programme focuses on the predatory skills of some of the most charismatic hunters found on the planet: whales, dolphins, tuna, shark and rapier-nosed billfish. The open ocean is unimaginably immense - it covers more than 360 million square kilometres of the Earth's surface. Much of this huge expanse of seawater is marine desert with virtually no sign of life. Yet the fastest and most powerful survive, playing a deadly game of hide-and-seek with their prey. This charts how they track down prey in the seemingly featureless seas, following the extraordinary life of yellowfin tuna from a minute egg to a 200 kilogram, voracious predatory giant.", 'small': 'Looking at the hunting skills of whales, dolphins, tuna, shark and rapier-nosed billfish.', 'medium': "David Attenborough narrates a natural history of the oceans. The deadly game of hide-and-seek played by the sea's charismatic hunters - whales, shark and billfish."}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}, {'duration': {'text': '58 mins'}, 'kind': 'audio-described', 'download': False, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, {'id': 'b00818zy', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr5cm.jpg'}, 'subtitle': '4. Frozen Seas', 'synopses': {'large': 'A look at the survival techniques of creatures that endure the harsh conditions of the Arctic and Antarctic. For animals at both poles, life is dominated by the annual retreat and advance of the freezing sea ice and the challenge of surviving winters when temperatures drop.\n\nIn the Arctic the polar bear is the top predator, catching seals on the ice and forcing seabirds to nest high up on cliffs. In Antarctica the flightless penguins have no ground-based predators to deal with but lurking in the water is the constant threat from leopard seals.\n\nNarrated by David Attenborough.', 'small': 'A look at the survival techniques of creatures in the Arctic and Antarctic.', 'medium': 'A natural history of the oceans. A look at the survival techniques of creatures that endure the harsh conditions of the Arctic and Antarctic.'}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Nature'}}], 'count': 9}, 'recommendations': None, 'versions': [{'id': 'b001fkdj', 'kind': 'original', 'download': True, 'hd': False, 'guidance': False, 'rrc': False, 'events': [{'name': 'started', 'offset': 30, 'system': 'uas'}, {'name': 'iplxp-ep-started', 'offset': 30, 'system': 'optimizely'}, {'name': 'iplxp-ep-started', 'offset': 30, 'system': 'dax'}, {'name': 'iplxp-ep-watched', 'offset': 3123, 'system': 'optimizely'}, {'name': 'iplxp-ep-watched', 'offset': 3123, 'system': 'dax'}, {'name': 'ended', 'offset': 3380, 'system': 'uas'}], 'firstBroadcast': '9pm 12 Sep 2001', 'duration': {'text': '58 mins', 'seconds': 3470}, 'availability': {'remaining': {'text': 'Available for 4 months'}}, 'creditsStart': 3464, 'startTime': None, 'endTime': 1554278400}], 'player': {'status': 'loading', 'playingState': None, 'volume': 0.6, 'subtitles': False, 'continuousPlay': None}, 'config': {'staticAssetsPath': 'https://iplayer-web.files.bbci.co.uk/iplayer-web-app-playback-v2/1.0.0-245', 'host': 'www.bbc.co.uk', 'iblBaseUrl': 'https://ibl.api.bbc.co.uk/ibl/v1', 'tipBaseUrl': 'https://iplayer-web.files.bbci.co.uk/iplayer-web-tip-playback/7.2.0'}, 'stats': {'countername': 'iplayer.tv.episode.the_blue_planet.1_introduction.b0074mhp.page', 'firedEvents': []}, 'id': {'status': 'green', 'signedIn': False, 'ageBracket': None, 'enablePersonalisation': False, 'ctaMarkup': "%3Cp%20class%3D%22id4-cta%22%20id%3D%22id4-cta-2c0561a8-945f-4eef-935a-94eaa9015a0f%22%3E%3Cspan%20class%3D%22id5-cta%20id4-cta-size-medium%20id4-cta-color-mixed%20id4-cta-medium-mixed%22%3E%3Ca%20href%3D%22https%3A%2F%2Fsession.bbc.co.uk%2Fsession%3Fptrt%3Dhttps%253A%252F%252Fwww.bbc.co.uk%252Fiplayer%252Fepisode%252Fb0074mhp%252Fthe-blue-planet-1-introduction%26context%3Dtvandiplayer%26userOrigin%3Dtvandiplayer%22%20class%3D%22id4-cta-signin%20id4-cta-button%22%3ESign%20in%3C%2Fa%3E%3Cspan%20class%3D%22id4-cta-with%22%3E%20to%20the%20BBC%2C%3C%2Fspan%3E%20or%20%3Ca%20href%3D%22https%3A%2F%2Fsession.bbc.co.uk%2Fsession%3Faction%3Dregister%26ptrt%3Dhttps%253A%252F%252Fwww.bbc.co.uk%252Fiplayer%252Fepisode%252Fb0074mhp%252Fthe-blue-planet-1-introduction%26context%3Dtvandiplayer%26userOrigin%3Dtvandiplayer%22%20class%3D%22id4-cta-register%22%3ERegister%3C%2Fa%3E%3Cscript%20type%3D%22text%2Fjavascript%22%3Eif%20(require.s.contexts._.config.paths%5B'idcta-v2'%5D)%20%7Brequire(%5B'idcta-v2%2Fidcta-1'%5D%2C%20function(idcta)%20%7Bif%20(idcta%20%26%26%20typeof%20idcta.addUserOrigin%20%3D%3D%3D%20'function')%20%7Bidcta.addUserOrigin('id4-cta-2c0561a8-945f-4eef-935a-94eaa9015a0f')%3B%7D%7D)%3B%7D%3C%2Fscript%3E%3C%2Fspan%3E%3C%2Fp%3E%3Cscript%20type%3D%22text%2Fjavascript%22%3Erequire(%5B'idcta-v2%2Fidcta-1'%5D%2C%20function(idcta)%20%7Bnew%20idcta.Cta(%7Bid%3A%20'id4-cta-2c0561a8-945f-4eef-935a-94eaa9015a0f'%2C%20states%3A%20%7B%7D%2C%20policyname%3A%20''%7D)%3B%7D)%3B%3C%2Fscript%3E", 'cdnFailover': False}, 'user': {'hasPolyfills': None, 'supportsDownloads': None, 'isForeignRegion': None}, 'nextEpisode': {'id': 'b0074mjc', 'live': False, 'type': 'episode', 'title': 'The Blue Planet', 'images': {'type': 'image', 'standard': 'https://ichef.bbci.co.uk/images/ic/{recipe}/p05rr2wn.jpg'}, 'subtitle': '2. The Deep', 'synopses': {'large': 'More people have walked on the moon than have travelled to the very depths of the deep ocean. David Attenborough journeys into the abyss to show us, for the very first time, strange creatures straight out of the film Alien, many of which are new to science. Terrifying fish with massive teeth that eat prey twice their size and weird jellyfish that flash in the darkness. And deep sea sharks never filmed before and submerged mountain ranges and volcanoes far larger than anything on land.', 'small': 'David Attenborough looks at the strange creatures that live in the depths of the ocean.', 'medium': 'David Attenborough narrates a natural history of the oceans to uncover the strange, otherworldly creatures living in the depths of the ocean.'}, 'versions': [{'duration': {'text': '58 mins'}, 'kind': 'original', 'download': True, 'availability': {'remaining': {'text': 'Available for 4 months'}}}, {'duration': {'text': '58 mins'}, 'kind': 'audio-described', 'download': False, 'availability': {'remaining': {'text': 'Available for 4 months'}}}], 'labels': {'category': 'Science & Nature'}}, 'journey': {'status': 'success'}, 'modal': {'msi': False, 'download': False, 'kidsUpsell': False}, 'preroll': None, 'variants': {'iplxp_pb15_trailers': None}}}
```
@kachelaqa, it also failed for me, but I wanted to make sure it was failing in the same place as yours :) | 2018-11-26T14:33:46 |
|
streamlink/streamlink | 2,205 | streamlink__streamlink-2205 | [
"2195"
] | 3946184ab4a9bf9dbc9f9810e27beed44f99791f | diff --git a/src/streamlink/plugins/btsports.py b/src/streamlink/plugins/btsports.py
--- a/src/streamlink/plugins/btsports.py
+++ b/src/streamlink/plugins/btsports.py
@@ -1,12 +1,15 @@
-import re
import time
+
+import logging
+import re
from uuid import uuid4
from streamlink.compat import quote
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
-from streamlink.utils import url_equal
+
+log = logging.getLogger(__name__)
class BTSports(Plugin):
@@ -47,25 +50,23 @@ def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
def login(self, username, password):
- self.logger.debug("Logging in as {0}".format(username))
+ log.debug("Logging in as {0}".format(username))
- redirect_to = "https://home.bt.com/ss/Satellite/secure/loginforward?redirectURL={0}".format(quote(self.url))
+ redirect_to = "https://home.bt.com/ss/Satellite/secure/loginforward?view=btsport&redirectURL={0}".format(quote(self.url))
data = {
"cookieExpp": "30",
"Switch": "yes",
"SMPostLoginUrl": "/appsyouraccount/secure/postlogin",
- "loginforward": "https://home.bt.com/ss/Satellite/secure/loginforward",
+ "loginforward": "https://home.bt.com/ss/Satellite/secure/loginforward?view=btsport",
"smauthreason": "0",
"TARGET": redirect_to,
"USER": username,
"PASSWORD": password}
-
res = self.session.http.post(self.login_url, data=data)
- self.logger.debug("Redirected to: {0}".format(res.url))
-
+ log.debug("Redirected to: {0}".format(res.url))
- if url_equal(res.url, self.url, ignore_scheme=True):
+ if "loginerror" not in res.text:
self.logger.debug("Login successful, getting SAML token")
res = self.session.http.get("https://samlfed.bt.com/sportgetfedwebhls?bt.cid={0}".format(self.acid()))
d = self.saml_re.search(res.text)
@@ -81,7 +82,8 @@ def login(self, username, password):
self.logger.error("Failed to login: {0} - {1}".format(fed_json['errorDescription'],
fed_json['message']))
return success
- return False
+ else:
+ return False
def device_id(self):
device_id = self.cache.get("device_id") or str(uuid4())
@@ -108,19 +110,23 @@ def _get_cdn(self, channel_id, channel_type="LIVE"):
def _get_streams(self):
if self.options.get("email") and self.options.get("password"):
if self.login(self.options.get("email"), self.options.get("password")):
- self.logger.debug("Logged in and authenticated with BT Sports.")
+ log.debug("Logged in and authenticated with BT Sports.")
res = self.session.http.get(self.url)
m = self.content_re.findall(res.text)
if m:
info = dict(m)
data = self._get_cdn(info.get("ID"), info.get("TYPE"))
+ log.debug("CDN respsonse: {0}".format(data))
if data['resultCode'] == 'OK':
return HLSStream.parse_variant_playlist(self.session, data['resultObj']['src'])
else:
- self.logger.error("Failed to get stream with error: {0} - {1}".format(data['errorDescription'],
+ log.error("Failed to get stream with error: {0} - {1}".format(data['errorDescription'],
data['message']))
+ else:
+ log.error("Login failed.")
else:
- self.logger.error("A username and password is required to use BT Sports")
+ log.error("A username and password is required to use BT Sports")
+
__plugin__ = BTSports
| BT sports plugin does not find playable streams
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
<!-- Explain the plugin issue as thoroughly as you can. -->
The plugin doesn't find any playable streams.
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. https://sport.bt.com/btsportplayer/live-streaming-01363980987389?leId=1364293056880
2. https://sport.bt.com/btsportplayer/live-streaming-01363980987389?leId=1364293057384
3. ...
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
C:\Users\>streamlink --btsports-email EMAIL --btsports-password PASSWORD https://sport.bt.co
m/btsportplayer/live-streaming-01363980987389?leId=1364293057384 --loglevel debug
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.5.2
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0)
[cli][info] Found matching plugin btsports for URL https://sport.bt.com/btsportplayer/live-streaming-01363980987389?leId
=1364293057384
[cli][debug] Plugin specific arguments:
[cli][debug] [email protected] (email)
[cli][debug] --btsports-password=******** (password)
[plugin.btsports][debug] Logging in as [email protected]
[plugin.btsports][debug] Redirected to: https://home.bt.com/s/assets/pages/login-interstitial.html?TARGET=https%253A%2F%
2Fsport.bt.com%2Fbtsportplayer%2Flive-streaming-01363980987389%253FleId%253D1364293057384
error: No playable streams found on this URL: https://sport.bt.com/btsportplayer/live-streaming-01363980987389?leId=1364
293057384
```
### Additional comments, screenshots, etc.
the links are for Champions League replay matches
should give multiple options for streams.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| Looks like the login process may have changed (a possibly more). I don't have an account, I borrowed some credentials to develop the plugin. Unfortunately without a username/password I cannot debug it properly.
you can use my login to have a look :)
where can i send it to? | 2018-12-19T14:08:08 |
|
streamlink/streamlink | 2,228 | streamlink__streamlink-2228 | [
"2222"
] | 94a8a7301c45dfdee89dd7d4d14043438dda4b38 | diff --git a/src/streamlink/plugins/filmon.py b/src/streamlink/plugins/filmon.py
--- a/src/streamlink/plugins/filmon.py
+++ b/src/streamlink/plugins/filmon.py
@@ -164,7 +164,7 @@ class Filmon(Plugin):
|
(?:tv/)channel/(?:export\?)?
|
- tv/(?!channel)
+ tv/(?!channel/)
|
channel/
|
| diff --git a/tests/plugins/test_filmon.py b/tests/plugins/test_filmon.py
--- a/tests/plugins/test_filmon.py
+++ b/tests/plugins/test_filmon.py
@@ -10,24 +10,25 @@ def test_can_handle_url(self):
'http://www.filmon.tv/index/popout?channel_id=5510&quality=low',
'http://www.filmon.tv/tv/channel/export?channel_id=5510&autoPlay=1',
'http://www.filmon.tv/tv/channel/grandstand-show',
+ 'http://www.filmon.tv/tv/channel-4',
'https://www.filmon.com/tv/bbc-news',
'https://www.filmon.tv/tv/55',
'http://www.filmon.tv/vod/view/10250-0-crime-boss',
'http://www.filmon.tv/group/comedy',
]
for url in should_match:
- self.assertTrue(Filmon.can_handle_url(url))
+ self.assertTrue(Filmon.can_handle_url(url), url)
def test_can_handle_url_negative(self):
should_not_match = [
'https://example.com/index.html',
]
for url in should_not_match:
- self.assertFalse(Filmon.can_handle_url(url))
+ self.assertFalse(Filmon.can_handle_url(url), url)
def _test_regex(self, url, expected):
m = Filmon.url_re.match(url)
- self.assertIsNotNone(m)
+ self.assertIsNotNone(m, url)
# expected must return [is_group, channel, vod_id]
self.assertEqual(expected, list(m.groups()))
@@ -51,6 +52,10 @@ def test_regex_live_stream_tv(self):
self._test_regex('https://www.filmon.com/tv/bbc-news',
[None, 'bbc-news', None])
+ def test_regex_live_stream_tv_with_channel_in_name(self):
+ self._test_regex('https://www.filmon.com/tv/channel-4',
+ [None, 'channel-4', None])
+
def test_regex_live_stream_tv_number(self):
self._test_regex('https://www.filmon.tv/tv/55',
[None, '55', None])
| FilmOn.py No plugin can handle
## Error Report
- [x] This is a bug report and I have read the post guidelines.
### Description
On the homepage of Film On the UK channels are played without problem.
Unfortunately not with Streamlink. Here it fails with the transmitter Channel4 and Channel5
### Expected / actual behavior
I enter the address and there is no picture.
streamlink http://www.filmon.com/tv/channel-4 best
### Reproduction steps / Explicit stream URLs to test
1.https: //www.filmon.com/tv/channel-4
2.https: //www.filmon.com/tv/channel-5
### log output
Not Work with Channel4:
WINDOWS> streamlink http://www.filmon.com/tv/channel-4 best
error: No plugin can handle URL: http://www.filmon.com/tv/channel-4
Work with More4
WINDOWS> streamlink https://www.filmon.com/tv/more4 best
[cli][info] Found matching plugin filmon for URL https://www.filmon.com/tv/more4
[cli][info] Available streams: low (worst), high (best)
[cli][info] Opening stream: high (hls-filmon)
[cli][info] Starting player: "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"
[cli][info] Player closed
[cli][info] Stream ended
[cli][info] Closing currently open stream...
### Additional comments, screenshots, etc.
https://i.ibb.co/FDs2QtX/film-on.jpg
| 2019-01-03T12:48:51 |
|
streamlink/streamlink | 2,229 | streamlink__streamlink-2229 | [
"2221"
] | 94a8a7301c45dfdee89dd7d4d14043438dda4b38 | diff --git a/src/streamlink/plugins/powerapp.py b/src/streamlink/plugins/powerapp.py
--- a/src/streamlink/plugins/powerapp.py
+++ b/src/streamlink/plugins/powerapp.py
@@ -7,7 +7,7 @@
class PowerApp(Plugin):
- url_re = re.compile(r"https?://(?:www.)?powerapp.com.tr/tv/(\w+)")
+ url_re = re.compile(r"https?://(?:www.)?powerapp.com.tr/tvs?/(\w+)")
api_url = "http://api.powergroup.com.tr/Channels/{0}/?appRef=iPowerWeb&apiVersion=11"
api_schema = validate.Schema(validate.all({
"errorCode": 0,
| diff --git a/tests/plugins/test_powerapp.py b/tests/plugins/test_powerapp.py
--- a/tests/plugins/test_powerapp.py
+++ b/tests/plugins/test_powerapp.py
@@ -9,9 +9,10 @@ def test_can_handle_url(self):
'http://powerapp.com.tr/tv/powertv4k',
'http://powerapp.com.tr/tv/powerturktv4k',
'http://powerapp.com.tr/tv/powerEarthTV',
+ 'http://www.powerapp.com.tr/tvs/powertv'
]
for url in should_match:
- self.assertTrue(PowerApp.can_handle_url(url))
+ self.assertTrue(PowerApp.can_handle_url(url), url)
def test_can_handle_url_negative(self):
should_not_match = [
| powerapp.py No plugin can handle URL
## Error Report
- [X] This is a bug report and I have read the Posting Guidelines.
### Description
powerapp.com.tr should be able to play the stations
### Expected / actual behavior
Inserting the page in the streamlink does not play the stream. About my web browser Firefox I see the picture and hear the sound synonymous
### Reproduction steps / Explicit stream URLs to test
1.www.powerapp.com.tr/tvs/powertv/
streamlink http://www.powerapp.com.tr/tvs/powertv best
### log output
> streamlink http://www.powerapp.com.tr/tvs/powertv best
error: No plugin can handle URL: http://www.powerapp.com.tr/tvs/powertv
> error: No plugin can handle URL: http://www.powerapp.com.tr/tvs/powertv
error:: The term "error:" was not used as the name of a cmdlet, a function, a script file, or a
recognized executable program. Check the spelling of the name, or if the path is correct (provided
contain) and repeat the process.
In line: 1 character: 1
+ error: No plugin can handle URL: http://www.powerapp.com.tr/tvs/power ...
+~~~~~
+ CategoryInfo: ObjectNotFound: (error :: String) [], CommandNotFoundException
+ FullyQualifiedErrorId: CommandNotFoundException
### Additional comments, screenshots, etc.
Screenshot
https://i.ibb.co/g99nXC0/france.jpg
| 2019-01-03T12:54:25 |
|
streamlink/streamlink | 2,230 | streamlink__streamlink-2230 | [
"2219"
] | 94a8a7301c45dfdee89dd7d4d14043438dda4b38 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -13,8 +13,8 @@
'futures;python_version<"3.0"',
# Require singledispatch on Python <3.4
'singledispatch;python_version<"3.4"',
- "requests>=2.2,!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0",
- 'urllib3[secure]<1.23,>=1.21.1;python_version<"3.0"',
+ "requests>=2.21.0,<3.0",
+ 'urllib3[secure]>=1.23;python_version<"3.0"',
"isodate",
"websocket-client",
# Support for SOCKS proxies
| Update dependencies with security vulnerabilities
As mentioned here:
https://github.com/streamlink/streamlink/pull/2199#issuecomment-447567326
1. urllib3
> Vulnerable versions: < 1.23
> Patched version: 1.23
> urllib3 before version 1.23 does not remove the Authorization HTTP header when following a cross-origin redirect (i.e., a redirect that differs in host, port, or scheme). This can allow for credentials in the Authorization header to be exposed to unintended hosts or transmitted in cleartext.
https://nvd.nist.gov/vuln/detail/CVE-2018-20060
2. requests
> Vulnerable versions: <= 2.19.1
> Patched version: 2.20.0
> The Requests package through 2.19.1 before 2018-09-14 for Python sends an HTTP Authorization header to an http URI upon receiving a same-hostname https-to-http redirect, which makes it easier for remote attackers to discover credentials by sniffing the network.
https://nvd.nist.gov/vuln/detail/CVE-2018-18074
| This should be the last blocker for https://github.com/streamlink/streamlink/pull/2199 @cdrage. | 2019-01-03T16:43:37 |
|
streamlink/streamlink | 2,269 | streamlink__streamlink-2269 | [
"2268"
] | 965c375825906d07354cf6bbc9208c9933bc5156 | diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py
--- a/src/streamlink/plugins/tf1.py
+++ b/src/streamlink/plugins/tf1.py
@@ -1,74 +1,43 @@
from __future__ import print_function
+
+import logging
import re
-from streamlink.compat import urlparse, parse_qsl
+from streamlink.compat import urljoin
from streamlink.plugin import Plugin
-from streamlink.plugin.api import useragents
-from streamlink.stream import HDSStream
-from streamlink.stream import HLSStream
-from streamlink.utils.url import update_qsd
+from streamlink.stream import DASHStream
+
+log = logging.getLogger(__name__)
class TF1(Plugin):
url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/([\w-]+)/direct|(lci).fr/direct)/?")
- embed_url = "http://www.wat.tv/embedframe/live{0}"
- embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE)
- api_url = "http://www.wat.tv/get/{0}/591997"
- swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf"
- hds_channel_remap = {"tf1": "androidliveconnect",
- "lci": "androidlivelci",
- "tfx": "nt1live",
- "hd1": "hd1live", # renamed to tfx
- "tf1-series-films": "hd1live"}
- hls_channel_remap = {"lci": "LCI",
- "tf1": "V4",
- "tfx": "nt1",
- "tf1-series-films": "hd1"}
+ api_url_base = "https://delivery.tf1.fr/mytf1-wrd/"
+ token = "07e45841-a17a-47cf-af64-a42311bdcc3d"
+
+ def api_call(self, channel):
+ url = urljoin(self.api_url_base, "L_"+channel.upper())
+ req = self.session.http.get(url, params=dict(token=self.token))
+ return self.session.http.json(req)
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
- def _get_hds_streams(self, channel):
- channel = self.hds_channel_remap.get(channel, "{0}live".format(channel))
- self.logger.debug("Using HDS channel name: {0}".format(channel))
- manifest_url = self.session.http.get(self.api_url.format(channel),
- params={"getURL": 1},
- headers={"User-Agent": useragents.FIREFOX}).text
-
- for s in HDSStream.parse_manifest(self.session,
- manifest_url,
- pvswf=self.swf_url,
- headers={"User-Agent": useragents.FIREFOX}).items():
- yield s
-
- def _get_hls_streams(self, channel):
- channel = self.hls_channel_remap.get(channel, channel)
- embed_url = self.embed_url.format(channel)
- self.logger.debug("Found embed URL: {0}", embed_url)
- # page needs to have a mobile user agent
- embed_page = self.session.http.get(embed_url, headers={"User-Agent": useragents.ANDROID})
-
- m = self.embed_re.search(embed_page.text)
- if m:
- # remove all query string arguments except hdnea
- hls_stream_url = update_qsd(m.group(1), {"hdnea": None}, remove="*")
- try:
- for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items():
- yield s
- except Exception:
- self.logger.error("Failed to load the HLS playlist for {0}", channel)
-
def _get_streams(self):
m = self.url_re.match(self.url)
if m:
channel = m.group(1) or m.group(2)
self.logger.debug("Found channel {0}", channel)
- for s in self._get_hds_streams(channel):
- yield s
-
- for s in self._get_hls_streams(channel):
- yield s
+ data = self.api_call(channel)
+
+ if data.get("error"):
+ log.error("Failed to get stream for {0}: {error} ({code})".format(channel, **data))
+ else:
+ log.debug("Got {format} stream {url}".format(**data))
+ if data["format"] == "dash":
+ for s in DASHStream.parse_manifest(self.session, data["url"]).items():
+ yield s
__plugin__ = TF1
| TF1 group
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
Streams from tf1 are not working anymore with streamlink, though it works on their website.
### Reproduction steps / Explicit stream URLs to test
I m using streamlink-0.14.2+84.ga91e134 or older versions on others servers.
```
/usr/local/bin/streamlink --loglevel debug "https://www.tf1.fr/tf1/direct" best
[cli][info] streamlink is running as root! Be careful!
[cli][debug] OS: Linux-4.4.0-139-generic-x86_64-with-Ubuntu-16.04-xenial
[cli][debug] Python: 2.7.12
[cli][debug] Streamlink: 0.14.2+84.ga91e134
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.44.0)
[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/tf1/direct
[plugin.tf1][debug] Found channel tf1
[plugin.tf1][debug] Using HDS channel name: androidliveconnect
error: Unable to open URL: http://tf1livhdsstrike-lh.akamaihd.net/z/strike01_1@97257/manifest.f4m?hdnea=st=1548416338~exp=1548418138~acl=/*~hmac=520d4c15de6c568cd6093711ae0757af7d106bd070fcb8633b894e9896bebab6&n=20&b=496,896,1296,1896 (503 Server Error: Service Unavailable for url: http://tf1livhdsstrike-lh.akamaihd.net/z/strike01_1@97257/manifest.f4m?hdnea=st=1548416338~exp=1548418138~acl=/*~hmac=520d4c15de6c568cd6093711ae0757af7d106bd070fcb8633b894e9896bebab6&n=20&b=496,896,1296,1896&g=CJMOWFRATQAD&hdcore=3.1.0)
```
| On the website it looks like you need to login, is that a recent change?
no it's very old the login. | 2019-01-25T22:10:24 |
|
streamlink/streamlink | 2,277 | streamlink__streamlink-2277 | [
"2213"
] | 7dbda7b5e733ad5a1f089011ae7da159e2378534 | diff --git a/src/streamlink/plugins/dogus.py b/src/streamlink/plugins/dogus.py
--- a/src/streamlink/plugins/dogus.py
+++ b/src/streamlink/plugins/dogus.py
@@ -1,9 +1,14 @@
import re
+import logging
from streamlink.plugin import Plugin
+from streamlink.plugin.api.utils import itertags
+from streamlink.plugins.youtube import YouTube
from streamlink.stream import HLSStream
from streamlink.utils import update_scheme
+log = logging.getLogger(__name__)
+
class Dogus(Plugin):
"""
@@ -14,13 +19,13 @@ class Dogus(Plugin):
(?:
ntv.com.tr/canli-yayin/ntv|
ntvspor.net/canli-yayin|
- kralmuzik.com.tr/tv/kral-tv|
- kralmuzik.com.tr/tv/kral-pop-tv|
+ kralmuzik.com.tr/tv/|
eurostartv.com.tr/canli-izle
)/?""", re.VERBOSE)
mobile_url_re = re.compile(r"""(?P<q>["'])(?P<url>(https?:)?//[^'"]*?/live/hls/[^'"]*?\?token=)
(?P<token>[^'"]*?)(?P=q)""", re.VERBOSE)
token_re = re.compile(r"""token=(?P<q>["'])(?P<token>[^'"]*?)(?P=q)""")
+ kral_token_url = "https://service.kralmuzik.com.tr/version/gettoken"
@classmethod
def can_handle_url(cls, url):
@@ -28,18 +33,31 @@ def can_handle_url(cls, url):
def _get_streams(self):
res = self.session.http.get(self.url)
- mobile_url_m = self.mobile_url_re.search(res.text)
-
- mobile_url = mobile_url_m and update_scheme(self.url, mobile_url_m.group("url"))
- token = mobile_url_m and mobile_url_m.group("token")
- if not token:
- # if no token is in the url, try to find it else where in the page
- token_m = self.token_re.search(res.text)
- token = token_m and token_m.group("token")
+ # Look for Youtube embedded video first
+ for iframe in itertags(res.text, 'iframe'):
+ if YouTube.can_handle_url(iframe.attributes.get("src")):
+ log.debug("Handing off to YouTube plugin")
+ return self.session.streams(iframe.attributes.get("src"))
- return HLSStream.parse_variant_playlist(self.session, mobile_url + token,
- headers={"Referer": self.url})
+ # Next check for HLS URL with token
+ mobile_url_m = self.mobile_url_re.search(res.text)
+ mobile_url = mobile_url_m and update_scheme(self.url, mobile_url_m.group("url"))
+ if mobile_url:
+ log.debug("Found mobile stream: {0}".format(mobile_url_m.group(0)))
+
+ token = mobile_url_m and mobile_url_m.group("token")
+ if not token and "kralmuzik" in self.url:
+ log.debug("Getting Kral Muzik HLS stream token from API")
+ token = self.session.http.get(self.kral_token_url).text
+ elif not token:
+ # if no token is in the url, try to find it else where in the page
+ log.debug("Searching for HLS stream token in URL")
+ token_m = self.token_re.search(res.text)
+ token = token_m and token_m.group("token")
+
+ return HLSStream.parse_variant_playlist(self.session, mobile_url + token,
+ headers={"Referer": self.url})
__plugin__ = Dogus
| dogus.py KRAL TV Plugin error: Unable to open URL:
## Bug Report
- [x] This is a bug report and I have read the contribution guidelines.
### Description dogus.py
<!-- What do you expect to happen, and what is actually happening? -->
Normally the picture and the sound should come, none of it will come
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. https://www.kralmuzik.com.tr/tv/kral-pop-tv
### Log output
streamlink http://www.kralmuzik.com.tr/tv/kral-pop-tv best
[cli][info] Found matching plugin dogus for URL http://www.kralmuzik.com.tr/tv/kral-pop-tv
error: Unable to open URL: https://dygvideo.dygdigital.com/live/hls/kralpop?token= : (403 Client Error: Forbidden for url: https://dygvideo.dygdigital.com/live/hls/kralpop?token=%20:%20)
| 2019-01-28T22:04:37 |
||
streamlink/streamlink | 2,279 | streamlink__streamlink-2279 | [
"2278"
] | 42c34ca104f9a1761164dfce6c3ebabea984a823 | diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -187,13 +187,20 @@ def login(self, ptrt_url):
: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)
)
- http_nonce = self._extract_nonce(session_res)
+ if auth_check(session_res):
+ log.debug("Already authenticated, skipping authentication")
+ return True
+ http_nonce = self._extract_nonce(session_res)
res = self.session.http.post(
self.auth_url,
params=dict(
@@ -208,7 +215,7 @@ def login(self, ptrt_url):
),
headers={"Referer": self.url})
- return len(res.history) != 0
+ return auth_check(res)
def _get_streams(self):
if not self.get_option("username"):
| diff --git a/tests/plugins/test_bbciplayer.py b/tests/plugins/test_bbciplayer.py
--- a/tests/plugins/test_bbciplayer.py
+++ b/tests/plugins/test_bbciplayer.py
@@ -1,5 +1,4 @@
import json
-import logging
import unittest
from requests import Response, Request
| Using Xtreme Codes Panel doesnt work anymore
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
I am trying to open a stream on Xtreme Codes panel as it worked no problem late last year but now it does not work. Works great on VLC. Below is what i am seeing.
### Reproduction steps / Explicit stream URLs to test
1. I run the below command to open the stream;
```
streamlink --player-external-http-port 1234 --player-external-http --bbciplayer-username MYUSERNAME --bbciplayer-password MYPASSWORD www.bbc.co.uk/iplayer/live/bbcone best & disown
```
### Log output
```
root@vps642372:~# streamlink --player-external-http-port 1234 --player-external-http --bbciplayer-username 'USER' --bbciplayer-password 'PASS' www.bbc.co.uk/iplayer/live/bbcone best --player-no-close & disown
[1] 3919
root@vps642372:~# [cli][info] streamlink is running as root! Be careful!
[cli][info] Found matching plugin bbciplayer for URL www.bbc.co.uk/iplayer/live/bbcone
[plugin.bbciplayer][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
[cli][info] Available streams: 288p_dash, 396p_dash, 540p_dash, 288p_dash_alt, 396p_dash_alt, 540p_dash_alt, 288p_dash_alt2, 396p_dash_alt2, 540p_dash_alt2, 352k_alt2 (worst), 352k_alt, 352k, 544k_alt2, 544k_alt, 544k, 216p_alt2, 216p_alt, 216p, 288p_alt2, 288p_alt, 288p, 942k_alt2, 942k_alt, 942k, 396p_alt2, 396p_alt, 396p, 540p_alt2, 540p_alt, 540p, 1700k_alt2, 1700k_alt, 1700k (best)
[cli][info] Starting server, access with one of:
[cli][info] http://127.0.0.1:1234/
[cli][info] http://127.0.1.1:1234/
[cli][info] http://MYIPADDRESS:1234/
[cli][info] Got HTTP request from Xtream-Codes IPTV Panel Pro
[cli][info] Opening stream: 1700k (hds)
[cli][info] HTTP connection closed
[cli][info] Stream ended
[cli][info] Got HTTP request from Xtream-Codes IPTV Panel Pro
[plugin.bbciplayer][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
[cli][info] Closing currently open stream...
Traceback (most recent call last):
File "/usr/bin/streamlink", line 11, in <module>
load_entry_point('streamlink==0.14.2', 'console_scripts', 'streamlink')()
File "/usr/share/streamlink/streamlink_cli/main.py", line 1002, in main
handle_url()
File "/usr/share/streamlink/streamlink_cli/main.py", line 553, in handle_url
handle_stream(plugin, streams, stream_name)
File "/usr/share/streamlink/streamlink_cli/main.py", line 397, in handle_stream
port=args.player_external_http_port)
File "/usr/share/streamlink/streamlink_cli/main.py", line 179, in output_stream_http
streams = initial_streams or fetch_streams(plugin)
File "/usr/share/streamlink/streamlink_cli/main.py", line 413, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "/usr/lib/python3/dist-packages/streamlink/plugin/plugin.py", line 431, in get_streams
return self.streams(*args, **kwargs)
File "/usr/lib/python3/dist-packages/streamlink/plugin/plugin.py", line 339, in streams
ostreams = list(ostreams)
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 224, in _get_streams
if not self.login(self.url):
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 197, in login
http_nonce = self._extract_nonce(session_res)
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 118, in _extract_nonce
final_url = urlparse(last_redirect_query['goto'])
KeyError: 'goto'
```
| ```
root@vps642372:~# streamlink ... best --player-no-close & disown
[1] 3919
```
remove the `& disown` it breaks the streamlink line
---
use `--loglevel debug` for the **Log output**
---
try hls `540p` instead of hds `1700k (best)`
thank you for the reply. I have done what you said and below is the output.
```
root@vps642372:~# streamlink --player-external-http-port 1234 --player-external-http --bbciplayer-username USER --bbciplayer-password PASS www.bbc.co.uk/iplayer/live/bbcone 540p --loglevel debug
[cli][info] streamlink is running as root! Be careful!
[cli][debug] OS: Linux-4.15.0-43-generic-x86_64-with-Ubuntu-18.04-bionic
[cli][debug] Python: 3.6.7
[cli][debug] Streamlink: 0.14.2
[cli][debug] Requests(2.18.4), Socks(1.6.5), Websocket(0.44.0)
[cli][info] Found matching plugin bbciplayer for URL www.bbc.co.uk/iplayer/live/bbcone
[cli][debug] Plugin specific arguments:
[cli][debug] --bbciplayer-username=USER (username)
[cli][debug] --bbciplayer-password=******** (password)
[plugin.bbciplayer][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
[plugin.bbciplayer][debug] Loading stream for live channel: bbcone
[plugin.bbciplayer][debug] Looking for tvip on http://www.bbc.co.uk/iplayer/live/bbcone
[plugin.bbciplayer][debug] Found TVIP: bbc_one_london
[plugin.bbciplayer][debug] Info API request: http://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/pc/vpid/bbc_one_london/format/json/atk/78ca5063d64bb5b308d1d87f737b610aa2db0f3f/asn/1/
[plugin.bbciplayer][debug] Info API request: http://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/iptv-all/vpid/bbc_one_london/format/json/atk/78ca5063d64bb5b308d1d87f737b610aa2db0f3f/asn/1/
[plugin.bbciplayer][debug] 4 hds streams
[plugin.bbciplayer][debug] OK: http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/ak/bbc_one_london.f4m
[plugin.bbciplayer][debug] OK: https://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/aks/bbc_one_london.f4m
[plugin.bbciplayer][debug] OK: http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/llnw/bbc_one_london.f4m
[plugin.bbciplayer][debug] OK: https://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hds/uk/pc/llnws/bbc_one_london.f4m
[plugin.bbciplayer][debug] 8 dash streams
[plugin.bbciplayer][debug] OK: http://vs-dash-uk-live.bbcfmt.hs.llnwd.net/pool_902/live/bbc_one_london/bbc_one_london.isml/pc_hd_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: https://vs-dash-uk-live.akamaized.net/pool_902/live/bbc_one_london/bbc_one_london.isml/iptv_sdlow_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: http://vs-dash-uk-live.akamaized.net/pool_902/live/bbc_one_london/bbc_one_london.isml/pc_hd_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: http://vs-dash-uk-live.bbcfmt.hs.llnwd.net/pool_902/live/bbc_one_london/bbc_one_london.isml/iptv_sdlow_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: https://vs-dash-uk-live.akamaized.net/pool_902/live/bbc_one_london/bbc_one_london.isml/pc_hd_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: http://vs-dash-uk-live.akamaized.net/pool_902/live/bbc_one_london/bbc_one_london.isml/iptv_sdlow_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: https://vs-dash-uk-live.bbcfmt.hs.llnwd.net/pool_902/live/bbc_one_london/bbc_one_london.isml/pc_hd_abr_v2_dash.mpd
[plugin.bbciplayer][debug] OK: https://vs-dash-uk-live.bbcfmt.hs.llnwd.net/pool_902/live/bbc_one_london/bbc_one_london.isml/iptv_sdlow_abr_v2_dash.mpd
[plugin.bbciplayer][debug] 4 hls streams
[plugin.bbciplayer][debug] OK: https://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_tv/aks/bbc_one_london.m3u8
[plugin.bbciplayer][debug] OK: https://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_tv/llnws/bbc_one_london.m3u8
[plugin.bbciplayer][debug] OK: http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_tv/llnw/bbc_one_london.m3u8
[plugin.bbciplayer][debug] OK: http://a.files.bbci.co.uk/media/live/manifesto/audio_video/simulcast/hls/uk/abr_tv/ak/bbc_one_london.m3u8
[cli][info] Available streams: 288p_dash, 396p_dash, 540p_dash, 288p_dash_alt, 396p_dash_alt, 540p_dash_alt, 288p_dash_alt2, 396p_dash_alt2, 540p_dash_alt2, 352k_alt2 (worst), 352k_alt, 352k, 544k_alt2, 544k_alt, 544k, 216p_alt2, 216p_alt, 216p, 288p_alt2, 288p_alt, 288p, 942k_alt2, 942k_alt, 942k, 396p_alt2, 396p_alt, 396p, 540p_alt2, 540p_alt, 540p, 1700k_alt2, 1700k_alt, 1700k (best)
[cli][info] Starting server, access with one of:
[cli][info] http://127.0.0.1:1234/
[cli][info] http://127.0.1.1:1234/
[cli][info] http://MYIPADDRESS:1234/
[cli][info] Got HTTP request from Xtream-Codes IPTV Panel Pro
[cli][info] Opening stream: 540p (hls)
[stream.hls][debug] Reloading playlist
[stream.hls][debug] First Sequence: 201671571; Last Sequence: 201672508
[stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 201672506; End Sequence: None
[stream.hls][debug] Adding segment 201672506 to queue
[cli][debug] Pre-buffering 8192 bytes
[stream.hls][debug] Adding segment 201672507 to queue
[stream.hls][debug] Adding segment 201672508 to queue
[stream.hls][debug] Download of segment 201672506 complete
[cli][debug] Writing stream to player
[stream.hls][debug] Download of segment 201672507 complete
[stream.hls][debug] Download of segment 201672508 complete
[cli][info] HTTP connection closed
[stream.segmented][debug] Closing worker thread
[stream.segmented][debug] Closing writer thread
[stream.segmented][debug] Closing writer thread
[cli][info] Stream ended
[cli][info] Got HTTP request from Xtream-Codes IPTV Panel Pro
[plugin.bbciplayer][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
[cli][info] Closing currently open stream...
Traceback (most recent call last):
File "/usr/bin/streamlink", line 11, in <module>
load_entry_point('streamlink==0.14.2', 'console_scripts', 'streamlink')()
File "/usr/share/streamlink/streamlink_cli/main.py", line 1002, in main
handle_url()
File "/usr/share/streamlink/streamlink_cli/main.py", line 553, in handle_url
handle_stream(plugin, streams, stream_name)
File "/usr/share/streamlink/streamlink_cli/main.py", line 397, in handle_stream
port=args.player_external_http_port)
File "/usr/share/streamlink/streamlink_cli/main.py", line 179, in output_stream_http
streams = initial_streams or fetch_streams(plugin)
File "/usr/share/streamlink/streamlink_cli/main.py", line 413, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "/usr/lib/python3/dist-packages/streamlink/plugin/plugin.py", line 431, in get_streams
return self.streams(*args, **kwargs)
File "/usr/lib/python3/dist-packages/streamlink/plugin/plugin.py", line 339, in streams
ostreams = list(ostreams)
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 224, in _get_streams
if not self.login(self.url):
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 197, in login
http_nonce = self._extract_nonce(session_res)
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 118, in _extract_nonce
final_url = urlparse(last_redirect_query['goto'])
KeyError: 'goto'
```
Seems to be caused by the multiple requests that `Xtreme Codes Panel` makes when connecting to an HTTP source.
is there a way to fix this at all as it did work last year? | 2019-01-30T12:49:42 |
streamlink/streamlink | 2,326 | streamlink__streamlink-2326 | [
"2287"
] | 8da935d3d651b6775930877f76623a128ea19511 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
import codecs
-from os import environ
-from os import path
-from sys import path as sys_path
+from os import environ, path
+from sys import argv, path as sys_path
from setuptools import setup, find_packages
@@ -53,6 +52,27 @@
with codecs.open(path.join(this_directory, "README.md"), 'r', "utf8") as f:
long_description = f.read()
+
+def is_wheel_for_windows():
+ if "bdist_wheel" in argv:
+ names = ["win32", "win-amd64", "cygwin"]
+ length = len(argv)
+ for pos in range(argv.index("bdist_wheel") + 1, length):
+ if argv[pos] == "--plat-name" and pos + 1 < length:
+ return argv[pos + 1] in names
+ elif argv[pos][:12] == "--plat-name=":
+ return argv[pos][12:] in names
+ return False
+
+
+entry_points = {
+ "console_scripts": ["streamlink=streamlink_cli.main:main"]
+}
+
+if is_wheel_for_windows():
+ entry_points["gui_scripts"] = ["streamlinkw=streamlink_cli.main:main"]
+
+
setup(name="streamlink",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
@@ -74,9 +94,7 @@
license="Simplified BSD",
packages=find_packages("src"),
package_dir={"": "src"},
- entry_points={
- "console_scripts": ["streamlink=streamlink_cli.main:main"]
- },
+ entry_points=entry_points,
install_requires=deps,
test_suite="tests",
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4",
| Streamlink no longer provides streamlink-script.py
As of version 0.14.0 streamlink does not install the streamlink-script.py script,
because of this streamlink-twitch-gui does not work as it cannot load the script.
This may an issue in streamlink, as there is no mention of its removal in the changelog.
| Which OS are you using and which method of installing Streamlink did you choose?
I am using Windows 10, and streamlink is installed via pip.
Also I am using python 3.
That's because of streamlink/streamlink#1701 / streamlink/streamlink#1758 and a change of the python wheel packaging.
I'll see what I can do about this. Maybe I have to add a "Streamlink standalone" option, just like "Livestreamer standalone", but this may conflict with Streamlink portable, as it also generates a .exe file on Windows which is not usable at all.
If you install Streamlink on Windows via pip, you can work around this for now by using the `--no-binary streamlink` parameter+value, like this:
```
pip uninstall streamlink
pip install --no-binary streamlink streamlink
```
```
pip install --help | grep -A8 'no-binary'
--no-binary <format_control>
Do not use binary packages. Can be supplied
multiple times, and each time adds to the
existing value. Accepts either :all: to disable
all binary packages, :none: to empty the set, or
one or more package names with commas between
them. Note that some packages are tricky to
compile and may fail to install when this option
is used on them.
```
/cc @beardypig
I’ll investigate as this seems to be a packaging issue.
I can confirm this, i'm not getting the script.
Has there been any progress on the fix for this?
Streamlink has released v1.0.0, which would imply that the majority of developers
there believe that the program has no major issues.
Also @beardypig while you said you would investigate this,
you did not open an issue at the streamlink repository so the other developers there
would know there was an issue with a closely associated application.
> streamlink-twitch-gui does not work as it cannot load the script.
there is a **streamlink.exe** file which can open the streams with streamlink-twitch-gui
you can find it in _(depends on your python location)_
`%LOCALAPPDATA%\Programs\Python\Python37-32\Scripts\streamlink.exe`
my tested `Streamlink Pythonscript` was
`C:\Users\win\AppData\Local\Programs\Python\Python37-32\Scripts\streamlink.exe`
---
the exe files works with a normal `python -m pip install -U streamlink`
don't use the exe file from `pip install --no-binary streamlink streamlink` this won't work
> there is a **streamlink.exe** file which can open the streams with streamlink-twitch-gui
No, that doesn't work.
The Twitch GUI's streamlink resolver expects a python executable and a streamlink entry script. Up until the point of this packaging change, there was no reason to implement a resolver config for a streamlink wrapper executable.
Before the fork of Streamlink, Livestreamer required two different resolver configs, one for its standalone release, which included a single executable, and one for the pip package, which included the entry script and a wrapper executable. Since the wrapper executable always opened a terminal window, it wasn't useful for being run from a GUI application and a second resolver config had to be implemented that used the regular python executable and the entry script. That's the reason for the two ["Livestreamer standalone" and "Livestreamer"](https://github.com/streamlink/streamlink-twitch-gui/blob/v1.6.0/src/config/streaming.json#L72-L127) resolver configs in the Twitch GUI.
The ["Streamlink"](https://github.com/streamlink/streamlink-twitch-gui/blob/v1.6.0/src/config/streaming.json#L25-L71) resolver config is basically a copy of the "Livestreamer" one, as it also expects a python executable and an entry script. This wasn't a problem until recently, because all install methods on Windows included both of these requirements. Now, with this pip packaging change, a secondary Streamlink resolver config would be needed, but I fear that this will cause more confusion than solve issues. And I'm also not sure if the terminal window issue will occur.
A better way of solving this problem would be including both the wrapper executable and entry script in the pip package on Windows, just like Livestreamer did.
But as I've said in my previous comment, the workaround of suppressing the binary works just fine, as it won't omit the entry script.
> A better way of solving this problem would be including both the wrapper executable and entry script in the pip package on Windows, just like Livestreamer did.
sure it could be done, but my point was that it already works **without any changes**
> > there is a **streamlink.exe** file which can open the streams with streamlink-twitch-gui
>
> No, that doesn't work.
works for me
> The Twitch GUI's streamlink resolver expects a python executable and a streamlink entry script. Up until the point of this packaging change,
there is a `pythonw.exe` and `streamlink.exe`
---
I tested it with a fresh install
- new windows 10 virtual machine
- vlc install
- python 3.7.2 install with https://www.python.org/ftp/python/3.7.2/python-3.7.2-amd64.exe
- cmd: `python -m pip install streamlink` **(important use the .whl not .tar.gz)**
- streamlink-twitch-gui install with `streamlink-twitch-gui-v1.6.0-win64-installer.exe`
- config streamlink-twitch-gui
ALl user
```
Python
C:\Program Files (x86)\Python37-32\pythonw.exe
Streamlink
C:\Program Files (x86)\Python37-32\Scripts\streamlink.exe
```
or
current user
```
Python
C:\Users\new\AppData\Local\Programs\Python\Python37-32\pythonw.exe
Streamlink
C:\Users\new\AppData\Local\Programs\Python\Python37-32\Scripts\streamlink.exe
```
- open a random stream with vlc
Streamlink starts as expected
---
> because of this streamlink-twitch-gui does not work as it cannot load the script.
so this is invalid
Just to confirm that setting the streamlink.exe file as the Streamlink python script appears to work fine. It would be cool if it was set to this out of the box though!
![2019-02-05 15_42_35-streamlink twitch gui](https://user-images.githubusercontent.com/400279/52284619-ab595800-295c-11e9-8073-93cedc274bf6.png)
> my point was that it already works **without any changes**
It only works if the user has set custom paths, which doesn't really mean *without any changes*. This is an **undocumented breaking packaging change** and we should fix this.
Sure, this can (and will be) fixed in the Twitch GUI's next release with an upgraded default resolver config, but other applications could be affected by this, too.
Hm, so this seems to be a bit more difficult than I thought. Let me try to explain:
The packaging change was introduced by pynist on Nov 6th after the change in takluyver/pynsist#169. The regular [entry scripts were removed](https://github.com/takluyver/pynsist/pull/169/files#diff-082101e7ff364358b0b29162a1e4a4a9L41) during the switch from `win_cli_launchers` to `distlib` for building the wrapper executables, as that's what pip seems to be using nowadays. This removal is unfortunately breaking the Streamlink Twitch GUI, because of the way it has to resolve and verify the Streamlink entry script and python executable on Windows.
----
Here is how this works:
If a user has set custom paths in the Twitch GUI (as shown in the comments above), no entry-script and executable resolving has to be done, as it's up to the user to select the right files. In case the python executable is not set, it'll use the the `PATH` env var for looking it up and the user has to make sure that the correct python version is used.
If however no custom paths are set, the Twitch GUI has to find the right files on its own, and this unfortunately requires a workaround on Windows. The reason for that is that you can't simply execute the `streamlink.exe` wrapper executable from within the GUI, as it uses `python.exe` instead of `pythonw.exe`, and a terminal window will be opened, which is pretty annoying. Because of this, `pythonw.exe` has to be resolved from reading the shebang of the entry script (it actually reads the `dirname` of this path and looks up `pythonw.exe` in there, because the shebang also references the unwanted `python.exe`).
A quicker alternative to this could be looking up `streamlink-script.py`/`streamlink.exe` and `pythonw.exe` individually from the system's `PATH` env var, but that method is not good enough, as the user could have a global python environment installed and its path could be registered in the `PATH` env var before the one of Streamlink. That could lead to a python version mismatch. Reading the shebang of the entry script is therefore required.
But now, since there's no entry script included anymore in the installer, all you can do is try to read the shebang from the file embedded in the wrapper executable (a zip archive?!), and that's stupid. or you could guess a relative path from that file where `pythonw.exe` is located, but that's equally stupid.
----
The removal of the entry scripts from pynist is a breaking change, but they didn't bump their major version. We could fix this here (temporarily) by downgrading, or the removal could be reverted in pynsist if the dev(s) can be convinced.
Regarding pip, is there a way to make pip always ignore the binary, so one doesn't have to set the `--no-binary streamlink` parameter, like for example a certain packaging flag? | 2019-02-25T20:30:53 |
|
streamlink/streamlink | 2,358 | streamlink__streamlink-2358 | [
"2357"
] | e96c725cb553027dd1ca7b1c278211b57947b05c | diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -222,7 +222,7 @@ def clips(self, clip_name, **params):
# Private API calls
def access_token(self, endpoint, asset, **params):
- return self.call("/api/{0}/{1}/access_token".format(endpoint, asset), **params)
+ return self.call("/api/{0}/{1}/access_token".format(endpoint, asset), **dict(platform="_", **params))
def token(self, **params):
return self.call("/api/viewer/token", **params)
| pre-roll ads playing before twitch stream
<!--
Thanks for reporting a bug!
USE THE TEMPLATE. Otherwise your bug report may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed bug reports:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Bug Report
<!-- Replace [ ] with [x] in order to check the box -->
- [x ] This is a bug report and I have read the contribution guidelines.
### Description
<!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. -->
streamlink 1.0.0 on windows 10 64bit (latest updates) has a chance of playing pre-roll ads before loading the twitch stream. sometimes it will partially play the end of an ad (i.e. 1 or 2 seconds), sometimes the entire ad. sometimes the ad is low resolution (480/720), sometimes 1080p. sometimes you get expected behavior (no ads).
### Expected / Actual behavior
<!-- What do you expect to happen, and what is actually happening? -->
expected: play the stream straight away
actual: sporadic pre-rolls play, then the stream.
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. use streamlink 1.0.0
2. execute streamlink using cmd line "streamlink twitch.tv/sodapoppin best"
3. other twitch streams can exhibit the same issue, but not always
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a bug report!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
C:\WINDOWS\system32>streamlink twitch.tv/sodapoppin best -l debug
[cli][info] Found matching plugin twitch for URL twitch.tv/sodapoppin
[plugin.twitch][debug] Getting live HLS streams for sodapoppin
[cli][info] Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)
[cli][info] Opening stream: 1080p60 (hls)
[cli][info] Starting player: "C:\mpv-x86_64-20190224\mpv.exe"
```
### Additional comments, screenshots, etc.
configuration file is default save for player-passthrough enabled/default player changed to mpv.
video of the issue in action - https://mega.nz/#!HEBn1K4S!titCic2lUv4Hsz2c5LjY4TDvK2cjrHRS_Y_BbyO8COk
i'll stress that this is sporadic - sometimes i'll get an ad no matter how many times i load the stream. sometimes i won't get an ad at all. this first started happening for me on march 14th.
bonus: alternate player for twitch.tv plugin (chrome/firefox) has the same issue.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| Doesn't Twitch embed some ads directly into the HLS playlist?
I don't now why this issue is appearing now because the system (Twitch calls it SureStream apparently) was [announced 2016](https://blog.twitch.tv/introducing-surestream-for-a-better-video-ad-experience-on-twitch-3ca5ce3287c) (although it is labeled as "new" on the [Twitch Advertisements page](https://twitchadvertising.tv/ad-products/surestream/)). Maybe it's just a bunch of companies actually buying SureStream Ad-Spots?
correct, but it's never been an issue prior to this with either livestreamer or streamlink. partially played ads wouldn't be expected behavior on twitch's end, and ads triggered by streamers during their stream still don't play - imo, something has changed.
edit: ads triggered by the streamer now also affecting streamlink.
It's because you're using [player-passthrough](https://streamlink.github.io/cli.html#cmdoption-player-passthrough). When you do that Streamlink isn't handling the stream, the player you are using is. If you disable player-passthrough this shouldn't be an issue any more. If it's happening without `player-passthrough` then we can open this back up to see if other people get the error as well.
it's happening with player-passthrough disabled as well. video: https://mega.nz/#!HQo2hIDa!iKbbD0uRjICdtwHT3gc43aIrKVLxrBSrtqdjrZEn2pg
```C:\>streamlink twitch.tv/mendokusaii best -l debug
[cli][info] Found matching plugin twitch for URL twitch.tv/mendokusaii
[plugin.twitch][debug] Getting live HLS streams for mendokusaii
[cli][info] Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 900p60 (best)
[cli][info] Opening stream: 900p60 (hls)
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 3 to queue
[cli][debug] Pre-buffering 8192 bytes
[stream.hls][debug] Adding segment 4 to queue
[stream.hls][debug] Adding segment 5 to queue
[stream.hls][debug] Download of segment 3 complete
[cli][info] Starting player: "C:\mpv-x86_64-20190224\mpv.exe"
[stream.hls][debug] Download of segment 4 complete
[stream.hls][debug] Download of segment 5 complete
[cli][debug] Writing stream to output
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 6 to queue
[stream.hls][debug] Adding segment 7 to queue
[stream.hls][debug] Download of segment 6 complete
[stream.hls][debug] Download of segment 7 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 8 to queue
[stream.hls][debug] Adding segment 9 to queue
[stream.hls][debug] Adding segment 10 to queue
[stream.hls][debug] Download of segment 8 complete
[stream.hls][debug] Download of segment 9 complete
[stream.hls][debug] Download of segment 10 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 11 to queue
[stream.hls][debug] Adding segment 12 to queue
[stream.hls][debug] Adding segment 13 to queue
[stream.hls][debug] Download of segment 11 complete
[stream.hls][debug] Download of segment 12 complete
[stream.hls][debug] Download of segment 13 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 14 to queue
[stream.hls][debug] Adding segment 15 to queue
[stream.hls][debug] Adding segment 16 to queue
[stream.hls][debug] Download of segment 14 complete
[stream.hls][debug] Download of segment 15 complete
[stream.hls][debug] Download of segment 16 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 17 to queue
[stream.hls][debug] Adding segment 18 to queue
[stream.hls][debug] Adding segment 19 to queue
[stream.hls][debug] Download of segment 17 complete
[stream.hls][debug] Download of segment 18 complete
[stream.hls][debug] Download of segment 19 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 20 to queue
[stream.hls][debug] Adding segment 21 to queue
[stream.hls][debug] Adding segment 22 to queue
[stream.hls][debug] Download of segment 20 complete
[stream.hls][debug] Download of segment 21 complete
[stream.hls][debug] Download of segment 22 complete
[cli][info] Player closed
[stream.hls][debug] Closing worker thread
[stream.hls][debug] Closing writer thread
[stream.hls][debug] Closing writer thread
[cli][info] Stream ended
[cli][info] Closing currently open stream...```
Weird, alright let's open this back up and see if others can duplicate. I haven't seen it since I've been using 1.0 so hopefully some others will chime in.
You are not running Streamlink 1.0.0 if the environment debug infos are not showing up when using `-l debug`. Please don't cut this out from the log.
Are you able to reliably get ads when watching this channel via Streamlink (without passthrough)? If so, then you could check the HLS playlist content and see whether the ad-segments at the beginning have a different pattern. Example on *nix in bash (see the [`--stream-url`](https://streamlink.github.io/cli.html#cmdoption-stream-url) parameter):
```bash
curl -s $(streamlink --stream-url twitch.tv/CHANNEL best) | less
```
There's also the [`--hls-segment-ignore-names`](https://streamlink.github.io/cli.html#cmdoption-hls-segment-ignore-names) parameter for filtering out HLS segments, but that probably won't be of use here due to dynamic file names.
As @skulblakka already said, Twitch has (tried to) embed ads into the HLS streams almost two years ago, but I've never seen any ads since their announcement of that feature, and Twitch streams are basically running all day long on my system. However, I've seen a reddit thread today where users of uBlock origin were complaining about getting ads, too, but others not. Maybe they're doing a field test in a specific region or so because of GDC next week, who knows.
Regarding actively blocking ads in Streamlink, I don't know how to feel about this. There hasn't been anything implemented to specifically block ads. Ads simply happened to be served from an external source and were loaded by the web player from there, so being ad-free was just a "coincidence". Blocking ads on a website with user tracking also has a different motivation. Projects like Streamlink however are relying on access to their API and have to worry about not breaking ToS (to a certain extent).
> then we can open this back up to see if other people get the error as well.
I'm running 1.0.0 and I'm still getting it too. I'm also reliably getting ads on streams (including ad breaks).
Just to chime in before this somehow gets closed again and wiped from the board.
>
>
> You are not running Streamlink 1.0.0 if the environment debug infos are not showing up when using `-l debug`. Please don't cut this out from the log.
version check tells me "1.0" is available despite uninstalling and reinstalling the 1.0.0 windows binary.
edit: as per the other issue thread, an old streamlink installation was clinging to life in local appdata. proper debug:
```streamlink twitch.tv/destiny best -l debug
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.6
[cli][debug] Streamlink: 1.0.0
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0)
[cli][info] Found matching plugin twitch for URL twitch.tv/destiny
[plugin.twitch][debug] Getting live HLS streams for destiny
[utils.l10n][debug] Language code: en_GB
[cli][info] Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)
[cli][info] Opening stream: 1080p60 (hls)
[stream.hls][debug] Reloading playlist
[stream.hls][debug] First Sequence: 0; Last Sequence: 7
[stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 5; End Sequence: None
[stream.hls][debug] Adding segment 5 to queue
[cli][debug] Pre-buffering 8192 bytes
[stream.hls][debug] Adding segment 6 to queue
[stream.hls][debug] Adding segment 7 to queue
[stream.hls][debug] Download of segment 5 complete
[cli][info] Starting player: "C:\mpv-x86_64-20190224\mpv.exe"
[cli.output][debug] Opening subprocess: "C:\mpv-x86_64-20190224\mpv.exe" --title twitch.tv/destiny -
[stream.hls][debug] Download of segment 6 complete
[stream.hls][debug] Download of segment 7 complete
[cli][debug] Writing stream to output
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 8 to queue
[stream.hls][debug] Download of segment 8 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 9 to queue
[stream.hls][debug] Download of segment 9 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 10 to queue
[stream.hls][debug] Download of segment 10 complete
[cli][info] Player closed
[stream.segmented][debug] Closing worker thread
[stream.segmented][debug] Closing writer thread
[stream.segmented][debug] Closing writer thread
[cli][info] Stream ended
[cli][info] Closing currently open stream...
```
> Are you able to reliably get ads when watching this channel via Streamlink (without passthrough)?
If so, then you could check the HLS playlist content and see whether the ad-segments at the beginning have a different pattern. Example on *nix in bash (see the [`--stream-url`](https://streamlink.github.io/cli.html#cmdoption-stream-url) parameter):
>
> ```shell
> curl -s $(streamlink --stream-url twitch.tv/CHANNEL best) | less
> ```
>
> There's also the [`--hls-segment-ignore-names`](https://streamlink.github.io/cli.html#cmdoption-hls-segment-ignore-names) parameter for filtering out HLS segments, but that probably won't be of use here due to dynamic file names.
this is what the playlist shows from a stream that is realiably displaying ads.
```#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:5
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-TWITCH-ELAPSED-SECS:12585.683
#EXT-X-TWITCH-TOTAL-SECS:12601.683
#EXT-X-DATERANGE:ID="stitched-ad-1552712664-17602000000",CLASS="twitch-stitched-ad",START-DATE="2019-03-16T05:04:24.476Z",DURATION=17.602,X-TV-TWITCH-AD-POD-POSITION="0",X-TV-TWITCH-AD-URL="https://www.amazon.co.uk/Amazon-Video/b?node=13827483031&ref=vm_uk_pr_ao_pd10t",X-TV-TWITCH-AD-ROLL-TYPE="PREROLL",X-TV-TWITCH-AD-POD-LENGTH="1"
#EXT-X-DISCONTINUITY
#EXT-X-SCTE35-OUT:URL="https://www.amazon.co.uk/Amazon-Video/b?node=13827483031&ref=vm_uk_pr_ao_pd10t"
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:24.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtkEdcsEJYc3LSFyDx4HVFZUPbykuUNEFKh1duw5-szSzT9bTSyK5HsVPBNe00DeUF1QfAm6h1PYe0wVxepUoO_eLZx56gFW406ViTaBFV6Mr3namnHuKXRn2vY4_b1nbxJjWSotNIEdH57OE9QIKc1BvSFOcJRLKl-JCEinuK9IzI7V3PBmbhKV2VSTaNgjz4PWRgkSbVdKK3g8fwG3ccTDQhO6xmVumH4-am9uheM-YUpdUZly7Bze4oz1XZisGCnd1VqVxpw9IXsCjOVycKcnGHxhkpGVYK00hhbF2bUrqLUQ-bPrIAXDuHlQf4t9OmKBDUucnqhPxZMVu9azIO7Dz5uEpa75aNU0Axa1L2M5i7HCtgrDfRRiXrX7d6Xcgfk-CGhMkEvl-vrcYhP9nlEKir9vOdovfB7ws3cj5HQfTNX5PN04cTSdbP4SOCFcXWMqHZ4FX43XJEmC2XiRRocnRdtFiLvwfzeFmd9R-r9pZPHDuVZk96eGsdH0BbhQ0P3NiWc263IqhINA6ndhyLlcUXxNthyBJeOaEV6cs2YXlIyiBhJ8ofeklcJZjIWjm5hX6nyPs7U_o2N_7NHHdQ6LZY-DHQeeIV2K3-7aY93Hycgu41OtPxzrtWhYHcrkcYv30SNlNcMoc_HqlsD-vWuu5c_Mry8y82lVhQD0XIpXe3MgkPAeTlyFS1imAB8Endu2RwtkU-DuK2yaVqhTuMVsHhdTtweBCq9LAxEkJ5UKauX3Vew9i7SVkPzVaWyQ6d0cRKyttjeLc-AADrJMSWathXchoQ_FYACHtRIQvreE_LXmYuXh8pU0vZQDShoM0yfix0mORPLqqtnB.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:26.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtMDgyCiriU_O3FhDCIYbwpmxxbPXC-C1H36pYuWsdfocXH0JncYnW5jswxtoOm6of8AQEdg1xGXtlWyt-eTEtrSuVDR6WEwWjlpKKxssEw2E1Qv_roOWjY7H8JkPqctdKQXM1TkU7hmh1h0zXWbUAzwamK_4KsZieiOLjvVSh_5dnXdtclt7VplT6yyzUfU70iZVu_d2BSAgM0hRdnAEhbZEL9d4AwtyfI5SQKZaZJmFldlhoZzmKbuB9DrkwaBFQcd_366H0pM98YgYBu9CKTCa53CA2OUyJJqM-XVzpR-ACDEUEhfC2XressrAjok-3G6UiEFit2-70oAUXCIWugbOSBObGChRQNypyHmYiK8XxyziZ3qj-4lyaM705axsi1N3_YrNCCZl-ax8ZSTAwuQylfOaeZZ01RYtOQYJY5PiPJOADKscybIzUV8Xuse5F_Cc0CZEOHEob861Bl70xucPdWDIIbNCHq7RvFjCTQw2h3d8pyLgig5-KGM3vkhvHWvs-zsdWTLzr-HOKRfOBnIzZ9aqMlcrGxH8Pt6aQ1ofBqPJkcyTetrCAvj9-o9DQ-8BU8WypaGYY-EqApFymoceDOmL0TvqIw4wMwfpztg-rMcC-QSEJGLIFXOtu0cz_XVQpLedOQaDI5kYvR-rE1RABv3Sg.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:28.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtkE0S_5_h-cKh8qBdSboJerQY_Q-J9XbLEmiQVSKECw7ikCWoI_tD1HvYezEfwgyVyE_sCJS5GDFvql4mtkkfRW5n_Xc34f1WEHj57_gfS-seUafSHE3ARHEfBHYn17XEO7ppBzS8FWRcm4_LqrDpa1hbjXLEEUlxgastGph01DUwfiXE1fNXBhCZNwe0lYpITCsmylStHUnhKsWZ3vKbsAN-laSrp-gSneDnViMClH1CTU02yCVLOQ1B_AKGVL_et5hEcVJH32Rnfou_P0IKs5H-G8AKk4TRE8KzkGCIzKvGDcv3zZ5KpmlZibPMmVWmCBWjqvnNt6xd5LbgSCUdNGNufw-aeNa_jgEKf_jpKVZWkLJ2Mq3ViDNGkB_WXPV6J-5IwdEgPJEqIGuOvNUTT1BZAYjyHqnJerwMzBt_NB2VxNhxWxgstRU0jfB5gRXcrGr9AjRaSuk20h0Pe5axNnDwua63_iGsigCF1dK-tWDwlYY78uvXgTSH1K08fXtTk5pKNPuU90IOv9t4rhjCNkrgS_GvggDByUn_EJ-3BPARleOXZZDL19OVPDfur4z2on3W7atxhVWiIJ_-E0wPKPDXbLvwd8CHmCKRjyjwWG9XKCryl6MZ1-WoCtr3DBZBVJayVnTc6UbIMCzJ4JaNkchc565o9iHF-lRuw0z3M9Ro0Jrk_hmi_uK2xnwVaufdkcl12df1EkYyMFFFT8v5VGzzNg7K2abnxpzl9IA8O5P5zQxu4yM4ItYw5dwVVLoDoElHLZaGGkGkZErhxmYpSb_shRSDaxt7vbfRIQOWspjKfb18eqRnNxY5t-GRoMGaxvLENvk5ZSDS74.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:30.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtMDwTE8c8O6ttoep3Yn_NGUlyIrgO_5AY81oKOdQ-MOXw4UYdGAyC3CKyQRFv2PBNV67Yghxd6qCbMxuz4TJIGBffYzIy_d090u5Xwbpb9r_xHha8ygKFRUW7Ktm0uh21wM-cPFRzJgzMBmp1h4T3ZUPSHsuu_w8fvEfq1FzO2b1qQTv9EkjSGUPBkufOK37FzZH4wbrZ_Tgj9bXH3eVOc3TVK57NWpg8pkj0FoL5bfntI9DGipSjptvX_PEU0gJG9EtG3C9ZtS2NnpL1hZ7x-4S7LO3XB94xqGCka4MWrmJddsVBdp1wbulRgE-dVz74cbzAYZJSxFQlso15Sbtl5WmCCM-ncxju16wWbpaFvMtdkE46HCWKf9tPGX-np1Ep25K2XBzsaplGowN-m6CSVyhWdZvetwG4uovlKO0uN3h3Mb-9eAPFCAHbd-1eGCbHwN9JfPikzTcqUCg3BlCQpAVIyDcF1v15JmS1R-_RoX2-DlmkVgAyusuk2BeNTchXGsOH1zsJVVYE1uWLTdfqas27OUWTUn21CqA3sclWIoMUPrvqZcLzBwPr8bswyRn8CaLNmwfhwLvH4rFrFuXtCd4WccVxrqbC_eJckEH3Dw6KA6zh4SEDIXWSpPgaTM_wMwErkz1IgaDMcRlbVkDIkLu2XzAA.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:32.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtkEJmIGK5yd7V4VwOmg6FQtDzDN6V_ZF5JpXzjAh1tzNONSdNJrH7zYhFiMjDz69SX0fgtEeMThnfiFcU6JSfTs0gDFWBjKoz2PoV16o3O2jfS7pk46Ed99FWduZiq-_uWJ55pUVp9jp3B4HFUnvxRyTkZZKt9mwjVZnFO2iO47uCtPSXwuvLnlWFHZsamEFWjPL-G7S2qwgBjd3ys4Ep3Iu9oBBcxk3gkZ4V6Sl6DyYgWBYXlh1dG6lBw9tMEtbeO9U07K4jDXsmWHGgxchXPcGqO0Z_LioKrN0hYym7SL1zQJDgLRKZbjIoeYYTLCyeIhD_T89OdrL-ZqqxRpkuWUPEeCo1-zKUNDj3Egi-pR3I-zDVlRjlHlCDTFIvZFW6u-bt0lXlA2nfsgxJqkc4zWDKTplvjSXUsiVPAwP3SaXwwU2C8N-C9mPXlbTEVoyV8dHbIGT6dQGIVAqUvRf5oXvaZLfqCbz2Kuheh5Y8AqYyvyu7U6-nVaZCoBVKzBP-kW-iN69vUTBsFBC_htrgDfvT8jBBfPOxlF8YLZN9gudA9lQIPC-jJYB4Yh5eYjLb_nZxwhETONVe4jH7IzyFlnzOgpFcWpqlGeNZH8xEaRVxf0eV6x3rHE0x9MrAbEwuBV7ILVor09oRzpBDvJ_Vc5Ed6IrlDPb0Lza4TfGaakaYVxkssEp1FMHJgSJekh6_N5jrcYNJmxq2-auXIiXXHCB0tSwStgr53oaJ66DU6mzWMsY87G8X3J7bSG4ZD0mHrXS7hTQYId2MGL5PVl0EImDuJCeZ2oGMuCcBIQ71Io-j7_sR_jKzfuLB8MsRoM7P6fzmYy6C8RD9en.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:34.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtMD0TSxM5isO4E5aB0NwQDwsaO8uCcSunpxeWQwiC_k7odD20wW9zq_flghLiGmsahchqCOV4pdYcF7xOVNf_ejGicPUAAYEw0f3TYSCW4w6a-mK2NlUn4AdODmAvO1sQZhZnUIV0ieRVAhhKqzKT01WTwpjZ1-s1NAZITryNMk-pzWWR7PRITdCQisIrCvi0mDdlRchmItaqoNFKBcaFFtiTXHZryi2VU5mVZuuzmfu9HpGaj1tHXzaIxbtug-19Q8bf4MXNFoVqqdasDEjib0uqzrehW6JQXWMK0aYVjipCIOIpsB0GuRId6Tt6ZMbo-t12HKmxX4GErZxV2qdbNI_PHvctBJ7ST4pDkUAT7SVzVZUgdu3g5XJ78A6Kbed1m2uZ0vsCRtqfBNU_LobKelEIm0JB1cUga2PSVH61SGDVBiY7Et4AUoE5JyYkc-wWrMAKgoogf0TH2A89xARnd8SO79vCWcBrYas7wAkB6Wmjn-sWNrdYCvLjAYfJuMT5Ds2qkHnQTCfOubYhIHcWJr79twtHFyEL7mw8SZruzUoMy1BunWponwA2iiy9vD2qWRYfZwBvv7bPq-x4h0fiA6674ybI1k3zEVvUL9REj0Rr4azE4SENvpJeLMLkmsaFjRZX7_H98aDG27NWppNEs_q8K8Uw.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:36.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtkENa_3lEq-XBzyT6pEf7Fl6IYtQtf1pNkFic1TnGNhxFMRoEednlJgcukf3GHAfs9goMGvFvCCDfZyrjCYIebq0GLRwyC8V3IxShc7KiZs3BNyf03Kl504K1qoTt-OqzfluJ7e7m42KDhvNhDNrpieRjNGLMn_qtJE3a_e4oJCZS-gMoYygsGz7X4X1VU0uKQ9XLLfG_9jOc2ukRSVBZfyWWc02Pp1N9fSC3v0eDIUy9wlS9cpX9VCbqVZYIZ9IAz8McKtBebMnAaBPOIh3uUSPulBovEjk3hKRgeAq0SnkvLL17zgg7YYjNFZ7YaV_Uk-t97Iz7UgPOdfDz8WoojWxIdgjC-M098zThx9c83axgKHG9WeFdZP5tTGDX4swzwGVfNFoDjT0aFNDEzC6DbtXYxNfeaaaOwZlV0Si5-Aip9qUIvUKdwyXIGGjS0Dq2hp6h7iJfWOfnnXlC4XyGLSsyaNc-iJ2lKXA4eG3MhMhFTlVfi0Rx0NF0Ox1qmaXi9HWevwNy0xYjFb6Q85ypHZpFJw-fEuRFW0D2IV6R8SlMrsFj456irFaxKtjIvp7VHrCcyhEvjt3tqqKXxFd2dFzdlNWjcb2tDxuNWJf0LyLbHDw41zDW7hfIMxVoklknyKwyamwfSaALqCFMsurdHKCC7ncc1qH0Wq12_b-iVIo4PY8OAxjiWUMOV_DbcXt4lCvTv8YyyRniD82FM37aJDdsf3z2pBDp5QNWIt0SJCQo-60Ul-2Ute1vkXU8b6k5eBBfFe9tXHTaACfu-UBdW3rbmarKqcEE0GFxIQ8K_72JT9Nu6m_y3GRnwuKxoMWWweq21VoBtq2bGj.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:04:38.476Z
#EXTINF:2.000,3648366870f93cffb39288a3cb7e2e2c-03-04-2019-00.00.03
https://video-edge-c67a94.lhr03.abs.hls.ttvnw.net/v1/segment/CtMDGTqRuj1R-QXWgkgziLLSua_d5gm40QVeTivAqV7kbTOTwHDQkSYqfnZ0qb3KTo3jxqOK4SbZIVhqlOGG4xmUsbAQHyCzHc_DU4P0Myae7w2erpgfWK87SFbOFqJNhpqnusrXZIxQojledAOVHkFftzVw5R4Fr7YA_bUY4htvvCLf4YjGxrfKCvki0p5r2DSXEvgrS7qhtefDzw3dW8hlPA-hWyDtgRmG_a5lmIFjxn7_AhnVUvYFIQBgzdFNyLNmqtHEJjHasDRPMUGBLRFvIqaIWxwpUraLn2bN-h05Bb_g6DpiBfVZ5LVnI64-UETKBFsO_zfpOZhxej4MDgyMPvXswvg3g-WQy1NiqZQ2naJ-RNYwVy2V3LU39OXey26e5zYalgryEKRNtFWzWzjG1IaMeLnNrQZ3H-16lK2C5NGO6jPG3SmqB-GGD3JwarrCWKuXRIlIYRBSuXk2VIvT5RfJHyygopvz6pcQnfurcE-MvKxZvWkMCNRalpe_pWKwEm0RuavaHtkgwpSdwBSDE9i9mxYZT_cdhGR8nNfkDqr_PWiGN_gvpKu7G9bJMX72H_oFMq-mwtx3jqJmxLlnCDS35US7xhUSGH-FzA-U8mwnxC4SEIwpvU3RSHJrQquPdNwJ3EUaDDhptrUqFPJUuBJf-A.ts```
The playlist is indeed different for the HLS ad segments vs live stream segments. I need to download the playlist a few times to ensure it includes both ad and live stream segments.
Note that the live segments are prefixed with `#EXTINF:2.000,live` while the ad segments aren't. This seems like something they could easily change though.
`streamlink --version
streamlink 1.0.0`
`streamlink --stream-url twitch.tv/tfue
https://video-weaver.syd01.hls.ttvnw.net/v1/playlist/CrYDff5aYKA19XXRE_GyftQTF1U5azuypA4VpL6zldptf-iPq1ayyCuU7496LQ1KmBf9-isCSbuLu73Xmc_Cdz2GE_dKAsCDRZ5XsUO_H4lZQpV30H7ypoEuA7O1i7R4WC7XAgIwxtCbMlF_Knp0iZmBYZeJuORZEqbygOd5C6yPaR2CGCxUMdVXtTJhgIptnDgtHwlBvGoUBHziRZmXDvNMD8wzRjsoxM2caCBRy7fQme8OWg_FZA-AALhf1QUxhu536WILF0WVw3oL2M5tIljQIq-tJIrrsYH5FqD0qbc5D27DLOKHFBWdmQk6jB_59-jWwfDE9G-7lbBZrkZDQ2R5rEhDjDkfz8W7dopgDKIs2Cz8TrB04HBzG5_Ywi4uFV7AdKGacc_yQkvabh8f6yG2A2hkIoPiuqajvEmk-0_cIFKfR5uQd_en1VbWRGCJtZLLy47X6Yqn21Ph1-rP3Wlp8UdxzPatdRTCZVWGuyWK84V9nkyafVQzf49HfWSamyVA64FMnXyhLqsjvv9m5lxj7hyDmmhy1dLkHcuPEgADcAyc-_segYYFuZ4TRoOT0WPkiOIUTKLXEhA8UPY5GtOddTEKwdQHeITJGgwCeDSchjJvNannfmU.m3u8`
```#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:5
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-TWITCH-ELAPSED-SECS:14632.000
#EXT-X-TWITCH-TOTAL-SECS:14657.164
#EXT-X-DATERANGE:ID="stitched-ad-1552713489-15163999993",CLASS="twitch-stitched-ad",START-DATE="2019-03-16T05:18:09.474Z",DURATION=15.164,X-TV-TWITCH-AD-POD-POSITION="0",X-TV-TWITCH-AD-URL="https://www.moosetoys.com/brand/fortnite/",X-TV-TWITCH-AD-ROLL-TYPE="PREROLL",X-TV-TWITCH-AD-POD-LENGTH="1"
#EXT-X-DISCONTINUITY
#EXT-X-SCTE35-OUT:URL="https://www.moosetoys.com/brand/fortnite/"
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:09.474Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CtQE5liiw6GK7ddulLbzeDSmBhKOtzxP65FTsMHcxnRFxOlc7kA6Nki-lc_Uw6iveok_oFAqL8DNgqPhtf-hlNWkdLJRtiMgA5_Tw_EBxWHJ4RFO_WfXDheJmwAyn7bGaqqbQzcLKdvRy5J4nMKdBVFuSw5FkK0h4uijoFwwV4J6t2xSPVsl1XN62QNCkr07DOrX_zARx91RPAqmceavwOtt9ZTWQ5OkOQRRGw1BcbxWGSoorFLmY_MSzigxA4IjT6UBf1bJ9_tvv-F7n4OA8ngnPD4kx9sFzmoQAZqi_dZvySXSeE9dljHKvn4m-8YEWKkNZqUETD4fXS1CHAiKNBEs_LAnZQIPAELHqkzeeqFQ-ef6Nowhu9RtoVn4AxCacAl1vq3zDtHLplpjA41APo3l7abwKb-q1pEg4caEp_L1DnHpGXmYSpt4WCg_Od4ArzIAxYO_iuL6dgxA4keh-tVvqrYQ-B_HRwpH0MHPo0EyariZm_mpQ8dXPhmLRhQTZhzc0EWldR2iPw8Z_wJS_Lwr-_PMI3v54JWIsRa4w-rapqCW4bgUwj8G9v4_tjAdhAZA4uhLL1X--kWDp22EgN_fYLIN9hKv8bfT67OuIByO5bbUr8_8cZu3Nvqin365q2VFPWL1M7k_4upRwNwG6RFZ74SkuNg84JdUrvwOnNPtIANrw3X2OHhMVjadAzxlSUM3li1-djl_J28407QCrQ0KwnQy9iyPGudvBM-nPcPzhyvcp0c_4TMkAn1dAHGdiNUOqi5WK3oBd_h25upBNr4BOI_fRxMSEOrp9DBXAf3EIhVtuMEPt7oaDJeGrPzIuQCqfOYqlA.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:11.475999999Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CtQEKCJz97fIzMeLvJflkXdVgGoHnFGx9_rFiqNklkQ3PyaND9m6eFYZ1sjIr5NWv6GZ7fPiIpjvzES_Kq54U1J7EXj_q3BIGbhljCyB3BOkxLhpgLnr_BFHLOPE2U69dHJ3bvdQUfKNO7_DtdRByZ0nI5tWZaVJLn4W2rPKgROpwDDAedoesbIjgXHLqATdwp5lvoBNXa4-3Dncoe_FzHsdXJtbwkoJ_EDwfr03BFQnMHHxtno-KIt6pDGngVyyPThX-8b0Z5wp3_BpAQeAG6qDWcsgx_5qI_ezadJKK9TcmMA6DBRzvuPDsD8DeHOGV9rG_n6WNA43QDh3SWiEQXTsKIxGWWk6J5KdiKcLr0HlNuJWkpgjXHQ-yfBxuT0eZJiQGop3gp4WO_MjPBkc-SYMfXTdjni7qf9PUdjkcaB_7QYbwLxsMJvz01WxJ_OuiRiiw0zgPmm7inTMNp3DU9jvxI7GJlcWde3qSW_-J7Jydv5hifD-BeRBb3yVvX1p7khfecDI97uVPtRiDyBFcX_7uyWkJYsrLoATP8ZwK8pGZZ8p1o0H26ZTWWb2bbJ0-ImiUgk0dso0MMFzMLgImIO8MVjYd6CSbjNKFCf_25ombaAfbGgfdZ06k3igrwviZO2710vOxluyhnRfVZt4nqn6BxKwG0RJXFDm0Rn1gA-QY8WAo7mxzFp7gfPA3Dh2x__9dyo4yoklS-m2XtdTsoDlNOhBRg5fQq5C8-zu_Xj6j11NRwg5lWhGzv9txz-diX-LQ9VY-00wDSqDMikszRMdxCaEFKISEFw8HErtzpIQenzxQ1vYOtsaDAGqm9mPYKfH7tdaPw.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:13.477999998Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/Cs8DpeS36WirvgsGhKmrxQ8yn66N5Ox06Lm-pDhB7FH6SWbFkxO5Ut1JOi794UBizIkIVRxffhI8uQHve8NQ6-GsVL5SDtG6DbCuxWDiL7eZzTLTwkMPO7I0wgZq63St55OPApvNLPVMIAU9d8jHLz9VF6Gcr9C5D4WTIij6FpmcwgnZXbtYoFgYk1TczNrdubxFxa9-gpp2Bq-sTz55EGOJiUT98p9RXdMlK9yxR6rTQYM8E4xXlwqzrjH3vyQ9W6fN2PEmIwHE93rSKqNyckWY0LoAwnBiZjbV_a9o527LdYF5Yxmo-bXPbWimgNVbH384_ghbGv-z7DuO31QyvRuymHH7JlTGF6d6wL-noCpPbNE3fR2G4roAjdCsEbGE6K1y7IEXdlS1Mygd5wcZOJVvn_kYSfb4IVw6V4MGguR_xHFfI5PfRvyApBLlYVdN4--eRP5QkAtMeg4v2fdTo2B948xd6W47A-9VTOkFioO5zv8gCUBHYEW0rbzGlXvGJ6PWaqGhcco8orMLmAmxI1y81LHdnnVqvUzrsHi6jlsmZZz8RVdEXYKpsBRMwQPVU3kyVXfIQbN0zs0mvk5KwUqxi0v7DcHGHx3qZ8sGJdn3jhIQ06ivm-VWC4ps1GD00GLVcBoMTPxAtCpgP8CwB-41.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:15.479999997Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CtQEw3qW07BT-Au2YGqV_XvbUzpSQw5_XCuTVyeSDgvlm8RdZt4IpuZa0PTp8UtYuwk3uHmT0hn8oBtBXMAV7IPzuvfVy29Migh_JqP4u3J0BDpcoKg4x2PjHkGIATxrpF9J1f7EVSxbZx-XEgl7HZSvTL16iIXL58XksMKTWGQ52la9xTwTeaOnI9hvZ8a6fh5M-k-kNMljZsMO6KKCwfnqhZNmDAjm2qhxzn-EVTGvSwjH0ixNmfZkT57O5Zvwygnfm2R6Z9LOrdVlgk0UiY_tMTjfFCd1fV7GU5HzxoF-GHD44JpZiWHM5wxQ_mQrCymKvunzVSQa4GkwvRwbrrR_ebb27JV-plNytFyJQun1SDWzujqgM4ngfvlul4YdglJ_yd5vvpnP1VQtJIaycgt5i6dMRuvdpARUP0gBp57GKW6Syy5Vewbco2g-eKJjsrqqdJxmJppGCOsljH-E7vLDCw0S9vPX4-69xFHGmOJQd88OqRHK-ycx0cgKyfYvn5ydcSb_goXJJ9tPwkPV6OBlNkf5rPSaT4qsYKDbNXdg-8HM_NeuHUtzRlzpPeexXnuU8UEaKXJIHjeAVTCxf0t_l8pHkwSYGtT3QwsyQKoIkDMpu7Vnk2ybviKTPRvh4R2POCzXC8eCmmJVslKrXq_DhhgPT6Q7Pi_482rUjjSm_e6SWfFvrl9nZDNpQT8zw7HlG-bt0H-foQcnAtiA3HQFbYVwvGBDul_zpPQY7Pl5uXGpxd1gIPysc-qQ68QJ9cv2n3styopH8pfal9wEXtkw-Y8aOQsSEKOinDeDDh0wBNKl2kNG9EoaDNItuoPLn2687yOUrQ.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:17.481999996Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/Cs8DJIvtZeKT1-XGZYZ5RfeLlP2k3HbtTffKFlrpeQDYb8d_FLRMVA3YUbXeAbgSPDgg_a_PecB1Skgg7CgJ3VSJoLUYJeaqa5kw4KYtnYcFUbWwoM0V2UukzBUjJFT9YtwgCEyAe93eC0kMu-TZMV73q9m2DOY5lFfFLE_HK7xf3e3aa4BUhOG_1ja35zES8bEDx1-E7gqExJPOV7DRtDFts7fMvJKKHIxJR-OdIGe0Lirsr-dp560bGOjjz9-ONhcGXIHK8RL-UP8c5oudmzxkKmoodxPruD6de81bYs5QjDkHBjwqsEfRr4PQcme7bnMfw9N_OUzNo80zQORQLvA_DK1hMzCmC0c4U6CaEHFxTLsMuZqigqnomO377chV5w7YgE_dE1pE0oyT98V6thSVjsbAnYJztegRrn3ymtg35JB_8k_D7cUnGfruMlAhtKY10mc9Im1ib62X1UjBnF7VMvyOanLVvQeL0KX5zCrCWGgTgpJWqJA_D0XvRTXTkSQEo2GOdwiZQb2RkBbtaX4_WJijjB41APzPYhar6Y7NM5yNUFMKu2QwWKbHeygjon2zxVXSffCN0whXylIzUx85HKiOcPUQ-9HhJ9HuVIHFpxIQwwsCk-mpKvwnSO3bRRr5ABoMLfJFpHHn569yFj6l.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:19.483999995Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CtQEH7pdy1nqH4ax_3xaOCoov4OH5Esb81AAfHbhK-VWPwB7ao92sITh4-IFFTl0ctAXemi0DMET1xyFjNyurQQ65cPkzvIg9ZDkWGe3gbeK-CazcyItvB2biter4BGwX4o3aVq6G4yDtZzpxu0Gs75iD2p_hmBxcdFd-iWus2v1SEkS9R6UXgrDQy6FhVithK-DoQw-hiCrEC_qlc00ABWSyhDRxUOTpTSpweSbru1Dc-OczXLx9D867Sm75VX19xg9n890pv_Cdnq2pqVhTvhhMi0hNY6o0rJ95-cMqkYf2ht_spmS3DwcS8rGqqkdfguSMSN7nKZwnfVhnNlXN_nKTFc21U1u0cD_f8xQPLkxmVVx3r4GW-QPQCRu_FzilxPQNc8vaJA2kCmqaqWdIoARgkvWqssOsKGM_iTcVeOmBJ4X9ODIzynsubeYI_exJy7DRtX1DYS-CkUr5fTZlWQzAjs9u3QHEPKtDsX914ITCN01Kicm62mzUWMPLdcqhzZ7X4UzptmIh4RHmPP_d2V1L8d88ZpjbCsGrNNXrOXAy1qAXU-QxHy4vFZfmBYLIInKgOTKe33zzaRc7vav5ySB2rhqcxq-P6nM3KOSPcDoZqJ_JHkO4ooAYoiNhxzaOqVoLNemDs0fWliAmslwfM__VQjqGWBkHp_VxK-XrUl9RDhe2cyy5V4qHKW4AAiX0Q26W0eXCbENUH9d5GkJAgW84lf4xS8hooRLL91kw07WKRrD6GKcsrEjtgOdgG1wH33a4lnhPcVfnWWezh1-ErCuQiA5pfMSEKhpN6_lxjMOMBU2MscR0E8aDEhLG3MO4q39YEdukA.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:21.485999994Z
#EXTINF:2.002,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/Cs8DrWQonyJtr2R1ZicafFyXovVNRVLVESPA6jFdDr7zzMp5qwOqCyMRSxizfImbA2nZxgfKnZZjO7WRuaUU5xGP4l48GPAfQTujBY00gRm01c-SPuNWG4ytN46JvJyi3cFoJwAcKC6GmXKue4MpI0iKOxHwWifasumoHnUh42b5T2dohBg3iXqn1DkWytv2-pXsZ-v_wwjlQ4FMe93RzucKE8C21SZInJ7-i705wWPbXGfwrYzGdR1_wb3Zma6d8-wSUfaAhu31yHSBsbXxLYnM4Ox0dJtmg1ssPT3F63Z36KPpKfJOQObZTQvL4QnwJhzfmoyROvQsEsemzU2zEZzdlORdS3KkdJeR4M3iWxXJvrx37lo04ISWeE9yi4QHl5RoUdJgU3t_8-6652Ure5bd7k4CCCInGahEpxVI12DV6yCLFLkVmLK7oB7nXO83bybOHe5RgII9dhxqwWs8M2xMQmCFTuEz-mm0wKC638f76Y_jgxMkJdB_V8chq5a6MxR_f78zfIBGjTieUzOpg4EcKOB32zbtQG4iySassfCcFMZQgqSkNKVG2ZJLwS6D7NkmKsVF_hPypwSAvfvfkceYZ3e0DiksIcYfBjnRi8rsQhIQlJeMSFqUcVYC5VPfBsrZVRoMQ436aeP_CztrcLX4.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:23.487999993Z
#EXTINF:1.150,87d22d0b208d6a47c3bba6f412f7fb43-03-04-2019-05.03.22
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CtQEPTRDLrhBigT90xbGBPM9e3jpEdYNg7BzDnAS3dc1RhfZ9H7YHTGm72a6SVPuTJLTiDI8QGhcoROLpVOWT1OjCo5wwL1jafaL0-jkVj5IbMu5xmt7z52OsyHhaM8l1m5MoLJm3Dp8UOBKGyW8aercCTd7jOLtwbVbZY04rZ5xWZu-1i1L5CHF8mOPuV4_Cq5dgRQyldaOw2OOLgLTJPfuABheNrNMLeVKx_RHAqUsNiWxsJoY9-S9YjmYq0U8Xo3BARhpCcnagcIPGnv_Q-1kfn0khhTIXpaW8BkvK2xL6P3EibVWt6ycW-rLmtN8PlSeKImQB8f_2nnN1LiQfY8_m8QsA6cJwtpADhDZoVbGw353vJO5BrGg9drdskWkYpyDSlBBPPXifOvc4NEGbOdpw2U-KuQYiE-KiEi_YnpCV4flLSr54q1hYzqQye1Q18TIns7oUblLIC3Pt8GzVboYaUDNwsxuYWL7wpLJxVJ3pXOh_JSqL9wrD91G0s-mFa63i1gQKYnYXsJ5yQSaeCiVMt8OJzgqfRasoReIAtHipaAF2P75j0dQ7n_gYLn8pxg8h9gpQJEFDZTU7O1Vo80LJkV1gVkEpJlSQy7cQewsd5Q7k8mbE6dWnQefjm1qhlMPcmD1EyAefLOCvztCIEwKGHc3oiFo8yArAuQqcY58fCbN709zHwJUL1rIMOXd7TxUcY88L3jOzJAUYpef3rl-bu_olydGY4TRjZ18zy7ez-Cv-2DhLftxA-LkoJDRmOQgTNyBXQIl9_oo1Zc9ZwplzV7VtXYSEA2Swt_nIWzI7tky6PPeRnMaDEROAJjbpsZNb8UXiw.ts
#EXT-X-DISCONTINUITY
#EXT-X-SCTE35-IN
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:23.474Z
#EXTINF:2.000,live
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CssD9FUuObFo4POd_Ybn56nPDxWlkYk0yk_IqcU0DGDOwdcplu-73s3hEo6EIa-cbJHWfKoErokSGEH_M43IW82cmrPw7Jxtfm6U622eqrgzDl4vfp11pB4UTQlFxw8nmddy7IloXdFGt_aJbLlkPBcTf8uqFCU9m2hsTCD06UCHUjQ-DQivpplluN_QfgSq7Zgipb8XdfQ4mjFJz4CjB2DX5w8dJ9zeGS9zUTfm324IHm6ESUC8msiqoIY362wLHmDTT9f2UsSKqRslmbohQBN7XRnbzSkibMrD46_mAnwiW-51u4uo3-le3Imlg0bS6XFtIx046QUTdOuofM3uoQWk14Bvy8ipFoImJGC4dri1YarMI9JgqkldeaD_upYbzu3igajZshWjqEPT5hV1oxLQjHgKQ_k3UWraihnj4ZB_pvZenlCHsnFfzjkZlbRY1eVl9uU9HN-DdYmAn5S7Oai0tJYnvKYNLheTsTuvHjR_pMcMIzFqFxs4jxphP3CfNMaQ-zHoQ07_gwYDXVQIBjvcgMERzczkJxhmTHdgn9z2NaIqnJlZYgeL479XOz2Ckx9-KdMe3drkxCASMbQ9y7o_CXpJztW1vEHSA_wFEhAuV2G9YjS2B740_7OYu8LTGgxfO-sxuamZP-ZYqhQ.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:25.474Z
#EXTINF:2.000,live
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CssDiTl8sU7PF7hjLzzoSPvHUGzeyB4PxpF2jSIbg1YYOpsmdZkXNNDNfkUcgyswKwSWnO6at1GdOoUBt8PeL-8vRRm9Qx0A7Tux9ADm9uft4MZUfJh_1PLfRqxz9qjj--nOOvcUM8e9vUnYvxCQc_Ir1QDYb6UEZ0384XrsPlOpjAuSwu0IkvriZt22Ukv4QktvVvV4AvRjlDydggp4Hq-F7cjEjziRdo659HUnvxwy2v35s6euo07SiqhetvGIk7Li9yPBxGLhJ1Ou8rEIyLP_IoQc52PXwx4Lb3NKJXV5laxx78nAZRMMcu18jFqcLZCM0o-FWZFBE3qaVIU_fyzhoD0lrOh6NXgeRepLf5F43FuTOLl8K2iHiK__J715TkmP7zQxPHPe_IlrDhmim7H4Peh8MBv97RtZTCTKLGqK4492GUKYOIIhH9eTqKSPyKtpmWaHE686C6gb2x1yweV6cIJhAduK6MrOEafIT8qMdGCJpX7UbMgbgIKiVkhahddftyuSKqZmBpgCicP4E04kdIQOGA3MUfvUaxQqnxjVDmwgw4-7QO2rFW-ECIQ7Jm-DZM5FXspSTK5iX4LK__tM--DEUz-EwxZfCx18EhBq44dvZnQmdZN4lonGP7kgGgyTOsw72VyZpEsGo-Q.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:27.474Z
#EXTINF:2.000,live
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CssDfoIX3KwXXkJI81wrRPRE1-rz35q0Z3IqSg9cJwiStDIqVHhkYsO62jHdsWnTpTkkvDBE8HqmFOu8Di3HRmLyuMnwdfGiYEh8r9Vcy2D-2geKLk-WWnfSmOgFNi2KPCTRRz0emA1KNi5w940szrR5K4CbLZrOu8mQ4PKfprKWeaaD4iAKsMAaVS2g1DLrZFayJKOdZK-WrXYwJ_WP9fp31f1CKGVMNJVljllvxWqk4d9jlFpke3aCFJJJ8VBAplGuOJ9E5agy0NFh_8hKJ8TC1qd0slFoyDDlXDeNXsZPy4_CaOp5hZA3wl4DDLNg8DR8u2ojHPkwF-lYE3rUR5Da1C8CV-LBDnHzzfEbzQyJvw-UZCDl8PN5Stn_JAXlf2drX82hsC-E6Rv47YCG4W9fhPI1EC1QX7WzGclEfgvU92ze7oJvwIWTp1LRPhZyygoI9bBEp2_XvECTeAjcUIOn60FoZA49H-ey70ulSSe9NCuiH2wLFZHFTmXHlF_YLjQCre6CffnwIOy_0cVQ_9gwdDcKiaEHcTJNDH5bqtG2OXL6YgMh6x93BpFa8DYCdDdxeWiIm6xPO-MqoMCXOV00IO5OF_EBQ48CpcgoEhCQ-KOBRF2Gb4BK7T4W6KuSGgwhUJffs3XS229gzU4.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:29.474Z
#EXTINF:2.000,live
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CssD_Ho-6B-GwcbeTR7ZsImVYwKMM5ioNlMzW2TYi1F0JQbQN-abmGkq7D4ZXm4_EiYnRkpXt-5fPv-4Q2nV3-ilb9IpvMR7McmDuCgiNjsYt11npSyYnm9YHJATD8Ey_ua3qmhG7Y3TC0WcyRHuTw8FKZjhgWCfCrNNT3f3b1tDMyczY4TTSqtLhorCRsYf7-QIEPoDufvr-OhN9LhGi2AyST-QU7BAEqsNtR9kpcF6WcGZKG0x-SVPOkx3EepJPEQaPQzsM_tg-S24p42UieHRXxcc2WBWJuKRBs80RLZSyJFw9aulmyI_oi8G6kYlRSiW5SO-8WKx0uyXVd4j0Zn2w-GyhUYLiEDKOioFgDWFi-tpc_kemAEiFPEtSZPSdBHoi5y00-2Nd28QaTCNJrcl1byRP_he6-rIFKlvvaBoMEVWGx8zd4GhbkaThDjubOHk5w3hGSdfarXj4PaGR-IvIL05TP4Y2WawI_kFk0ziJfr_Dvs-eERlFzKDI0wunAQR9eewQjo0cAvkG9b77HbdpJMcD2Xy7nYEmSH4Rl63gRoJgOEdxso0PR_DkHpar-tCnR_tJiiBSGKCvImIpYeEeomsAds32IvMCXNAEhDorEnz2q-lbkJ_0jHWSS0qGgyp-5X01I5v-OEkRwQ.ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-16T05:18:31.474Z
#EXTINF:2.000,live
https://video-edge-8c79b4.syd01.abs.hls.ttvnw.net/v1/segment/CssD1c8P64GbJexuXVdMBB6HLqh2nK6IDaU1Ua4MI_jCVmhO4GlLLeVeFBgCDs7nEOMb5Rc0U1sC__PeoIEr1zUQLTIE6NJw5TyGyXMEj6QlCoNmK4T6WBS6060P0nFOcOnhiTZXuNFZ2ZprNSAtVasjLgVwTyKpYFExswdsgsDGJH03RsZQsrFFNDtyMSMoWrSP13dEXfexm4e-arX15hb38HpHTJRx3sGq-OamtW8WI0-Ei7lvp84jAcAVMSayQnFpH8Q240oOPslPpWUF1dvhNVxtxbzZ_aSqrCx_irh2ZAct_TA3NXTp0o_P81Uv0c9DcMHUw9ykypinl6wwGHvbtliTio68EEUK1KT9DQhIGt-e95s2N6QxdhHOyzkFdpr4zGcNZwcCzXAI8w4UqmVMuGrJdciZqANaKjyN8SCYYVeiJh1wdoFzttEjSWyHhBMrEOzBDQMhQIAtMId6GvqfRLRDW6EusDZ1q5pm6dp7b-88IV7bFRumv_4k_8ztSxehy_MBnmL2M51UP4gdSchxulHE8vqhlLVHVuslzPoVGnyD3oy4bZQBTrwK7a5E-ER1ToPNoLkj5D4GTsnCcaXoBQu1OtH0EnVFi54aEhCtN3cHil0bIXAzU1EUalcXGgyU0oclPZz34lYjBTY.ts```
Thanks, I also just got an ad. Looks like the playlist containing the [`EXT-X-DISCONTINUITY`](https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.3) tag is the one with ads (and the following ones until the next tag). I wonder if those could simply be dropped...
According to [this ](https://github.com/instance01/Twitch-HLS-AdBlock) chrome extension the ad segments are marked as advertisements using the [SCTE-35 flag](https://en.wikipedia.org/wiki/SCTE-35)
Edit: A better source for the SCTE-35 messages in HLS might be Amazons own documentation on it [here](https://docs.aws.amazon.com/medialive/latest/ug/scte-35-message-processing.html).
Thus the beginning of the ad should be marked with ```SCTE35-OUT``` and the end with ```SCTE35-IN```
I can confirm this.
I just had a "twitch prime" ad for the first time today when I launched a stream.
Some more info:
While testing with Tfue's stream, Twitch isn't currently showing me any preroll ads in my browser while logged in to my Twitch account. I can consistently get preroll ads while opening his stream in private browsing mode though. It seems that Twitch may have saved a flag server-side to prevent showing me ads for some period of time.
Streamlink consistently displays the preroll ads on Tfue's stream every time. Using Streamlink OAuth to Twitch doesn't seem to help at all there.
Testing with other streams is inconsistent, Tfue's is one of the few i've found which will consistently display the preroll ad in Streamlink, it's probably a good candidate for testing while he remains live.
~~I made a small hacky modification to the [low latency test plugin](https://github.com/streamlink/streamlink/issues/1676#issuecomment-430304591) which prevents preroll ads from being shown in Streamlink, I still get an ad-length delay when opening the stream though so it's not particularly helpful.~~
~~Change line 378 from:
` elif line.startswith("#EXTINF"):`
To:
` elif re.match("#EXTINF:[0-9].[0-9]*,live", line):`
Make sure you keep the spaces preceding the line.
Note: Might break stuff.~~
Edit: Above change does break the stream after downloading about 16 segments. Left in case someone wants to expand on it.
I fear that Twitch will refuse to send you the live stream segments until the time when the ad would be complete and that there may not be a way around it.
A simple solution that works is to block the ip serving ads. Use wireshark and block the entire subnet.
Changing chrome user agent to "Blackberry --9900" prevents ads from appearing.
>
>
> Changing chrome user agent to "Blackberry --9900" prevents ads from appearing.
How does one do this in streamlink ?
Don't know if it's related but the Alternative Player For Twitch extension for Chrome and FF just started showing ads too (as of last night). Seems Twitch have changed something their end.
I'll comment here as there isn't an issue open on the uBlockOrigin repo and I don't have a reddit account.
The `https://api.twitch.tv/api/channels/XXXXXXXX/access_token?` request is what determines if server side ads are delivered. A regular request/response by a browser without an adblocker will look as follows:
`https://api.twitch.tv/api/channels/quin69/access_token?need_https=true&oauth_token&platform=web&player_backend=mediaplayer&player_type=site`
`{"token":"{\"adblock\":false,\"authorization\":{\"forbidden\":false,\"reason\":\"\"},\"blackout_enabled\":false,\"channel\":\"quin69\",\"channel_id\":56649026,\"chansub\":{\"restricted_bitrates\":[],\"view_until\":REDACTED},\"ci_gb\":false,\"geoblock_reason\":\"\",\"device_id\":null,\"expires\":REDACTED,\"game\":\"Path of Exile\",\"hide_ads\":false,\"https_required\":true,\"mature\":false,\"partner\":false,\"platform\":\"web\",\"player_type\":\"site\",\"private\":{\"allowed_to_view\":true},\"privileged\":false,\"server_ads\":true,\"show_ads\":true,\"subscriber\":false,\"turbo\":false,\"user_id\":null,\"user_ip\":\"REDACTED\",\"version\":2}","sig":"REDACTED","mobile_restricted":false}`
The token/sig are then used as part of the m3u8 request. Notice that in the response the 'server_ads' param is 'true'. If you modify the 'platform' param in the request to be something like '_' the response now has 'server_ads' set to 'false' and ads are no longer shown.
`https://api.twitch.tv/api/channels/quin69/access_token?need_https=true&oauth_token=&platform=_&player_backend=mediaplayer`
`{"token":"{\"adblock\":false,\"authorization\":{\"forbidden\":false,\"reason\":\"\"},\"blackout_enabled\":false,\"channel\":\"quin69\",\"channel_id\":56649026,\"chansub\":{\"restricted_bitrates\":[],\"view_until\":REDACTED},\"ci_gb\":false,\"geoblock_reason\":\"\",\"device_id\":null,\"expires\":REDACTED,\"game\":\"Path of Exile\",\"hide_ads\":false,\"https_required\":true,\"mature\":false,\"partner\":false,\"platform\":\"_\",\"player_type\":null,\"private\":{\"allowed_to_view\":true},\"privileged\":false,\"server_ads\":false,\"show_ads\":true,\"subscriber\":false,\"turbo\":false,\"user_id\":null,\"user_ip\":\"REDACTED\",\"version\":2}","sig":"REDACTED","mobile_restricted":false}`
Last time there were changes to the way they served ads they quickly made additional changes so it's likely that this method wont work for long.
Here is a test url which can be used with uBlockOrigin's userResourcesLocation (which changes the platform to '_' as mentioned above) https://gist.githubusercontent.com/pixeltris/1338ad540175499b90b3dc245de663be/raw/58154403783563f0370dd7a39bc1517c39a81c7c/gistfile1.txt
The ublock issue is here https://github.com/uBlockOrigin/uAssets/issues/5138
@vohzi
You can change HTTP headers via `--http-header "key=value"`.
Setting the `User-Agent` to `Blackberry --9900` does **not** prevent ads from being injected into the stream. I don't think they will check the User-Agent string, since it can easily be faked.
----
@pixeltris
Adding the `platform=_` GET parameter to the `access_token` API endpoint call seems to be working. But yeah, that's something they could fix very easily.
If anyone wants to try it, see this diff:
```diff
diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
index 410a22b6..17ce4e0b 100644
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -222,7 +222,7 @@ class TwitchAPI(object):
# Private API calls
def access_token(self, endpoint, asset, **params):
- return self.call("/api/{0}/{1}/access_token".format(endpoint, asset), **params)
+ return self.call("/api/{0}/{1}/access_token".format(endpoint, asset), **dict(platform="_", **params))
def token(self, **params):
return self.call("/api/viewer/token", **params)
```
The [SureStream page ](https://twitchadvertising.tv/ad-products/surestream/) says it is only available on desktop devices. Might be the reason why changing the platform parameter disables ad injection.
This isn't just limited to desktop devices. I am encountering ads using [Pocket Plays](https://play.google.com/store/apps/details?id=net.nrask.notifyme&hl=en_US) as well as of this morning.
>
> If anyone wants to try it, see this diff:
so far so good. no pre-rolls across multiple streams of varying sizes.
edit: no streamer triggered ads either.
>
>
> This isn't just limited to desktop devices. I am encountering ads using [Pocket Plays](https://play.google.com/store/apps/details?id=net.nrask.notifyme&hl=en_US) as well as of this morning.
if i load a pre-fix streamlink extracted url into safari for ios, ads will play. adguard pro for ios, however, still works for the official twitch app (forcing a system wide filtered dns using a local vpn). from memory, system level blocking works a similar way on android - my guess is if you were to do the same with the official android twitch app, you won't see ads. both apps might be passing along their respective platform strings - with dns/vpn intercepting the ad requests - while pocket plays is relying on similar methodology to streamlink. or maybe not, but worth a test.
Can
> @vohzi
> You can change HTTP headers via `--http-header "key=value"`.
> Setting the `User-Agent` to `Blackberry --9900` does **not** prevent ads from being injected into the stream. I don't think they will check the User-Agent string, since it can easily be faked.
>
> @pixeltris
> Adding the `platform=_` GET parameter to the `access_token` API endpoint call seems to be working. But yeah, that's something they could fix very easily.
> If anyone wants to try it, see this diff:
>
> ```diff
> diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
> index 410a22b6..17ce4e0b 100644
> --- a/src/streamlink/plugins/twitch.py
> +++ b/src/streamlink/plugins/twitch.py
> @@ -222,7 +222,7 @@ class TwitchAPI(object):
> # Private API calls
>
> def access_token(self, endpoint, asset, **params):
> - return self.call("/api/{0}/{1}/access_token".format(endpoint, asset), **params)
> + return self.call("/api/{0}/{1}/access_token".format(endpoint, asset), **dict(platform="_", **params))
>
> def token(self, **params):
> return self.call("/api/viewer/token", **params)
> ```
Can you explain how to apply that change so I can test it? Thanks | 2019-03-16T23:27:44 |
|
streamlink/streamlink | 2,372 | streamlink__streamlink-2372 | [
"2368"
] | 499301dd2720d9022c051c6004c3efebf217fc12 | diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -1,6 +1,8 @@
# coding=utf-8
+import logging
import re
import warnings
+from collections import namedtuple
from random import random
import requests
@@ -13,6 +15,8 @@
from streamlink.stream import (
HTTPStream, HLSStream, FLVPlaylist, extract_flv_header_tags
)
+from streamlink.stream.hls import HLSStreamReader, HLSStreamWriter, HLSStreamWorker
+from streamlink.stream.hls_playlist import M3U8Parser, load as load_hls_playlist
from streamlink.utils.times import hours_minutes_seconds
try:
@@ -20,6 +24,9 @@
except ImportError:
pass
+
+log = logging.getLogger(__name__)
+
QUALITY_WEIGHTS = {
"source": 1080,
"1080": 1080,
@@ -128,6 +135,82 @@
)
+Segment = namedtuple("Segment", "uri duration title key discontinuity scte35 byterange date map")
+
+
+class TwitchM3U8Parser(M3U8Parser):
+ def parse_tag_ext_x_scte35_out(self, value):
+ self.state["scte35"] = True
+
+ # unsure if this gets used by Twitch
+ def parse_tag_ext_x_scte35_out_cont(self, value):
+ self.state["scte35"] = True
+
+ def parse_tag_ext_x_scte35_in(self, value):
+ self.state["scte35"] = False
+
+ def get_segment(self, uri):
+ byterange = self.state.pop("byterange", None)
+ extinf = self.state.pop("extinf", (0, None))
+ date = self.state.pop("date", None)
+ map_ = self.state.get("map")
+ key = self.state.get("key")
+ discontinuity = self.state.pop("discontinuity", False)
+ scte35 = self.state.pop("scte35", None)
+
+ return Segment(
+ uri,
+ extinf[0],
+ extinf[1],
+ key,
+ discontinuity,
+ scte35,
+ byterange,
+ date,
+ map_
+ )
+
+
+class TwitchHLSStreamWorker(HLSStreamWorker):
+ def _reload_playlist(self, text, url):
+ return load_hls_playlist(text, url, parser=TwitchM3U8Parser)
+
+
+class TwitchHLSStreamWriter(HLSStreamWriter):
+ def __init__(self, *args, **kwargs):
+ HLSStreamWriter.__init__(self, *args, **kwargs)
+ options = self.session.plugins.get("twitch").options
+ self.disable_ads = options.get("disable-ads")
+ if self.disable_ads:
+ log.info("Will skip ad segments")
+
+ def write(self, sequence, *args, **kwargs):
+ if self.disable_ads:
+ if sequence.segment.scte35 is not None:
+ self.reader.ads = sequence.segment.scte35
+ if self.reader.ads:
+ log.info("Will skip ads beginning with segment {0}".format(sequence.num))
+ else:
+ log.info("Will stop skipping ads beginning with segment {0}".format(sequence.num))
+ if self.reader.ads:
+ return
+ return HLSStreamWriter.write(self, sequence, *args, **kwargs)
+
+
+class TwitchHLSStreamReader(HLSStreamReader):
+ __worker__ = TwitchHLSStreamWorker
+ __writer__ = TwitchHLSStreamWriter
+ ads = None
+
+
+class TwitchHLSStream(HLSStream):
+ def open(self):
+ reader = TwitchHLSStreamReader(self)
+ reader.open()
+
+ return reader
+
+
class UsherService(object):
def __init__(self, session):
self.session = session
@@ -277,6 +360,13 @@ class Twitch(Plugin):
action="store_true",
help="""
Do not open the stream if the target channel is hosting another channel.
+ """
+ ),
+ PluginArgument("disable-ads",
+ action="store_true",
+ help="""
+ Skip embedded advertisement segments at the beginning or during a stream.
+ Will cause these segments to be missing from the stream.
"""
))
@@ -640,9 +730,12 @@ def _get_hls_streams(self, stream_type="live"):
try:
# If the stream is a VOD that is still being recorded the stream should start at the
# beginning of the recording
- streams = HLSStream.parse_variant_playlist(self.session, url,
- start_offset=time_offset,
- force_restart=not stream_type == "live")
+ streams = TwitchHLSStream.parse_variant_playlist(
+ self.session,
+ url,
+ start_offset=time_offset,
+ force_restart=not stream_type == "live"
+ )
except IOError as err:
err = str(err)
if "404 Client Error" in err or "Failed to parse playlist" in err:
diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py
--- a/src/streamlink/stream/hls.py
+++ b/src/streamlink/stream/hls.py
@@ -181,6 +181,9 @@ def __init__(self, *args, **kwargs):
self.duration_offset_start, self.duration_limit,
self.playlist_sequence, self.playlist_end)
+ def _reload_playlist(self, text, url):
+ return hls_playlist.load(text, url)
+
def reload_playlist(self):
if self.closed:
return
@@ -192,7 +195,7 @@ def reload_playlist(self):
retries=self.playlist_reload_retries,
**self.reader.request_params)
try:
- playlist = hls_playlist.load(res.text, res.url)
+ playlist = self._reload_playlist(res.text, res.url)
except ValueError as err:
raise StreamError(err)
@@ -472,8 +475,12 @@ def parse_variant_playlist(cls, session_, url, name_key="name",
duration=duration,
**request_params)
else:
- stream = HLSStream(session_, playlist.uri, force_restart=force_restart,
- start_offset=start_offset, duration=duration, **request_params)
+ stream = cls(session_,
+ playlist.uri,
+ force_restart=force_restart,
+ start_offset=start_offset,
+ duration=duration,
+ **request_params)
streams[name_prefix + stream_name] = stream
return streams
diff --git a/src/streamlink/stream/hls_playlist.py b/src/streamlink/stream/hls_playlist.py
--- a/src/streamlink/stream/hls_playlist.py
+++ b/src/streamlink/stream/hls_playlist.py
@@ -19,24 +19,20 @@
Map = namedtuple("Map", "uri byterange")
# EXT-X-MEDIA
-Media = namedtuple("Media", "uri type group_id language name default "
- "autoselect forced characteristics")
+Media = namedtuple("Media", "uri type group_id language name default autoselect forced characteristics")
# EXT-X-START
Start = namedtuple("Start", "time_offset precise")
# EXT-X-STREAM-INF
-StreamInfo = namedtuple("StreamInfo", "bandwidth program_id codecs resolution "
- "audio video subtitles")
+StreamInfo = namedtuple("StreamInfo", "bandwidth program_id codecs resolution audio video subtitles")
# EXT-X-I-FRAME-STREAM-INF
-IFrameStreamInfo = namedtuple("IFrameStreamInfo", "bandwidth program_id "
- "codecs resolution video")
+IFrameStreamInfo = namedtuple("IFrameStreamInfo", "bandwidth program_id codecs resolution video")
Playlist = namedtuple("Playlist", "uri stream_info media is_iframe")
Resolution = namedtuple("Resolution", "width height")
-Segment = namedtuple("Segment", "uri duration title key discontinuity "
- "byterange date map")
+Segment = namedtuple("Segment", "uri duration title key discontinuity byterange date map")
class M3U8(object):
@@ -65,7 +61,7 @@ class M3U8Parser(object):
_tag_re = re.compile(r"#(?P<tag>[\w-]+)(:(?P<value>.+))?")
_res_re = re.compile(r"(\d+)x(\d+)")
- def __init__(self, base_uri=None):
+ def __init__(self, base_uri=None, **kwargs):
self.base_uri = base_uri
def create_stream_info(self, streaminf, cls=None):
@@ -142,97 +138,107 @@ def parse_resolution(self, value):
return Resolution(width, height)
- def parse_tag(self, line, transform=None):
- tag, value = self.split_tag(line)
-
- if transform:
- value = transform(value)
-
- return value
+ def parse_tag_extinf(self, value):
+ self.state["expect_segment"] = True
+ self.state["extinf"] = self.parse_extinf(value)
+
+ def parse_tag_ext_x_byterange(self, value):
+ self.state["expect_segment"] = True
+ self.state["byterange"] = self.parse_byterange(value)
+
+ def parse_tag_ext_x_targetduration(self, value):
+ self.m3u8.target_duration = int(value)
+
+ def parse_tag_ext_x_media_sequence(self, value):
+ self.m3u8.media_sequence = int(value)
+
+ def parse_tag_ext_x_key(self, value):
+ attr = self.parse_attributes(value)
+ iv = attr.get("IV")
+ if iv:
+ iv = self.parse_hex(iv)
+ self.state["key"] = Key(attr.get("METHOD"),
+ self.uri(attr.get("URI")),
+ iv, attr.get("KEYFORMAT"),
+ attr.get("KEYFORMATVERSIONS"))
+
+ def parse_tag_ext_x_program_date_time(self, value):
+ self.state["date"] = value
+
+ def parse_tag_ext_x_allow_cache(self, value):
+ self.m3u8.allow_cache = self.parse_bool(value)
+
+ def parse_tag_ext_x_stream_inf(self, value):
+ self.state["streaminf"] = self.parse_attributes(value)
+ self.state["expect_playlist"] = True
+
+ def parse_tag_ext_x_playlist_type(self, value):
+ self.m3u8.playlist_type = value
+
+ def parse_tag_ext_x_endlist(self, value):
+ self.m3u8.is_endlist = True
+
+ def parse_tag_ext_x_media(self, value):
+ attr = self.parse_attributes(value)
+ media = Media(
+ self.uri(attr.get("URI")),
+ attr.get("TYPE"),
+ attr.get("GROUP-ID"),
+ attr.get("LANGUAGE"),
+ attr.get("NAME"),
+ self.parse_bool(attr.get("DEFAULT")),
+ self.parse_bool(attr.get("AUTOSELECT")),
+ self.parse_bool(attr.get("FORCED")),
+ attr.get("CHARACTERISTICS")
+ )
+ self.m3u8.media.append(media)
+
+ def parse_tag_ext_x_discontinuity(self, value):
+ self.state["discontinuity"] = True
+ self.state["map"] = None
+
+ def parse_tag_ext_x_discontinuity_sequence(self, value):
+ self.m3u8.discontinuity_sequence = int(value)
+
+ def parse_tag_ext_x_i_frames_only(self, value):
+ self.m3u8.iframes_only = True
+
+ def parse_tag_ext_x_map(self, value):
+ attr = self.parse_attributes(value)
+ byterange = self.parse_byterange(attr.get("BYTERANGE", ""))
+ self.state["map"] = Map(attr.get("URI"), byterange)
+
+ def parse_tag_ext_x_i_frame_stream_inf(self, value):
+ attr = self.parse_attributes(value)
+ streaminf = self.state.pop("streaminf", attr)
+ stream_info = self.create_stream_info(streaminf, IFrameStreamInfo)
+ playlist = Playlist(self.uri(attr.get("URI")), stream_info, [], True)
+ self.m3u8.playlists.append(playlist)
+
+ def parse_tag_ext_x_version(self, value):
+ self.m3u8.version = int(value)
+
+ def parse_tag_ext_x_start(self, value):
+ attr = self.parse_attributes(value)
+ start = Start(attr.get("TIME-OFFSET"),
+ self.parse_bool(attr.get("PRECISE", "NO")))
+ self.m3u8.start = start
def parse_line(self, line):
- if not line.startswith("#"):
- if self.state.pop("expect_segment", None):
- byterange = self.state.pop("byterange", None)
- extinf = self.state.pop("extinf", (0, None))
- date = self.state.pop("date", None)
- map_ = self.state.get("map")
- key = self.state.get("key")
-
- segment = Segment(self.uri(line), extinf[0],
- extinf[1], key,
- self.state.pop("discontinuity", False),
- byterange, date, map_)
- self.m3u8.segments.append(segment)
- elif self.state.pop("expect_playlist", None):
- streaminf = self.state.pop("streaminf", {})
- stream_info = self.create_stream_info(streaminf)
- playlist = Playlist(self.uri(line), stream_info, [], False)
- self.m3u8.playlists.append(playlist)
- elif line.startswith("#EXTINF"):
- self.state["expect_segment"] = True
- self.state["extinf"] = self.parse_tag(line, self.parse_extinf)
- elif line.startswith("#EXT-X-BYTERANGE"):
- self.state["expect_segment"] = True
- self.state["byterange"] = self.parse_tag(line, self.parse_byterange)
- elif line.startswith("#EXT-X-TARGETDURATION"):
- self.m3u8.target_duration = self.parse_tag(line, int)
- elif line.startswith("#EXT-X-MEDIA-SEQUENCE"):
- self.m3u8.media_sequence = self.parse_tag(line, int)
- elif line.startswith("#EXT-X-KEY"):
- attr = self.parse_tag(line, self.parse_attributes)
- iv = attr.get("IV")
- if iv:
- iv = self.parse_hex(iv)
- self.state["key"] = Key(attr.get("METHOD"),
- self.uri(attr.get("URI")),
- iv, attr.get("KEYFORMAT"),
- attr.get("KEYFORMATVERSIONS"))
- elif line.startswith("#EXT-X-PROGRAM-DATE-TIME"):
- self.state["date"] = self.parse_tag(line)
- elif line.startswith("#EXT-X-ALLOW-CACHE"):
- self.m3u8.allow_cache = self.parse_tag(line, self.parse_bool)
- elif line.startswith("#EXT-X-STREAM-INF"):
- self.state["streaminf"] = self.parse_tag(line, self.parse_attributes)
- self.state["expect_playlist"] = True
- elif line.startswith("#EXT-X-PLAYLIST-TYPE"):
- self.m3u8.playlist_type = self.parse_tag(line)
- elif line.startswith("#EXT-X-ENDLIST"):
- self.m3u8.is_endlist = True
- elif line.startswith("#EXT-X-MEDIA"):
- attr = self.parse_tag(line, self.parse_attributes)
- media = Media(self.uri(attr.get("URI")), attr.get("TYPE"),
- attr.get("GROUP-ID"), attr.get("LANGUAGE"),
- attr.get("NAME"),
- self.parse_bool(attr.get("DEFAULT")),
- self.parse_bool(attr.get("AUTOSELECT")),
- self.parse_bool(attr.get("FORCED")),
- attr.get("CHARACTERISTICS"))
- self.m3u8.media.append(media)
- elif line.startswith("#EXT-X-DISCONTINUITY"):
- self.state["discontinuity"] = True
- self.state["map"] = None
- elif line.startswith("#EXT-X-DISCONTINUITY-SEQUENCE"):
- self.m3u8.discontinuity_sequence = self.parse_tag(line, int)
- elif line.startswith("#EXT-X-I-FRAMES-ONLY"):
- self.m3u8.iframes_only = True
- elif line.startswith("#EXT-X-MAP"):
- attr = self.parse_tag(line, self.parse_attributes)
- byterange = self.parse_byterange(attr.get("BYTERANGE", ""))
- self.state["map"] = Map(attr.get("URI"), byterange)
- elif line.startswith("#EXT-X-I-FRAME-STREAM-INF"):
- attr = self.parse_tag(line, self.parse_attributes)
- streaminf = self.state.pop("streaminf", attr)
- stream_info = self.create_stream_info(streaminf, IFrameStreamInfo)
- playlist = Playlist(self.uri(attr.get("URI")), stream_info, [], True)
+ if line.startswith("#"):
+ tag, value = self.split_tag(line)
+ if not tag:
+ return
+ method = "parse_tag_" + tag.lower().replace("-", "_")
+ if not hasattr(self, method):
+ return
+ getattr(self, method)(value)
+ elif self.state.pop("expect_segment", None):
+ segment = self.get_segment(self.uri(line))
+ self.m3u8.segments.append(segment)
+ elif self.state.pop("expect_playlist", None):
+ playlist = self.get_playlist(self.uri(line))
self.m3u8.playlists.append(playlist)
- elif line.startswith("#EXT-X-VERSION"):
- self.m3u8.version = self.parse_tag(line, int)
- elif line.startswith("#EXT-X-START"):
- attr = self.parse_tag(line, self.parse_attributes)
- start = Start(attr.get("TIME-OFFSET"),
- self.parse_bool(attr.get("PRECISE", "NO")))
- self.m3u8.start = start
def parse(self, data):
self.state = {}
@@ -272,8 +278,32 @@ def uri(self, uri):
else:
return uri
-
-def load(data, base_uri=None, parser=M3U8Parser):
+ def get_segment(self, uri):
+ byterange = self.state.pop("byterange", None)
+ extinf = self.state.pop("extinf", (0, None))
+ date = self.state.pop("date", None)
+ map_ = self.state.get("map")
+ key = self.state.get("key")
+ discontinuity = self.state.pop("discontinuity", False)
+
+ return Segment(
+ uri,
+ extinf[0],
+ extinf[1],
+ key,
+ discontinuity,
+ byterange,
+ date,
+ map_
+ )
+
+ def get_playlist(self, uri):
+ streaminf = self.state.pop("streaminf", {})
+ stream_info = self.create_stream_info(streaminf)
+ return Playlist(uri, stream_info, [], False)
+
+
+def load(data, base_uri=None, parser=M3U8Parser, **kwargs):
"""Attempts to parse a M3U8 playlist from a string of data.
If specified, *base_uri* is the base URI that relative URIs will
@@ -283,4 +313,4 @@ def load(data, base_uri=None, parser=M3U8Parser):
to parse the data.
"""
- return parser(base_uri).parse(data)
+ return parser(base_uri, **kwargs).parse(data)
| diff --git a/tests/plugins/test_twitch.py b/tests/plugins/test_twitch.py
--- a/tests/plugins/test_twitch.py
+++ b/tests/plugins/test_twitch.py
@@ -1,6 +1,17 @@
+import logging
import unittest
+from functools import partial
-from streamlink.plugins.twitch import Twitch
+from streamlink.plugins.twitch import Twitch, TwitchHLSStream
+
+import requests_mock
+from tests.mock import call, patch
+
+from streamlink.session import Streamlink
+from tests.resources import text
+
+
+log = logging.getLogger(__name__)
class TestPluginTwitch(unittest.TestCase):
@@ -21,3 +32,158 @@ def test_can_handle_url_negative(self):
]
for url in should_not_match:
self.assertFalse(Twitch.can_handle_url(url))
+
+
+class TestTwitchHLSStream(unittest.TestCase):
+ scte35_out = "#EXT-X-DISCONTINUITY\n#EXT-X-SCTE35-OUT\n"
+ scte35_out_cont = "#EXT-X-SCTE35-OUT-CONT\n"
+ scte35_in = "#EXT-X-DISCONTINUITY\n#EXT-X-SCTE35-IN\n"
+ segment = "#EXTINF:1.000,\nstream{0}.ts\n"
+
+ def getMasterPlaylist(self):
+ with text("hls/test_master.m3u8") as pl:
+ return pl.read()
+
+ def getPlaylist(self, media_sequence, items):
+ playlist = """
+#EXTM3U
+#EXT-X-VERSION:5
+#EXT-X-TARGETDURATION:1
+#EXT-X-MEDIA-SEQUENCE:{0}
+""".format(media_sequence)
+
+ for item in items:
+ if type(item) != int:
+ playlist += item
+ else:
+ playlist += self.segment.format(item)
+
+ return playlist
+
+ def start_streamlink(self, kwargs=None):
+ kwargs = kwargs or {}
+ log.info("Executing streamlink")
+ streamlink = Streamlink()
+
+ streamlink.set_option("hls-live-edge", 4)
+ streamlink.plugins.get("twitch").options.set("disable-ads", True)
+
+ masterStream = TwitchHLSStream.parse_variant_playlist(
+ streamlink,
+ "http://mocked/path/master.m3u8",
+ **kwargs
+ )
+ stream = masterStream["1080p (source)"].open()
+ data = b"".join(iter(partial(stream.read, 8192), b""))
+ stream.close()
+ log.info("End of streamlink execution")
+ return data
+
+ def mock(self, mocked, method, url, *args, **kwargs):
+ mocked[url] = method(url, *args, **kwargs)
+
+ def get_result(self, streams, playlists):
+ mocked = {}
+ with requests_mock.Mocker() as mock:
+ self.mock(mocked, mock.get, "http://mocked/path/master.m3u8", text=self.getMasterPlaylist())
+ self.mock(mocked, mock.get, "http://mocked/path/playlist.m3u8", [{"text": p} for p in playlists])
+ for i, stream in enumerate(streams):
+ self.mock(mocked, mock.get, "http://mocked/path/stream{0}.ts".format(i), content=stream)
+ return self.start_streamlink(), mocked
+
+ @patch("streamlink.plugins.twitch.log")
+ def test_hls_scte35_start_with_end(self, mock_logging):
+ streams = ["[{0}]".format(i).encode("ascii") for i in range(12)]
+ playlists = [
+ self.getPlaylist(0, [self.scte35_out, 0, 1, 2, 3]),
+ self.getPlaylist(4, [self.scte35_in, 4, 5, 6, 7]),
+ self.getPlaylist(8, [8, 9, 10, 11]) + "#EXT-X-ENDLIST\n"
+ ]
+ result, mocked = self.get_result(streams, playlists)
+
+ expected = b''.join(streams[4:12])
+ self.assertEqual(expected, result)
+ for i, _ in enumerate(streams):
+ self.assertTrue(mocked["http://mocked/path/stream{0}.ts".format(i)].called)
+ mock_logging.info.assert_has_calls([
+ call("Will skip ad segments"),
+ call("Will skip ads beginning with segment 0"),
+ call("Will stop skipping ads beginning with segment 4")
+ ])
+
+ @patch("streamlink.plugins.twitch.log")
+ def test_hls_scte35_no_start(self, mock_logging):
+ streams = ["[{0}]".format(i).encode("ascii") for i in range(8)]
+ playlists = [
+ self.getPlaylist(0, [0, 1, 2, 3]),
+ self.getPlaylist(4, [self.scte35_in, 4, 5, 6, 7]) + "#EXT-X-ENDLIST\n"
+ ]
+ result, mocked = self.get_result(streams, playlists)
+
+ expected = b''.join(streams[0:8])
+ self.assertEqual(expected, result)
+ for i, _ in enumerate(streams):
+ self.assertTrue(mocked["http://mocked/path/stream{0}.ts".format(i)].called)
+ mock_logging.info.assert_has_calls([
+ call("Will skip ad segments")
+ ])
+
+ @patch("streamlink.plugins.twitch.log")
+ def test_hls_scte35_no_start_with_cont(self, mock_logging):
+ streams = ["[{0}]".format(i).encode("ascii") for i in range(8)]
+ playlists = [
+ self.getPlaylist(0, [self.scte35_out_cont, 0, 1, 2, 3]),
+ self.getPlaylist(4, [self.scte35_in, 4, 5, 6, 7]) + "#EXT-X-ENDLIST\n"
+ ]
+ result, mocked = self.get_result(streams, playlists)
+
+ expected = b''.join(streams[4:8])
+ self.assertEqual(expected, result)
+ for i, _ in enumerate(streams):
+ self.assertTrue(mocked["http://mocked/path/stream{0}.ts".format(i)].called)
+ mock_logging.info.assert_has_calls([
+ call("Will skip ad segments"),
+ call("Will skip ads beginning with segment 0"),
+ call("Will stop skipping ads beginning with segment 4")
+ ])
+
+ @patch("streamlink.plugins.twitch.log")
+ def test_hls_scte35_no_end(self, mock_logging):
+ streams = ["[{0}]".format(i).encode("ascii") for i in range(12)]
+ playlists = [
+ self.getPlaylist(0, [0, 1, 2, 3]),
+ self.getPlaylist(4, [self.scte35_out, 4, 5, 6, 7]),
+ self.getPlaylist(8, [8, 9, 10, 11]) + "#EXT-X-ENDLIST\n"
+ ]
+ result, mocked = self.get_result(streams, playlists)
+
+ expected = b''.join(streams[0:4])
+ self.assertEqual(expected, result)
+ for i, _ in enumerate(streams):
+ self.assertTrue(mocked["http://mocked/path/stream{0}.ts".format(i)].called)
+ mock_logging.info.assert_has_calls([
+ call("Will skip ad segments"),
+ call("Will skip ads beginning with segment 4")
+ ])
+
+ @patch("streamlink.plugins.twitch.log")
+ def test_hls_scte35_in_between(self, mock_logging):
+ streams = ["[{0}]".format(i).encode("ascii") for i in range(20)]
+ playlists = [
+ self.getPlaylist(0, [0, 1, 2, 3]),
+ self.getPlaylist(4, [4, 5, self.scte35_out, 6, 7]),
+ self.getPlaylist(8, [8, 9, 10, 11]),
+ self.getPlaylist(12, [12, 13, self.scte35_in, 14, 15]),
+ self.getPlaylist(16, [16, 17, 18, 19]) + "#EXT-X-ENDLIST\n"
+ ]
+ result, mocked = self.get_result(streams, playlists)
+
+ expected = b''.join(streams[0:6]) + b''.join(streams[14:20])
+ self.assertEqual(expected, result)
+ for i, _ in enumerate(streams):
+ self.assertTrue(mocked["http://mocked/path/stream{0}.ts".format(i)].called)
+ mock_logging.info.assert_has_calls([
+ call("Will skip ad segments"),
+ call("Will skip ads beginning with segment 6"),
+ call("Will stop skipping ads beginning with segment 14")
+ ])
| Twitch Pre-Roll ads (even on audio_only) -- Yes, tested using git snapshot post "fix"
- [x] This is a bug report and I have read the contribution guidelines.
The previously closed issue #2357 is still happening and I have reproduced it after manually installing a git checkout from about 10 min before this bug report.
Current test URL:
Even audio only (though the example was captured at another resolution)
```
streamlink twitch.tv/zisteau audio_only
```
Will display an actual VIDEO ad, also completely ignoring resolution or bandwidth use desires.
Occasionally the mismatch between the ad and the stream also causes the audio to playback in an oddly corrupted way (the streamer sounded down-pitch shifted, and the audio was very studdery, but that was a result of the ad invasion).
```
streamlink --loglevel=debug twitch.tv/zisteau 480p 2>&1 | tee streamlog.txt
[cli][debug] OS: Linux-4.9.0-8-amd64-x86_64-with-debian-9.8
[cli][debug] Python: 2.7.13
[cli][debug] Streamlink: 1.0.0+46.g42105d8
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.55.0)
[cli][info] Found matching plugin twitch for URL twitch.tv/zisteau
[plugin.twitch][debug] Getting live HLS streams for zisteau
[utils.l10n][debug] Language code: en_US
[cli][info] Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 900p60 (best)
[cli][info] Opening stream: 480p (hls)
[stream.hls][debug] Reloading playlist
[stream.hls][debug] First Sequence: 0; Last Sequence: 4
[stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 2; End Sequence: None
[stream.hls][debug] Adding segment 2 to queue
[cli][debug] Pre-buffering 8192 bytes
[stream.hls][debug] Adding segment 3 to queue
[stream.hls][debug] Adding segment 4 to queue
[stream.hls][debug] Download of segment 2 complete
[cli][info] Starting player: /usr/bin/vlc
[cli.output][debug] Opening subprocess: /usr/bin/vlc --input-title-format twitch.tv/zisteau -
[stream.hls][debug] Download of segment 3 complete
[stream.hls][debug] Download of segment 4 complete
[cli][debug] Writing stream to output
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 5 to queue
[stream.hls][debug] Adding segment 6 to queue
[stream.hls][debug] Adding segment 7 to queue
[stream.hls][debug] Download of segment 5 complete
[stream.hls][debug] Download of segment 6 complete
[stream.hls][debug] Download of segment 7 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 8 to queue
[stream.hls][debug] Adding segment 9 to queue
[stream.hls][debug] Download of segment 8 complete
[stream.hls][debug] Download of segment 9 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 10 to queue
[stream.hls][debug] Adding segment 11 to queue
[stream.hls][debug] Adding segment 12 to queue
[stream.hls][debug] Adding segment 13 to queue
[stream.hls][debug] Download of segment 10 complete
[stream.hls][debug] Download of segment 11 complete
[stream.hls][debug] Download of segment 12 complete
[stream.hls][debug] Download of segment 13 complete
[stream.hls][debug] Reloading playlist
[stream.hls][debug] Adding segment 14 to queue
[stream.hls][debug] Adding segment 15 to queue
[stream.hls][debug] Download of segment 14 complete
[stream.hls][debug] Download of segment 15 complete
```
### Additional comments, screenshots, etc.
I also had streamlink dump a --stream-url and ran wget on the the result:
Contents (longer hex strings [REDACTED]):
```
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:5
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-TWITCH-ELAPSED-SECS:28232.000
#EXT-X-TWITCH-TOTAL-SECS:28242.010
#EXT-X-DATERANGE:ID="stitched-ad-[REDACTED]-[REDACTED]",CLASS="twitch-stitched-ad",START-DATE="2019-03-20T05:17:07.821Z",DURATION=15.164,X-TV-TWITCH-AD-ROLL-TYPE="PREROLL",X-TV-TWITCH-AD-POD-LENGTH="2",X-TV-TWITCH-AD-POD-POSITION="0",X-TV-TWITCH-AD-URL="https://www.hersheys.com/icebreakers/en_us/home.html"
#EXT-X-DISCONTINUITY
#EXT-X-SCTE35-OUT:URL="https://www.hersheys.com/icebreakers/en_us/home.html"
#EXT-X-PROGRAM-DATE-TIME:2019-03-20T05:17:07.821Z
#EXTINF:2.002,[REDACTED]-01-02-2019-23.49.14
https://video-edge-7e9300.sea01.abs.hls.ttvnw.net/v1/segment/[REDACTED].ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-20T05:17:09.822999999Z
#EXTINF:2.002,[REDACTED]-01-02-2019-23.49.14
https://video-edge-7e9300.sea01.abs.hls.ttvnw.net/v1/segment/[REDACTED].ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-20T05:17:11.824999998Z
#EXTINF:2.002,[REDACTED]-01-02-2019-23.49.14
https://video-edge-7e9300.sea01.abs.hls.ttvnw.net/v1/segment/[REDACTED].ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-20T05:17:13.826999997Z
#EXTINF:2.002,[REDACTED]-01-02-2019-23.49.14
https://video-edge-7e9300.sea01.abs.hls.ttvnw.net/v1/segment/[REDACTED].ts
#EXT-X-PROGRAM-DATE-TIME:2019-03-20T05:17:15.828999996Z
#EXTINF:2.002,[REDACTED]-01-02-2019-23.49.14
https://video-edge-7e9300.sea01.abs.hls.ttvnw.net/v1/segment/[REDACTED].ts
```
Some of the redacted streams appear likely to be either session or user-login specific, so to err on the safeside I've [REDACTED] them.
Of also note, the EXTINF date-stamp appears to be referencing one that is wildly divergent from current timestamps.
| This is happening to me as well and beyond the annoyance of ads that don't respect your resolution or audio settings (always loads 1080p), it absolutely destroys streamlink audio and video settings when the ad ends.
I constantly have to close and re-open the stream, which plays another ad each time, just crossing my fingers that the audio won't be glitched out or the playback speed messed up. I suspect this might also be introducing even more stream delay too, based on comparing timestamps in chat (pulled through Chatty) to when the streamer reacts to the message on screen.
Also the player closes ("stream ended" message) very often when a streamer plays an ad. Both big and small channels.
Glitched audio takes different forms. Sometimes it "stutters": half second of audio and a half second of silence, constantly. Other times it plays at an increased speed, "chipmunk syndrome."
Are you by any chance using VLC?
These are glitches caused by your player while reading the MPEG-TS stream of Streamlink's concatenated HLS segments. Since ads don't necessarily share the same format as the live stream, this can cause issues in certain players like VLC. MPV has been working fine for me, so you might want to try that instead...
In the HLS stream, the start and end of an ad sequence is annotated with the `#EXT-X-DISCONTINUITY` tag. This is meant for telling the player to reset its decoding/rendering state. That does of course only work if a player is reading the HLS stream directly and implements it correctly. I'm not sure how this can be translated into the way Streamlink currently works. Would remuxing the MPEG-TS stream into a different format help, or do you have any other ideas here, @beardypig?
----
Unless somebody finds a way to request HLS streams which are not using their
"SureStream" stuff or unless someone finds a way to (re-)request the live segments during an ad sequence, I fear that we won't be able to fix this. Twitch has the upper hand here...
Regarding simply ignoring the ad segments, I don't think this is an option unless we're fine with potentially long gaps in the stream output. It would fix the player issues, though.
It is possible to ignore the **pre-roll** ads, but it would delay the start of the stream by a bit - until twitch starts sending the actual stream data.
I stream ads are more complicated, we can ignore those too - but it might cause the stream to stop if the ad break to too long.
I'll take a look at filtering our pre-roll ads.
Also happening for me
**Please stop posting "me too"**, this doesn't help and only bloats up this thread. We are looking for solutions here...
If you want to get notified on an update, you can subscribe to the thread (the button on the right) or watch the entire repository (the button on top).
I've whipped up a fragile kludge that hides the preroll ads for the moment, based on [back-to's work](https://github.com/streamlink/streamlink/issues/1676#issuecomment-430304591).
```
4d3
< import time
174,199d172
< reee = re.compile('stitched-ad.*,DURATION=([0-9.]+),')
< m = reee.search(res.text)
< n = 1
< t=0.0
< tee=0.0
< while m:
< if tee > 600.0:
< log.error("10 minutes of ads is too long. screw this.")
< raise StreamError("ad waiting timeout.")
< elif n > 10:
< log.error("10 ads in a row is too much. screw this.")
< raise StreamError("ad waiting tolerance exceeded.")
< else:
< t=float(m.group(1))
< log.info("waiting out ad playlist #%02d for %.2f seconds" % (n,t))
< time.sleep(t)
< tee+=t
< res = self.session.http.get(self.stream.url,
< exception=StreamError,
< retries=self.playlist_reload_retries,
< **self.reader.request_params)
< m = reee.search(res.text)
< n+=1
< if tee > 0.0:
< n-=1
< log.info("waited %.2f seconds on %2d ads." % (tee,n))
990c963
< __plugin__ = Twitch
---
> __plugin__ = Twitch
\ No newline at end of file
```
Works in the latest streamlink development version, at least. Make sure to not use any form of player passthrough, so the TwitchM3U8Parser can do it's thing.
Does that work with in-stream ads?
> Are you by any chance using VLC?
Not the OP, but I'm seeing the same behavior with MPV opening a video window despite using `audio_only`. Is this really two separate issues (video opening despite `audio_only`, and ads causing issues with stream playback)?
@spencerhakim when they injects the ads they always have video, I guess this violates the HLS standard - but that's a twitch.tv issue :)
They inject whatever video ads they like which disrupts the steam with their adverts - if you have chosen audio_only it's the same thing, but you get unexpected video. As a workaround you can set the video output on `mpv` to null (`--vo null`). Alternatively you can test out my fix, but it's slightly more difficult to apply.
Seeing this too, not just with Streamlink but also with Twitched app on Roku starting yesterday. So I guess they finally started injecting into the actual video stream. | 2019-03-23T23:00:50 |
streamlink/streamlink | 2,376 | streamlink__streamlink-2376 | [
"2371"
] | 499301dd2720d9022c051c6004c3efebf217fc12 | diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -30,7 +30,7 @@ class BBCiPlayer(Plugin):
)
""", re.VERBOSE)
mediator_re = re.compile(
- r'window\.mediatorDefer\s*=\s*page\([^,]*,\s*({.*?})\);', re.DOTALL)
+ r'window\.__IPLAYER_REDUX_STATE__\s*=\s*({.*?});', re.DOTALL)
tvip_re = re.compile(r'channel"\s*:\s*{\s*"id"\s*:\s*"(\w+?)"')
tvip_master_re = re.compile(r'event_master_brand=(\w+?)&')
account_locals_re = re.compile(r'window.bbcAccount.locals\s*=\s*({.*?});')
@@ -45,20 +45,19 @@ class BBCiPlayer(Plugin):
mediator_schema = validate.Schema(
{
- "appStoreState": {
- "versions": [{"id": validate.text}]
- }
+ "versions": [{"id": validate.text}]
},
- validate.get("appStoreState"), validate.get("versions"), validate.get(0),
+ validate.get("versions"), validate.get(0),
validate.get("id")
)
mediaselector_schema = validate.Schema(
validate.transform(parse_json),
{"media": [
- {"connection": [{
- validate.optional("href"): validate.url(),
- validate.optional("transferFormat"): validate.text
- }],
+ {"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"),
| BBC iPlayer plugin cannot find VPID
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
The BBC IPlayer plugin cannot find the VPID for valid urls.
### Reproduction steps / Explicit stream URLs to test
The following command:
```streamlink -l debug 'https://www.bbc.co.uk/iplayer/episode/m000388w/australia-earths-magical-kingdom-series-1-1-land' best```
produces this output:
```
[baz@blackbox iplayer]
[cli][debug] OS: Linux-5.0.2-arch1-1-ARCH-x86_64-with-arch
[cli][debug] Python: 3.7.2
[cli][debug] Streamlink: 1.0.0
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.55.0)
[cli][info] Found matching plugin bbciplayer for URL https://www.bbc.co.uk/iplayer/episode/m000388w/australia-earths-magical-kingdom-series-1-1-land
[cli][debug] Plugin specific arguments:
[cli][debug] --bbciplayer-username=******** (username)
[cli][debug] --bbciplayer-password=******** (password)
[plugin.bbciplayer][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
[plugin.bbciplayer][debug] Loading streams for episode: m000388w
[plugin.bbciplayer][debug] Looking for vpid on https://www.bbc.co.uk/iplayer/episode/m000388w/australia-earths-magical-kingdom-series-1-1-land
[plugin.bbciplayer][error] Could not find VPID for episode m000388w
error: No playable streams found on this URL: https://www.bbc.co.uk/iplayer/episode/m000388w/australia-earths-magical-kingdom-series-1-1-land
```
### Comments
This seems to be a another variation of #922.
| Confirmed. I will take a look... | 2019-03-25T09:19:20 |
|
streamlink/streamlink | 2,388 | streamlink__streamlink-2388 | [
"1905",
"1905"
] | df36df4cdeeabd7935f2d2cddad27614562dd98b | diff --git a/src/streamlink/plugins/playtv.py b/src/streamlink/plugins/playtv.py
--- a/src/streamlink/plugins/playtv.py
+++ b/src/streamlink/plugins/playtv.py
@@ -1,3 +1,5 @@
+import base64
+import json
import re
from streamlink.plugin import Plugin
@@ -5,11 +7,17 @@
from streamlink.stream import HDSStream, HLSStream
+def jwt_decode(token):
+ info, payload, sig = token.split(".")
+ data = base64.urlsafe_b64decode(payload + '=' * (-len(payload) % 4))
+ return json.loads(data)
+
+
class PlayTV(Plugin):
- FORMATS_URL = 'http://playtv.fr/player/initialize/{0}/'
- API_URL = 'http://playtv.fr/player/play/{0}/?format={1}&language={2}&bitrate={3}'
+ FORMATS_URL = 'https://playtv.fr/player/initialize/{0}/'
+ API_URL = 'https://playtv.fr/player/play/{0}/?format={1}&language={2}&bitrate={3}'
- _url_re = re.compile(r'http://(?:playtv\.fr/television|play\.tv/live-tv/\d+)/(?P<channel>[^/]+)/?')
+ _url_re = re.compile(r'https?://(?:playtv\.fr/television|(:?\w+\.)?play\.tv/live-tv/\d+)/(?P<channel>[^/]+)/?')
_formats_schema = validate.Schema({
'streams': validate.any(
@@ -27,9 +35,13 @@ class PlayTV(Plugin):
}
)
})
- _api_schema = validate.Schema({
- 'url': validate.url()
- })
+
+ _api_schema = validate.Schema(
+ validate.transform(lambda x: jwt_decode(x)),
+ {
+ 'url': validate.url()
+ }
+ )
@classmethod
def can_handle_url(cls, url):
@@ -57,7 +69,7 @@ def _get_streams(self):
continue
api_url = self.API_URL.format(channel, protocol, language, bitrate['value'])
res = self.session.http.get(api_url)
- video_url = self.session.http.json(res, schema=self._api_schema)['url']
+ video_url = self._api_schema.validate(res.text)['url']
bs = '{0}k'.format(bitrate['value'])
if protocol == 'hls':
| Playtv uk
playtv.fr working fine is there any possibility to run http://uk.play.tv/ looks like both sites france and uk owned by same company. As streamlink support tvplay.fr. hope u get support for uk playtv.
http://uk.play.tv/live-tv/363/pick-tv/
http://uk.play.tv/live-tv/752/itv4-1/
http://uk.play.tv/live-tv/1106/itv3-1/
http://uk.play.tv/live-tv/1105/itv-1/
Playtv uk
playtv.fr working fine is there any possibility to run http://uk.play.tv/ looks like both sites france and uk owned by same company. As streamlink support tvplay.fr. hope u get support for uk playtv.
http://uk.play.tv/live-tv/363/pick-tv/
http://uk.play.tv/live-tv/752/itv4-1/
http://uk.play.tv/live-tv/1106/itv3-1/
http://uk.play.tv/live-tv/1105/itv-1/
| This doesn't meet the plugin request template requirements and I believe you were notified of this before on another issue, so why are you not using the template and including the required information?
@gravyboat i m happy to do it mate. any donation link here. and please if u add link of template i m happy to do it through that process. regards.
All of these streams are just embedded, just use the source website.
This doesn't meet the plugin request template requirements and I believe you were notified of this before on another issue, so why are you not using the template and including the required information?
@gravyboat i m happy to do it mate. any donation link here. and please if u add link of template i m happy to do it through that process. regards.
All of these streams are just embedded, just use the source website. | 2019-03-31T16:33:58 |
|
streamlink/streamlink | 2,428 | streamlink__streamlink-2428 | [
"2406"
] | e67c68c6457246d6072d9e5cd2353ea1d21c3c11 | diff --git a/src/streamlink/plugins/goodgame.py b/src/streamlink/plugins/goodgame.py
--- a/src/streamlink/plugins/goodgame.py
+++ b/src/streamlink/plugins/goodgame.py
@@ -1,9 +1,12 @@
import re
+import logging
from streamlink.plugin import Plugin
from streamlink.stream import HLSStream
from streamlink.utils import parse_json
+log = logging.getLogger(__name__)
+
HLS_URL_FORMAT = "https://hls.goodgame.ru/hls/{0}{1}.m3u8"
QUALITIES = {
"1080p": "",
@@ -35,7 +38,7 @@ def _get_streams(self):
match = _ddos_re.search(res.text)
if match:
- self.logger.debug("Anti-DDOS bypass...")
+ log.debug("Anti-DDOS bypass...")
headers["Cookie"] = match.group(1)
res = self.session.http.get(self.url, headers=headers)
@@ -45,10 +48,9 @@ def _get_streams(self):
self.logger.error("Could not find channel info")
return
- self.logger.debug("Found channel info: channelkey={channelkey} pid={streamkey} online={status}",
- **channel_info)
+ log.debug("Found channel info: id={id} channelkey={channelkey} pid={streamkey} online={status}".format(**channel_info))
if not channel_info['status']:
- self.logger.debug("Channel appears to be offline")
+ log.debug("Channel appears to be offline")
streams = {}
for name, url_suffix in QUALITIES.items():
| Goodgame plugin not worked.
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
<!-- Explain the plugin issue as thoroughly as you can. -->
It looks like the plugin can no longer open streams.
### Reproduction steps / Explicit stream URLs to test
https://goodgame.ru/channel/Miker/#autoplay
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. ...
2. ...
3. ...
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
REPLACE THIS TEXT WITH THE LOG OUTPUT
```
c:\>streamlink --loglevel debug https://goodgame.ru/channel/Miker/#autoplay best
[cli][debug] OS: Windows 7
[cli][debug] Python: 3.6.6
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin goodgame for URL https://goodgame.ru/channel/Miker/#autoplay
Traceback (most recent call last):
File "runpy.py", line 193, in _run_module_as_main
File "runpy.py", line 85, in _run_code
File "C:\Program Files (x86)\Streamlink\bin\streamlink.exe\__main__.py", line 18, in <module>
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 1033, in main
handle_url()
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 577, in handle_url
streams = fetch_streams(plugin)
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 457, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugin\plugin.py", line 317, in streams
ostreams = self._get_streams()
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins\goodgame.py", line 49, in _get_str
eams
**channel_info)
File "logging\__init__.py", line 1295, in debug
TypeError: _log() got an unexpected keyword argument 'id'
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| > --loglevel debug
this returns invalid data, use `--loglevel info`, it should work
Yes, it really works without this command. I used it in most of my bat files. | 2019-04-15T22:41:05 |
|
streamlink/streamlink | 2,524 | streamlink__streamlink-2524 | [
"2491"
] | 209e43186b6bcf34c58f06019e8491f7ee2587d7 | diff --git a/src/streamlink/plugins/schoolism.py b/src/streamlink/plugins/schoolism.py
--- a/src/streamlink/plugins/schoolism.py
+++ b/src/streamlink/plugins/schoolism.py
@@ -17,8 +17,9 @@ class Schoolism(Plugin):
url_re = re.compile(r"https?://(?:www\.)?schoolism\.com/(viewAssignment|watchLesson).php")
login_url = "https://www.schoolism.com/index.php"
key_time_url = "https://www.schoolism.com/video-html/key-time.php"
- playlist_re = re.compile(r"var allVideos\s*=\s*(\[\{.*\}]);", re.DOTALL)
+ playlist_re = re.compile(r"var allVideos\s*=\s*(\[.*\]);", re.DOTALL)
js_to_json = partial(re.compile(r'(?!<")(\w+):(?!/)').sub, r'"\1":')
+ fix_brackets = partial(re.compile(r',\s*\}').sub, r'}')
playlist_schema = validate.Schema(
validate.transform(playlist_re.search),
validate.any(
@@ -26,7 +27,7 @@ class Schoolism(Plugin):
validate.all(
validate.get(1),
validate.transform(js_to_json),
- validate.transform(lambda x: x.replace(",}", "}")), # remove invalid ,
+ validate.transform(fix_brackets), # remove invalid ,
validate.transform(parse_json),
[{
"sources": validate.all([{
| diff --git a/tests/plugins/test_schoolism.py b/tests/plugins/test_schoolism.py
--- a/tests/plugins/test_schoolism.py
+++ b/tests/plugins/test_schoolism.py
@@ -17,3 +17,37 @@ def test_can_handle_url_negative(self):
]
for url in should_not_match:
self.assertFalse(Schoolism.can_handle_url(url))
+
+ def test_playlist_parse_subs(self):
+ with_subs = """var allVideos=[
+ {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part1.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Digital Painting - Lesson 2 - Part 1",playlistTitle:"Part 1",}], subtitles: [{
+ "default": true,
+ kind: "subtitles", srclang: "en", label: "English",
+ src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-1.vtt",
+ }],
+ },
+ {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part2.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Digital Painting - Lesson 2 - Part 2",playlistTitle:"Part 2",}], subtitles: [{
+ "default": true,
+ kind: "subtitles", srclang: "en", label: "English",
+ src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-2.vtt",
+ }]
+ }];
+ """
+
+ data = Schoolism.playlist_schema.validate(with_subs)
+
+ self.assertIsNotNone(data)
+ self.assertEqual(2, len(data))
+
+
+ def test_playlist_parse(self):
+ without_subs = """var allVideos=[
+ {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part1.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Gesture Drawing - Lesson 1 - Part 1",playlistTitle:"Part 1",}],},
+ {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part2.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Gesture Drawing - Lesson 1 - Part 2",playlistTitle:"Part 2",}]}
+ ];
+ """
+
+ data = Schoolism.playlist_schema.validate(without_subs)
+
+ self.assertIsNotNone(data)
+ self.assertEqual(2, len(data))
| Schoolism plugin not working with videos which have subtitles
<!--
Thanks for reporting a bug!
USE THE TEMPLATE. Otherwise your bug report may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed bug reports:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Bug Report
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a bug report and I have read the contribution guidelines.
### Description
<!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. -->
Schoolism plugin works fine with other courses except the two courses below. it'll get error when opening video with subtitles.
- Digital Painting with Craig Mullins
- Drawing Fundamentals with Thomas Fluharty
I'm using streamlink 1.1.1 in python 2.7. I think I have detected the reason why this bug happens but unfortunately I'm not familiar with python and streamlink itself so I may need some help:/
The javascript variable "allVideos" (which stores video URL link and other information) in HTML code is different when video contains subtitles.
- Videos without subtitles:
```
var allVideos=[
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part1.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC8xNC8xLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2Mjc3MH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTE3MH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=HE0~u~zThmbVd0QMbmSuHe3Pxxcg4-ZZXf6N8Fyczbae5Ov1BSfuJgWOeGPk1Y7zuVVE2vO5TlEWNR2aVIvQIAkVQNuaohOf9xuOdnn96SFq6J-LxTEPZthTvhbb3SJeDLWzdEj9-f93pfptKsTd8gABIAltfM1A-~Wjv~jiMVd19T0GJA9PUMNIeNkY7snBE7bMT85ARGrrHynWR71g31U1O-JvfAcnHLEcql-kc~5ZbV0HiJlvqicYhyJUsLzO3lR7sBihjmdq2FDH3-ckhzX3LJhJ9mpZYqZJ6r5DF1LApM870Ct-0KOe84EqdkCxUO4eaCd2ggJx8XLGbibaGQ__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Gesture Drawing - Lesson 1 - Part 1",playlistTitle:"Part 1",}],},
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part2.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC8xNC8xLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2Mjc3MH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTE3MH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=HE0~u~zThmbVd0QMbmSuHe3Pxxcg4-ZZXf6N8Fyczbae5Ov1BSfuJgWOeGPk1Y7zuVVE2vO5TlEWNR2aVIvQIAkVQNuaohOf9xuOdnn96SFq6J-LxTEPZthTvhbb3SJeDLWzdEj9-f93pfptKsTd8gABIAltfM1A-~Wjv~jiMVd19T0GJA9PUMNIeNkY7snBE7bMT85ARGrrHynWR71g31U1O-JvfAcnHLEcql-kc~5ZbV0HiJlvqicYhyJUsLzO3lR7sBihjmdq2FDH3-ckhzX3LJhJ9mpZYqZJ6r5DF1LApM870Ct-0KOe84EqdkCxUO4eaCd2ggJx8XLGbibaGQ__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Gesture Drawing - Lesson 1 - Part 2",playlistTitle:"Part 2",}]}
];
```
- Videos with subtitles:
```
var allVideos=[
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part1.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC80NC8yLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2MjkyMH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTMyMH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=WysPwDFhH0K75hoVq~XPrOjp-Lv5SbNTaM~x0NGpLUJTmzHw83Zz~HAqbpZPaeJiKRaEieC2y7uYJzzLlOdZvPWLyCoy76-5nav1bcihyD2DeJ7lIdCmsNlJarlODdxot3HaO0E7V2rv7WikNol5DmuL-dRsld8Y8JUWm4gJT5SSLVOSBWlCHI~TPrdDyjujMX1k2cLjLc7mHeOuBJOrJGWwwtb3DB48h8rjavZ6R5SXP3YU8uUDow8W74H27nKFd1mhd6ic0CBMVVEucL91ZkyGklNpoRTDqK2nHm6gZk7VWr6it7~XGtYpmHqOJf7BT0p1qaKHLNZnms~S3rKq0A__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Digital Painting - Lesson 2 - Part 1",playlistTitle:"Part 1",}], subtitles: [{
"default": true,
kind: "subtitles", srclang: "en", label: "English",
src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-1.vtt",
}],
},
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part2.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC80NC8yLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2MjkyMH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTMyMH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=WysPwDFhH0K75hoVq~XPrOjp-Lv5SbNTaM~x0NGpLUJTmzHw83Zz~HAqbpZPaeJiKRaEieC2y7uYJzzLlOdZvPWLyCoy76-5nav1bcihyD2DeJ7lIdCmsNlJarlODdxot3HaO0E7V2rv7WikNol5DmuL-dRsld8Y8JUWm4gJT5SSLVOSBWlCHI~TPrdDyjujMX1k2cLjLc7mHeOuBJOrJGWwwtb3DB48h8rjavZ6R5SXP3YU8uUDow8W74H27nKFd1mhd6ic0CBMVVEucL91ZkyGklNpoRTDqK2nHm6gZk7VWr6it7~XGtYpmHqOJf7BT0p1qaKHLNZnms~S3rKq0A__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Digital Painting - Lesson 2 - Part 2",playlistTitle:"Part 2",}], subtitles: [{
"default": true,
kind: "subtitles", srclang: "en", label: "English",
src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-2.vtt",
}]
];
```
### Expected / Actual behavior
<!-- What do you expect to happen, and what is actually happening? -->
The plugin works whether videos have subtitles or not. / It gets error with videos with subtitles.
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. Login to Schoolism and switch course to "Digital Painting with Craig Mullins"
2. Open lesson 1 part 1 with streamlink, for example. The course page URL is "https://www.schoolism.com/watchLesson.php?type=st&id=506
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a bug report!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
[cli][debug] OS: Linux-4.4.0-17134-Microsoft-x86_64-with-Ubuntu-18.04-bionic
[cli][debug] Python: 2.7.15rc1
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin schoolism for URL https://www.schoolism.com/watchLesson.php?type=st&id=506
[cli][debug] Plugin specific arguments:
[cli][debug] --schoolism-email=(email omitted)
[cli][debug] --schoolism-password=(password omitted)
[cli][debug] --schoolism-part=1 (part)
[plugin.schoolism][debug] Logged in to Schoolism as (email omitted)
error: Unable to parse JSON: Expecting property name enclosed in double quotes: line 5 column 9 (char 1337) (u'[{"sources":[{"type":"application ...)
```
### Additional comments, screenshots, etc.
I have a schoolism account valid till August so I can help testing.
Or if someone can give me some hint fixing this issue, I can make a merge request myself. Thank you!
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2019-07-04T12:01:09 |
|
streamlink/streamlink | 2,527 | streamlink__streamlink-2527 | [
"2501"
] | 209e43186b6bcf34c58f06019e8491f7ee2587d7 | diff --git a/src/streamlink/plugins/cdnbg.py b/src/streamlink/plugins/cdnbg.py
--- a/src/streamlink/plugins/cdnbg.py
+++ b/src/streamlink/plugins/cdnbg.py
@@ -23,6 +23,7 @@ class CDNBG(Plugin):
mmtvmusic\.com/live|
mu-vi\.tv/LiveStreams/pages/Live\.aspx|
videochanel\.bstv\.bg|
+ live\.bstv\.bg|
bloombergtv.bg/video
)/?
""", re.VERBOSE)
| diff --git a/tests/plugins/test_cdnbg.py b/tests/plugins/test_cdnbg.py
--- a/tests/plugins/test_cdnbg.py
+++ b/tests/plugins/test_cdnbg.py
@@ -23,6 +23,7 @@ def test_can_handle_url(self):
self.assertTrue(CDNBG.can_handle_url("https://mmtvmusic.com/live/"))
self.assertTrue(CDNBG.can_handle_url("http://mu-vi.tv/LiveStreams/pages/Live.aspx"))
self.assertTrue(CDNBG.can_handle_url("http://videochanel.bstv.bg/"))
+ self.assertTrue(CDNBG.can_handle_url("http://live.bstv.bg/"))
self.assertTrue(CDNBG.can_handle_url("https://www.bloombergtv.bg/video"))
# shouldn't match
| Plugin: cdnbg
Domain for BSTV has been changed to https://live.bstv.bg/.
| 2019-07-05T07:42:20 |
|
streamlink/streamlink | 2,528 | streamlink__streamlink-2528 | [
"2498"
] | 209e43186b6bcf34c58f06019e8491f7ee2587d7 | diff --git a/src/streamlink/plugins/ustvnow.py b/src/streamlink/plugins/ustvnow.py
--- a/src/streamlink/plugins/ustvnow.py
+++ b/src/streamlink/plugins/ustvnow.py
@@ -1,24 +1,33 @@
from __future__ import unicode_literals
+import argparse
+import base64
+import json
import logging
import re
-from collections import OrderedDict
+from uuid import uuid4
+from Crypto.Cipher import AES
+from Crypto.Hash import SHA256
+from Crypto.Util.Padding import pad, unpad
+
+from streamlink import PluginError
+from streamlink.compat import urljoin, urlparse
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
-from streamlink.plugin.api import useragents
-from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
log = logging.getLogger(__name__)
class USTVNow(Plugin):
- _url_re = re.compile(r"https?://(?:watch\.)?ustvnow\.com(?:/(?:watch|guide)/(?P<scode>\w+))?")
- _token_re = re.compile(r'''var\s+token\s*=\s*"(.*?)";''')
- _login_url = "https://watch.ustvnow.com/account/login"
- _signin_url = "https://watch.ustvnow.com/account/signin"
- _guide_url = "http://m.ustvnow.com/gtv/1/live/channelguidehtml"
- _stream_url = "http://m.ustvnow.com/stream/1/live/view"
+ _url_re = re.compile(r"https?://(?:www\.)?ustvnow\.com/live/(?P<scode>\w+)/-(?P<id>\d+)")
+ _main_js_re = re.compile(r"""src=['"](main\..*\.js)['"]""")
+ _enc_key_re = re.compile(r'(?P<key>AES_(?:Key|IV))\s*:\s*"(?P<value>[^"]+)"')
+
+ TENANT_CODE = "ustvnow"
+ _api_url = "https://teleupapi.revlet.net/service/api/v1/"
+ _token_url = _api_url + "get/token"
+ _signin_url = "https://www.ustvnow.com/signin"
arguments = PluginArguments(
PluginArgument(
@@ -38,65 +47,135 @@ class USTVNow(Plugin):
PluginArgument(
"station-code",
metavar="CODE",
- help="USTV Now station code"
+ help=argparse.SUPPRESS
),
)
+ def __init__(self, url):
+ super(USTVNow, self).__init__(url)
+ self._encryption_config = {}
+ self._token = None
+
@classmethod
def can_handle_url(cls, url):
return cls._url_re.match(url) is not None
- def login(self, username, password):
- r = self.session.http.get(self._signin_url)
- csrf = None
+ @classmethod
+ def encrypt_data(cls, data, key, iv):
+ rkey = "".join(reversed(key)).encode('utf8')
+ riv = "".join(reversed(iv)).encode('utf8')
+
+ fkey = SHA256.new(rkey).hexdigest()[:32].encode("utf8")
+
+ cipher = AES.new(fkey, AES.MODE_CBC, riv)
+ encrypted = cipher.encrypt(pad(data, 16, 'pkcs7'))
+ return base64.b64encode(encrypted)
- for input in itertags(r.text, "input"):
- if input.attributes['name'] == "csrf_ustvnow":
- csrf = input.attributes['value']
+ @classmethod
+ def decrypt_data(cls, data, key, iv):
+ rkey = "".join(reversed(key)).encode('utf8')
+ riv = "".join(reversed(iv)).encode('utf8')
- log.debug("CSRF: {0}", csrf)
+ fkey = SHA256.new(rkey).hexdigest()[:32].encode("utf8")
- r = self.session.http.post(self._login_url, data={'csrf_ustvnow': csrf,
- 'signin_email': username,
- 'signin_password': password,
- 'signin_remember': '1'})
- m = self._token_re.search(r.text)
- return m and m.group(1)
+ cipher = AES.new(fkey, AES.MODE_CBC, riv)
+ decrypted = cipher.decrypt(base64.b64decode(data))
+ if decrypted:
+ return unpad(decrypted, 16, 'pkcs7')
+ else:
+ return decrypted
+
+ def _get_encryption_config(self, url):
+ # find the path to the main.js
+ # load the main.js and extract the config
+ if not self._encryption_config:
+ res = self.session.http.get(url)
+ m = self._main_js_re.search(res.text)
+ main_js_path = m and m.group(1)
+ if main_js_path:
+ res = self.session.http.get(urljoin(url, main_js_path))
+ self._encryption_config = dict(self._enc_key_re.findall(res.text))
+
+ return self._encryption_config.get("AES_Key"), self._encryption_config.get("AES_IV")
+
+ @property
+ def box_id(self):
+ if not self.cache.get("box_id"):
+ self.cache.set("box_id", str(uuid4()))
+ return self.cache.get("box_id")
+
+ def get_token(self):
+ """
+ Get the token for USTVNow
+ :return: a valid token
+ """
+
+ if not self._token:
+ log.debug("Getting new session token")
+ res = self.session.http.get(self._token_url, params={
+ "tenant_code": self.TENANT_CODE,
+ "box_id": self.box_id,
+ "product": self.TENANT_CODE,
+ "device_id": 5,
+ "display_lang_code": "ENG",
+ "device_sub_type": "",
+ "timezone": "UTC"
+ })
+
+ data = res.json()
+ if data['status']:
+ self._token = data['response']['sessionId']
+ log.debug("New token: {}".format(self._token))
+ else:
+ log.error("Token acquisition failed: {details} ({detail})".format(**data['error']))
+ raise PluginError("could not obtain token")
+
+ return self._token
+
+ def api_request(self, path, data, metadata=None):
+ key, iv = self._get_encryption_config(self._signin_url)
+ post_data = {
+ "data": self.encrypt_data(json.dumps(data).encode('utf8'), key, iv).decode("utf8"),
+ "metadata": self.encrypt_data(json.dumps(metadata).encode('utf8'), key, iv).decode("utf8")
+ }
+ headers = {"box-id": self.box_id,
+ "session-id": self.get_token(),
+ "tenant-code": self.TENANT_CODE,
+ "content-type": "application/json"}
+ res = self.session.http.post(self._api_url + path, data=json.dumps(post_data), headers=headers).json()
+ data = dict((k, v and json.loads(self.decrypt_data(v, key, iv)))for k, v in res.items())
+ return data
+
+ def login(self, username, password):
+ log.debug("Trying to login...")
+ resp = self.api_request("send",
+ {
+ "login_id": username,
+ "login_key": password,
+ "login_mode": "1",
+ "manufacturer": "123"
+ },
+ {"request": "signin"})
+
+ return resp['data']['status']
def _get_streams(self):
"""
- Finds the streams from tvcatchup.com.
+ Finds the streams from ustvnow.com.
"""
- token = self.login(self.get_option("username"), self.get_option("password"))
- m = self._url_re.match(self.url)
- scode = m and m.group("scode") or self.get_option("station_code")
-
- res = self.session.http.get(self._guide_url, params=dict(token=token))
-
- channels = OrderedDict()
- for t in itertags(res.text, "a"):
- if t.attributes.get('cs'):
- channels[t.attributes.get('cs').lower()] = t.attributes.get('title').replace("Watch ", "").strip()
-
- if not scode:
- log.error("Station code not provided, use --ustvnow-station-code.")
- log.info("Available stations are: \n{0} ".format('\n'.join(' {0} ({1})'.format(c, n) for c, n in channels.items())))
- return
-
- if scode in channels:
- log.debug("Finding streams for: {0}", channels.get(scode))
-
- r = self.session.http.get(self._stream_url, params={"scode": scode,
- "token": token,
- "br_n": "Firefox",
- "br_v": "52",
- "br_d": "desktop"},
- headers={"User-Agent": useragents.FIREFOX})
-
- data = self.session.http.json(r)
- return HLSStream.parse_variant_playlist(self.session, data["stream"])
+ if self.login(self.get_option("username"), self.get_option("password")):
+ path = urlparse(self.url).path.strip("/")
+ resp = self.api_request("send", {"path": path}, {"request": "page/stream"})
+ if resp['data']['status']:
+ for stream in resp['data']['response']['streams']:
+ if stream['keys']['licenseKey']:
+ log.warning("Stream possibly protected by DRM")
+ for q, s in HLSStream.parse_variant_playlist(self.session, stream['url']).items():
+ yield (q, s)
+ else:
+ log.error("Could not find any streams: {code}: {message}".format(**resp['data']['error']))
else:
- log.error("Invalid station-code: {0}", scode)
+ log.error("Failed to login, check username and password")
__plugin__ = USTVNow
| diff --git a/tests/plugins/test_ustvnow.py b/tests/plugins/test_ustvnow.py
--- a/tests/plugins/test_ustvnow.py
+++ b/tests/plugins/test_ustvnow.py
@@ -5,12 +5,27 @@
class TestPluginUSTVNow(unittest.TestCase):
def test_can_handle_url(self):
- self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com"))
- self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/"))
- self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com/watch"))
- self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch"))
- self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch/syfy"))
- self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/guide/foxnews"))
+ self.assertTrue(USTVNow.can_handle_url("http://www.ustvnow.com/live/foo/-65"))
def test_can_not_handle_url(self):
self.assertFalse(USTVNow.can_handle_url("http://www.tvplayer.com"))
+
+ def test_encrypt_data(self):
+
+ key = "80035ad42d7d-bb08-7a14-f726-78403b29"
+ iv = "3157b5680927cc4a"
+
+ self.assertEqual(
+ b"uawIc5n+TnmsmR+aP2iEDKG/eMKji6EKzjI4mE+zMhlyCbHm7K4hz7IDJDWwM3aE+Ro4ydSsgJf4ZInnoW6gqvXvG0qB/J2WJeypTSt4W124zkJpvfoJJmGAvBg2t0HT",
+ USTVNow.encrypt_data(b'{"login_id":"[email protected]","login_key":"testtest1234","login_mode":"1","manufacturer":"123"}', key, iv)
+ )
+
+ def test_decrypt_data(self):
+
+ key = "80035ad42d7d-bb08-7a14-f726-78403b29"
+ iv = "3157b5680927cc4a"
+
+ self.assertEqual(
+ b'{"status":false,"error":{"code":-2,"type":"","message":"Invalid credentials.","details":{}}}',
+ USTVNow.decrypt_data(b"KcRLETVAmHlosM0OyUd5hdTQ6WhBRTe/YRAHiLJWrzf94OLkSueXTtQ9QZ1fjOLCbpX2qteEPUWVnzvvSgVDkQmRUttN/royoxW2aL0gYQSoH1NWoDV8sIgvS5vDiQ85", key, iv)
+ )
| USTVnow plugin stopped working
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
USTVnow plugin stopped working; it reports "invalid station code" / empty list of Available Stations
### Log output
-- start without station code --
[cli][debug] OS: Linux-4.15.0-51-generic-x86_64-with-Ubuntu-18.04-bionic
[cli][debug] Python: 3.6.8
[cli][debug] Streamlink: 1.1.1+28.gd655cbd
[cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin ustvnow for URL http://watch.ustvnow.com/watch/
[cli][debug] Plugin specific arguments:
[cli][debug] --ustvnow-username=******** (username)
[cli][debug] --ustvnow-password=******** (password)
[plugin.ustvnow][debug] CSRF: None
[plugin.ustvnow][error] Station code not provided, use --ustvnow-station-code.
[plugin.ustvnow][info] Available stations are:
error: No playable streams found on this URL: http://watch.ustvnow.com/watch/
-- stop --
-- start with station code --
[cli][debug] OS: Linux-4.15.0-51-generic-x86_64-with-Ubuntu-18.04-bionic
[cli][debug] Python: 3.6.8
[cli][debug] Streamlink: 1.1.1+28.gd655cbd
[cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin ustvnow for URL http://watch.ustvnow.com/watch/whtm
[cli][debug] Plugin specific arguments:
[cli][debug] --ustvnow-username=******** (username)
[cli][debug] --ustvnow-password=******** (password)
[plugin.ustvnow][debug] CSRF: None
[plugin.ustvnow][error] Invalid station-code: whtm
error: No playable streams found on this URL: http://watch.ustvnow.com/watch/whtm
-- stop --
## Additional Information
They seem to have changed the urls, on watch.* i'm getting a not-available-in-your-region-error, but i.e. https://www.ustvnow.com/live/cwwpix/-53 seems to work
| They completely changed the website layout - look much better now. But will require a significant rewrite to make it work again. | 2019-07-05T14:50:33 |
streamlink/streamlink | 2,532 | streamlink__streamlink-2532 | [
"2531"
] | 1aaab4bf0b1d21f3e4b5f452dfd8653efc537c7a | diff --git a/src/streamlink/plugins/ustreamtv.py b/src/streamlink/plugins/ustreamtv.py
--- a/src/streamlink/plugins/ustreamtv.py
+++ b/src/streamlink/plugins/ustreamtv.py
@@ -11,7 +11,7 @@
from threading import Thread, Event
from time import sleep
-from streamlink.compat import range, urljoin, urlunparse
+from streamlink.compat import range, urljoin, urlunparse, urlparse, unquote_plus
from streamlink.exceptions import PluginError, StreamError
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import useragents, validate
@@ -57,6 +57,7 @@ def __init__(self, media_id, application, **options):
self._app_version = options.pop("app_version", self.APP_VERSION)
self._cluster = options.pop("cluster", "live")
self._password = options.pop("password")
+ self._proxy_url = options.pop("proxy")
self._ws = None
@property
@@ -79,11 +80,32 @@ def cluster(self, cluster):
self._cluster = cluster
self.reconnect()
+ @staticmethod
+ def parse_proxy_url(purl):
+ proxy_options = {}
+ if purl:
+ p = urlparse(purl)
+ proxy_options['proxy_type'] = p.scheme
+ proxy_options['http_proxy_host'] = p.hostname
+ if p.port:
+ proxy_options['http_proxy_port'] = p.port
+ if p.username:
+ proxy_options['http_proxy_auth'] = (unquote_plus(p.username), unquote_plus(p.password or ""))
+ return proxy_options
+
def connect(self):
- log.debug("Connecting to {0}".format(self.host))
+ proxy_options = self.parse_proxy_url(self._proxy_url)
+ if proxy_options.get('http_proxy_host'):
+ log.debug("Connecting to {0} via proxy ({1}://{2}:{3})".format(self.host,
+ proxy_options.get('proxy_type') or "http",
+ proxy_options.get('http_proxy_host'),
+ proxy_options.get('http_proxy_port') or 80))
+ else:
+ log.debug("Connecting to {0}".format(self.host))
self._ws = websocket.create_connection(self.host,
header=["User-Agent: {0}".format(useragents.CHROME)],
- origin="https://www.ustream.tv")
+ origin="https://www.ustream.tv",
+ **proxy_options)
args = dict(type="viewer",
appId=self._app_id,
@@ -304,6 +326,7 @@ def stopper(self, f):
def _stopper(*args, **kwargs):
self.stop()
return f(*args, **kwargs)
+
return _stopper
def handle_module_info(self, args):
@@ -411,8 +434,8 @@ def handle_module_info(self, args):
raise PluginError("Stream format is not supported: {0}".format(
", ".join(data["streamFormats"].keys())))
elif "stream" in arg and arg["stream"]["contentAvailable"] is False:
- log.error("This stream is currently offline")
- raise ModuleInfoNoStreams
+ log.error("This stream is currently offline")
+ raise ModuleInfoNoStreams
return res
@@ -432,7 +455,11 @@ def handle_reject(self, api, args):
def _get_streams(self):
media_id, application = self._get_media_app()
if media_id:
- api = UHSClient(media_id, application, referrer=self.url, cluster="live", password=self.get_option("password"))
+ api = UHSClient(media_id, application,
+ referrer=self.url,
+ cluster="live",
+ password=self.get_option("password"),
+ proxy=self.session.get_option("http-proxy"))
log.debug("Connecting to UStream API: media_id={0}, application={1}, referrer={2}, cluster={3}",
media_id, application, self.url, "live")
api.connect()
diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py
--- a/src/streamlink_cli/argparser.py
+++ b/src/streamlink_cli/argparser.py
@@ -1070,8 +1070,8 @@ def build_parser():
"--http-proxy",
metavar="HTTP_PROXY",
help="""
- A HTTP proxy to use for all HTTP requests, by default this proxy
- will be used for all HTTPS requests too.
+ A HTTP proxy to use for all HTTP requests, including WebSocket connections.
+ By default this proxy will be used for all HTTPS requests too.
Example: "http://hostname:port/"
"""
| plugins.ustreamtv: Proxy and Socks do not work
Hi,
I noticed Proxy and Socks no longer work on Streamlink.
The channel I want to watch blocks all countries except the United States and I use US IP to see it.
```
streamlink --http-proxy xxx.xxx.xxx.xxx:xxxx https://www.ustream.tv/embed/23259921 best
```
And it doesn't work
```
[cli][info] Found matching plugin ustreamtv for URL https://www.ustream.tv/embed/23259921
[plugin.ustreamtv][error] This content is not available in your area
```
Meanwhile, I use the Proxy SwitchyOmega extension and the same IP, I can watch it on the browser.
Please help me, Thanks.
| Try setting `--https-proxy` too, to the same thing. For legacy reasons they are different. It might be worth defaulting the `https-proxy` to the same as `http-proxy`, but for now you gotta do it yourself.
I tried it all but it didn't work.
You're right, WebSocket connections are not proxied - we'll have to update that. | 2019-07-08T11:52:58 |
|
streamlink/streamlink | 2,543 | streamlink__streamlink-2543 | [
"2539"
] | e46a84c7190e6ce73cd901ee86b6c40dd517375d | diff --git a/src/streamlink/plugins/youtube.py b/src/streamlink/plugins/youtube.py
--- a/src/streamlink/plugins/youtube.py
+++ b/src/streamlink/plugins/youtube.py
@@ -82,6 +82,9 @@ def parse_fmt_list(formatsmap):
{
validate.optional("streamingData"): {
validate.optional("hlsManifestUrl"): validate.text,
+ },
+ validate.optional("videoDetails"): {
+ validate.optional("isLive"): validate.transform(bool),
}
}
),
@@ -339,7 +342,8 @@ def _get_streams(self):
log.error("Could not get video info")
return
- if info.get("livestream") == '1' or info.get("live_playback") == '1':
+ if info.get("livestream") == '1' or info.get("live_playback") == '1' \
+ or info.get("player_response", {}).get("videoDetails", {}).get("isLive") == True:
log.debug("This video is live.")
is_live = True
| Unable to get the YT Live best quality hls stream url in sometimes
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
YouTube seems to have changed their code on July 11, especially in terms of live streaming.
The first problem is the inability to parse the video id of the user/channel 's live broadcast room address.
```
> streamlink -l debug -o test.ts https://www.youtube.com/rocketbeanstv/live best
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.7.3
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/rocketbeanstv/live
error: Could not find a video on this page
```
Try to fix in #2538 .
Another issue is that if a live stream video have 1080p and 1080p60 at the same time, it can't get the hls url for 1080p60. (Maybe it doesn't exist at all?)
It will try to get the http substream and program exit directly, only one frame/segment of data can be obtained (about 500k).
I found that youtube-dl has the same problem. https://github.com/ytdl-org/youtube-dl/issues/21734
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. Looking for a live broadcast room with 1080p60 quality options
2. Try to download the video at the best quality
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
Try to download best quality (1080p60) with format code 299
```
$ streamlink -o test.ts https://www.youtube.com/rocketbeanstv/live best -l debug
[cli][debug] OS: Linux-5.1.15-arch1-1-ARCH-x86_64-with-arch
[cli][debug] Python: 3.7.3
[cli][debug] Streamlink: 1.1.1+39.g04f0b0d
[cli][debug] Requests(2.22.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/rocketbeanstv/live
[plugin.youtube][debug] Video ID from currentVideoEndpoint
[plugin.youtube][debug] Using video ID: E-MsayZ_Epw
[plugin.youtube][debug] get_video_info - 1: Found data
[plugin.youtube][debug] MuxedStream: v 137 a 140 = 1080p
[plugin.youtube][debug] MuxedStream: v 299 a 140 = 1080p60
[utils.l10n][debug] Language code: zh_CN
[cli][info] Available streams: audio_mp4, 144p (worst), 240p, 360p, 480p, 720p, 1080p, 1080p60 (best)
[cli][info] Opening stream: 1080p60 (muxed-stream)
[stream.ffmpegmux][debug] Opening http substream
[stream.ffmpegmux][debug] Opening http substream
[stream.mp4mux-ffmpeg][debug] ffmpeg command: ffmpeg -nostats -y -i /tmp/ffmpeg-74555-150 -i /tmp/ffmpeg-74555-765 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-74555-150
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-74555-765
[cli][debug] Pre-buffering 8192 bytes
[stream.ffmpegmux][debug] Pipe copy complete: /tmp/ffmpeg-74555-765
[cli][debug] Checking file output
[cli][debug] Writing stream to output
[stream.ffmpegmux][debug] Pipe copy complete: /tmp/ffmpeg-74555-150
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.ffmpegmux][debug] Closed all the substreams
[cli][info] Stream ended
[cli][info] Closing currently open stream...
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.ffmpegmux][debug] Closed all the substreams
[stream.ffmpegmux][debug] Closing ffmpeg thread
[stream.ffmpegmux][debug] Closed all the substreams
```
If you choose 1080p quality, it can download as normal.
```
$ streamlink -o test.ts https://www.youtube.com/rocketbeanstv/live 1080p -l debug
[cli][debug] OS: Linux-5.1.15-arch1-1-ARCH-x86_64-with-arch
[cli][debug] Python: 3.7.3
[cli][debug] Streamlink: 1.1.1+39.g04f0b0d
[cli][debug] Requests(2.22.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/rocketbeanstv/live
[plugin.youtube][debug] Video ID from currentVideoEndpoint
[plugin.youtube][debug] Using video ID: E-MsayZ_Epw
[plugin.youtube][debug] get_video_info - 1: Found data
[plugin.youtube][debug] MuxedStream: v 137 a 140 = 1080p
[plugin.youtube][debug] MuxedStream: v 299 a 140 = 1080p60
[utils.l10n][debug] Language code: zh_CN
[cli][info] Available streams: audio_mp4, 144p (worst), 240p, 360p, 480p, 720p, 1080p, 1080p60 (best)
[cli][info] Opening stream: 1080p (hls)
[stream.hls][debug] Reloading playlist
[stream.hls][debug] First Sequence: 72157; Last Sequence: 75755
[stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 75753; End Sequence: None
[stream.hls][debug] Adding segment 75753 to queue
[cli][debug] Pre-buffering 8192 bytes
[stream.hls][debug] Adding segment 75754 to queue
[stream.hls][debug] Adding segment 75755 to queue
```
After the live broadcast is over, it can be download normally.
| see https://github.com/streamlink/streamlink/pull/1556
Streamlink should not use `MuxedStream` for livestreams
the `is_live` check in Streamlink doesn't work anymore
So actually that is same problem with #1520...
YouTube changed the livestream flags, so is_live check part should be rewrited.
I found a key "playabilityStatus" is that useful ?
![9d75efe8dc5e4b3](https://user-images.githubusercontent.com/25289725/61075103-de43d280-a44b-11e9-87ab-b3f7b0c50e60.png)
![-33d54f3d836c3568](https://user-images.githubusercontent.com/25289725/61075113-e4d24a00-a44b-11e9-9186-c412895946a1.png)
| 2019-07-12T08:40:07 |
|
streamlink/streamlink | 2,545 | streamlink__streamlink-2545 | [
"2291"
] | e46a84c7190e6ce73cd901ee86b6c40dd517375d | diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py
--- a/src/streamlink/stream/dash.py
+++ b/src/streamlink/stream/dash.py
@@ -1,3 +1,4 @@
+import copy
import itertools
import logging
import datetime
@@ -30,7 +31,8 @@ def fetch(self, segment, retries=None):
return
try:
- headers = {}
+ request_args = copy.deepcopy(self.reader.stream.args)
+ headers = request_args.pop("headers", {})
now = datetime.datetime.now(tz=utc)
if segment.available_at > now:
time_to_wait = (segment.available_at - now).total_seconds()
@@ -49,7 +51,8 @@ def fetch(self, segment, retries=None):
return self.session.http.get(segment.url,
timeout=self.timeout,
exception=StreamError,
- headers=headers)
+ headers=headers,
+ **request_args)
except StreamError as err:
log.error("Failed to open segment {0}: {1}", segment.url, err)
return self.fetch(segment, retries - 1)
@@ -109,7 +112,7 @@ def reload(self):
self.reader.buffer.wait_free()
log.debug("Reloading manifest ({0}:{1})".format(self.reader.representation_id, self.reader.mime_type))
- res = self.session.http.get(self.mpd.url, exception=StreamError)
+ res = self.session.http.get(self.mpd.url, exception=StreamError, **self.stream.args)
new_mpd = MPD(self.session.http.xml(res, ignore_ns=True),
base_url=self.mpd.base_url,
| DASHStream: can't use headers for DASHStreamReader/Worker/Writer
## Bug Report
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a bug report and I have read the contribution guidelines.
### Description
could be related to https://github.com/streamlink/streamlink/issues/2270
but there is no `403 Client Error` so lets use a different issue here
**headers** (User-Agent) used with **DASHStream.parse_manifest** will only work here
https://github.com/streamlink/streamlink/blob/5db462eb993d659e27d9de4babd14ab33eb4ad8d/src/streamlink/stream/dash.py#L174
https://github.com/streamlink/streamlink/blob/5db462eb993d659e27d9de4babd14ab33eb4ad8d/src/streamlink/stream/dash.py#L226
not in DASHStreamReader/Worker/Writer
### Expected / Actual behavior
allow headers in **reload** ... , same as hls
HLS with request_params
https://github.com/streamlink/streamlink/blob/62409cdb1537626dbeca35606ed5d913090e6878/src/streamlink/stream/hls.py#L282-L288
https://github.com/streamlink/streamlink/blob/62409cdb1537626dbeca35606ed5d913090e6878/src/streamlink/stream/hls.py#L193
DASH does not have request_params
https://github.com/streamlink/streamlink/blob/62409cdb1537626dbeca35606ed5d913090e6878/src/streamlink/stream/dash.py#L128-L136
https://github.com/streamlink/streamlink/blob/62409cdb1537626dbeca35606ed5d913090e6878/src/streamlink/stream/dash.py#L111
### Reproduction steps / Explicit stream URLs to test
1. `streamlink https://www.tf1.fr/lci/direct 576p_dash`
https://github.com/streamlink/streamlink/blob/62409cdb1537626dbeca35606ed5d913090e6878/src/streamlink/plugins/tf1.py#L49
### Log output
```
$ streamlink https://www.tf1.fr/lci/direct 576p_dash
[cli][debug] OS: Linux
[cli][debug] Python: 3.6.7
[cli][debug] Streamlink: 1.0.0+3.g4100688.dirty
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0)
[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct
[plugin.tf1][debug] Found channel lci
[plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
[utils.l10n][debug] Language code: en_US
[stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a)
[plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&st=
[utils.l10n][debug] Language code: en_US
[cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best)
[cli][info] Opening stream: 576p_dash (dash)
[stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264))
[stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4)
[stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC))
[stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4)
[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532
[cli][debug] Pre-buffering 8192 bytes
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete
Exception in thread Thread-DASHStreamWorker:
Traceback (most recent call last):
File "src/streamlink/plugin/api/http_session.py", line 166, in request
res.raise_for_status()
File "env/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "src/streamlink/stream/segmented.py", line 59, in run
for segment in self.iter_segments():
File "src/streamlink/stream/dash.py", line 97, in iter_segments
if not self.reload():
File "src/streamlink/stream/dash.py", line 111, in reload
res = self.session.http.get(self.mpd.url, exception=StreamError)
File "env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get
return self.request('GET', url, **kwargs)
File "src/streamlink/plugin/api/http_session.py", line 175, in request
raise err
streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)
Exception in thread Thread-DASHStreamWorker:
Traceback (most recent call last):
File "src/streamlink/plugin/api/http_session.py", line 166, in request
res.raise_for_status()
File "env/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "src/streamlink/stream/segmented.py", line 59, in run
for segment in self.iter_segments():
File "src/streamlink/stream/dash.py", line 97, in iter_segments
if not self.reload():
File "src/streamlink/stream/dash.py", line 111, in reload
res = self.session.http.get(self.mpd.url, exception=StreamError)
File "env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get
return self.request('GET', url, **kwargs)
File "src/streamlink/plugin/api/http_session.py", line 175, in request
raise err
streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete
```
### Additional comments, screenshots, etc.
used with a global User-Agent fixed it
| You need to update the session headers, either in the tf1 plugin or dash.py:
`self.session.http.headers.update (...)`
otherwise the headers only work in the corresponding `http.get ()` call. | 2019-07-12T14:43:29 |
|
streamlink/streamlink | 2,556 | streamlink__streamlink-2556 | [
"2533"
] | 0f01f35a6356595f42cf8ab0f1f4a282b41cbbe6 | diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -59,7 +59,7 @@
(?P<video_id>\d+)
)?
(?:
- /
+ /(?:clip/)?
(?P<clip_name>[\w]+)
)?
""", re.VERBOSE)
| twitch clips still try to use the v2 api
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
<!-- Explain the plugin issue as thoroughly as you can. -->
Downloading twitch clips does not work. It looks like this is something that was missed when you moved away from the v2 APIs - https://github.com/streamlink/streamlink/issues/1982 etc. - or just something I don't understand.
### Reproduction steps / Explicit stream URLs to test
$ streamlink -o test-clip https://www.twitch.tv/day9tv/clip/AmazonianEnchantingKangarooAsianGlow
[cli][info] Found matching plugin twitch for URL https://www.twitch.tv/day9tv/clip/AmazonianEnchantingKangarooAsianGlow
error: Unable to open URL: https://clips.twitch.tv/api/v2/clips/clip/status (404 Client Error: Not Found for url: https://clips.twitch.tv/api/v2/clips/clip/status?as3=t)
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
[cli][debug] OS: Linux-5.0.16-100.fc28.x86_64-x86_64-with-fedora-28-Twenty_Eight
[cli][debug] Python: 3.6.8
[cli][debug] Streamlink: 1.1.1+34.g0a38762
[cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin twitch for URL https://www.twitch.tv/day9tv/clip/AmazonianEnchantingKangarooAsianGlow
error: Unable to open URL: https://clips.twitch.tv/api/v2/clips/clip/status (404 Client Error: Not Found for url: https://clips.twitch.tv/api/v2/clips/clip/status?as3=t)
```
| I don't think the API for clips was ever public (I might be wrong) and we were using an internal API. It looks like there is a new GraphQL API that powers clips - so we'll have to update the twitch plugin to support that.
Requesting the clip's mp4 file URLs has always been a private API call. This doesn't change with the switch to the GQL API. The only public APIs are the REST kraken/v5 and helix APIs, which (obviously) don't support that.
I'm just wondering, is it really necessary for Streamlink to support Twitch clips? Clips are just simple mp4 containers which can be downloaded via a simple HTTP request (in contrast to the HLS streams of their live streams and VODs). In terms of clips, this makes Streamlink and its Twitch plugin a simple URL resolver instead of being a stream URL resolver + HLS client. I might be wrong though, since there are a lot of other plugins which basically do the same, and it's probably also a justified use case.
I don’t have any problem with streamlink supporting clips, as long as someone wants to work on it :)
@bastimeyer I don't really care about Twitch clips and I'm not willing to ask people to spend time on it. Seems like it really just supports people downloading clips (presumably) to make clip compilations.
I originally stumbled across this when I tried to download a clip in order to manipulate it to elaborate on a joke, in a constructive way. But I admit I never thought about whether it enables people to do something undesirable.
As a simple streamlink user, I see it as a tool to reduce friction in dealing with online video - and downloading twitch clips effortlessly would be an extension of that.
@oliverhenshaw Sorry if my comment came off in an accusatory manner. It's more trying to determine if there is a use case for the work that makes it worth investing time in to and that was the only thing I could think of for use cases.
> Downloading twitch clips does not work.
`_url_re` is invalid for your URL in the **Twitch plugin**,
it does not match the clip name correctly.
> It looks like this is something that was missed when you moved away from the v2 APIs
No, it still works correctly.
Remove the `/clip/` in the url
` https://www.twitch.tv/day9tv/AmazonianEnchantingKangarooAsianGlow`
| 2019-07-20T10:12:22 |
|
streamlink/streamlink | 2,565 | streamlink__streamlink-2565 | [
"2557"
] | 4e86cfb360ca330d88b560c5de198d7ff98fa954 | diff --git a/src/streamlink/plugins/youtube.py b/src/streamlink/plugins/youtube.py
--- a/src/streamlink/plugins/youtube.py
+++ b/src/streamlink/plugins/youtube.py
@@ -85,8 +85,13 @@ def parse_fmt_list(formatsmap):
},
validate.optional("videoDetails"): {
validate.optional("isLive"): validate.transform(bool),
- }
- }
+ },
+ validate.optional("playabilityStatus"): {
+ validate.optional("status"): validate.text,
+ validate.optional("reason"): validate.all(validate.text,
+ validate.transform(maybe_decode)),
+ },
+ },
),
validate.optional("live_playback"): validate.transform(bool),
validate.optional("reason"): validate.all(validate.text, validate.transform(maybe_decode)),
@@ -104,20 +109,25 @@ def parse_fmt_list(formatsmap):
_url_re = re.compile(r"""(?x)https?://(?:\w+\.)?youtube\.com
(?:
(?:
- /(?:watch.+v=|embed/(?!live_stream)|v/)
- (?P<video_id>[0-9A-z_-]{11})
+ /(?:
+ watch.+v=
+ |
+ embed/(?!live_stream)
+ |
+ v/
+ )(?P<video_id>[0-9A-z_-]{11})
)
|
(?:
/(?:
- (?:user|channel)/
+ (?:user|c(?:hannel)?)/
|
embed/live_stream\?channel=
- )(?P<user>[^/?&]+)
+ )[^/?&]+
)
|
(?:
- /(?:c/)?(?P<liveChannel>[^/?]+)/live/?$
+ /(?:c/)?[^/?]+/live/?$
)
)
""")
@@ -316,9 +326,12 @@ def _get_stream_info(self, video_id):
res = self.session.http.get(self._video_info_url, params=params)
info_parsed = parse_query(res.content if is_py2 else res.text, name="config", schema=_config_schema)
- if info_parsed.get("status") == "fail":
+ if (info_parsed.get("player_response", {}).get("playabilityStatus", {}).get("status") != "OK"
+ or info_parsed.get("status") == "fail"):
+ reason = (info_parsed.get("player_response", {}).get("playabilityStatus", {}).get("reason")
+ or info_parsed.get("reason"))
log.debug("get_video_info - {0}: {1}".format(
- count, info_parsed.get("reason"))
+ count, reason)
)
continue
self.author = info_parsed.get("author")
| diff --git a/tests/plugins/test_youtube.py b/tests/plugins/test_youtube.py
--- a/tests/plugins/test_youtube.py
+++ b/tests/plugins/test_youtube.py
@@ -6,53 +6,39 @@
class TestPluginYouTube(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
+ "https://www.youtube.com/EXAMPLE/live",
+ "https://www.youtube.com/c/EXAMPLE",
+ "https://www.youtube.com/c/EXAMPLE/",
"https://www.youtube.com/c/EXAMPLE/live",
"https://www.youtube.com/c/EXAMPLE/live/",
"https://www.youtube.com/channel/EXAMPLE",
- "https://www.youtube.com/v/aqz-KE-bpKQ",
+ "https://www.youtube.com/channel/EXAMPLE/",
"https://www.youtube.com/embed/aqz-KE-bpKQ",
+ "https://www.youtube.com/embed/live_stream?channel=UCNye-wNBqNL5ZzHSJj3l8Bg",
+ "https://www.youtube.com/user/EXAMPLE",
"https://www.youtube.com/user/EXAMPLE/",
+ "https://www.youtube.com/user/EXAMPLE/live",
+ "https://www.youtube.com/v/aqz-KE-bpKQ",
"https://www.youtube.com/watch?v=aqz-KE-bpKQ",
- "https://www.youtube.com/embed/live_stream?channel=UCNye-wNBqNL5ZzHSJj3l8Bg",
]
for url in should_match:
- self.assertTrue(YouTube.can_handle_url(url))
+ self.assertTrue(YouTube.can_handle_url(url), url)
should_not_match = [
+ "https://accounts.google.com/",
"https://www.youtube.com",
+ "https://www.youtube.com/account",
+ "https://www.youtube.com/feed/guide_builder",
+ "https://www.youtube.com/t/terms",
]
for url in should_not_match:
- self.assertFalse(YouTube.can_handle_url(url))
+ self.assertFalse(YouTube.can_handle_url(url), url)
def _test_regex(self, url, expected_string, expected_group):
m = _url_re.match(url)
self.assertIsNotNone(m)
self.assertEqual(expected_string, m.group(expected_group))
- def test_regex_liveChannel_c(self):
- self._test_regex("https://www.youtube.com/c/EXAMPLE/live",
- "EXAMPLE", "liveChannel")
-
- def test_regex_liveChannel_no_c(self):
- self._test_regex("https://www.youtube.com/EXAMPLE1/live",
- "EXAMPLE1", "liveChannel")
-
- def test_regex_user_channel(self):
- self._test_regex("https://www.youtube.com/channel/EXAMPLE2",
- "EXAMPLE2", "user")
-
- def test_regex_user_user(self):
- self._test_regex("https://www.youtube.com/channel/EXAMPLE3",
- "EXAMPLE3", "user")
-
- def test_regex_user_embed_list_stream(self):
- self._test_regex("https://www.youtube.com/embed/live_stream?channel=UCNye-wNBqNL5ZzHSJj3l8Bg",
- "UCNye-wNBqNL5ZzHSJj3l8Bg", "user")
-
- def test_regex_user_embed_list_stream_2(self):
- self._test_regex("https://www.youtube.com/embed/live_stream?channel=UCNye-wNBqNL5ZzHSJj3l8Bg&autoplay=1&modestbranding=1&rel=0&showinfo=0&color=white&fs=1",
- "UCNye-wNBqNL5ZzHSJj3l8Bg", "user")
-
def test_regex_video_id_v(self):
self._test_regex("https://www.youtube.com/v/aqz-KE-bpKQ",
"aqz-KE-bpKQ", "video_id")
| plugins.youtube: fix url check
valid url example:
https://www.youtube.com/c/ТелеканалНАШ
| # [Codecov](https://codecov.io/gh/streamlink/streamlink/pull/2557?src=pr&el=h1) Report
> Merging [#2557](https://codecov.io/gh/streamlink/streamlink/pull/2557?src=pr&el=desc) into [master](https://codecov.io/gh/streamlink/streamlink/commit/0f01f35a6356595f42cf8ab0f1f4a282b41cbbe6?src=pr&el=desc) will **decrease** coverage by `1.07%`.
> The diff coverage is `n/a`.
```diff
@@ Coverage Diff @@
## master #2557 +/- ##
==========================================
- Coverage 52.54% 51.46% -1.08%
==========================================
Files 239 239
Lines 15131 14797 -334
==========================================
- Hits 7950 7616 -334
Misses 7181 7181
```
| 2019-07-27T18:58:15 |
streamlink/streamlink | 2,568 | streamlink__streamlink-2568 | [
"2564"
] | 1aaab4bf0b1d21f3e4b5f452dfd8653efc537c7a | diff --git a/src/streamlink/plugins/wwenetwork.py b/src/streamlink/plugins/wwenetwork.py
--- a/src/streamlink/plugins/wwenetwork.py
+++ b/src/streamlink/plugins/wwenetwork.py
@@ -1,47 +1,29 @@
from __future__ import print_function
-import re
-from pprint import pprint
-import time
+import json
+import logging
+import re
from streamlink import PluginError
-from streamlink.cache import Cache
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import useragents
-from streamlink.plugin.api import validate
-from streamlink.compat import urlparse, parse_qsl
from streamlink.stream import HLSStream
+from streamlink.utils import memoize
+from streamlink.compat import urlparse, parse_qsl
+from streamlink.utils.times import seconds_to_hhmmss
+
+log = logging.getLogger(__name__)
class WWENetwork(Plugin):
- url_re = re.compile(r"https?://network.wwe.com")
- content_id_re = re.compile(r'''"content_id" : "(\d+)"''')
- playback_scenario = "HTTP_CLOUD_WIRED"
- login_url = "https://secure.net.wwe.com/workflow.do"
- login_page_url = "https://secure.net.wwe.com/enterworkflow.do?flowId=account.login&forwardUrl=http%3A%2F%2Fnetwork.wwe.com"
- api_url = "https://ws.media.net.wwe.com/ws/media/mf/op-findUserVerifiedEvent/v-2.3"
- _info_schema = validate.Schema(
- validate.union({
- "status": validate.union({
- "code": validate.all(validate.xml_findtext(".//status-code"), validate.transform(int)),
- "message": validate.xml_findtext(".//status-message"),
- }),
- "urls": validate.all(
- validate.xml_findall(".//url"),
- [validate.getattr("text")]
- ),
- validate.optional("fingerprint"): validate.xml_findtext(".//updated-fingerprint"),
- validate.optional("session_key"): validate.xml_findtext(".//session-key"),
- "session_attributes": validate.all(
- validate.xml_findall(".//session-attribute"),
- [validate.getattr("attrib"),
- validate.union({
- "name": validate.get("name"),
- "value": validate.get("value")
- })]
- )
- })
- )
+ url_re = re.compile(r"https?://watch.wwe.com/(channel)?")
+ site_config_re = re.compile(r'''">window.__data = (\{.*?\})</script>''')
+ stream_url = "https://dce-frontoffice.imggaming.com/api/v2/stream/{id}"
+ live_url = "https://dce-frontoffice.imggaming.com/api/v2/event/live"
+ login_url = "https://dce-frontoffice.imggaming.com/api/v2/login"
+ API_KEY = "cca51ea0-7837-40df-a055-75eb6347b2e7"
+
+ customer_id = 16
arguments = PluginArguments(
PluginArgument(
"email",
@@ -66,105 +48,105 @@ class WWENetwork(Plugin):
def __init__(self, url):
super(WWENetwork, self).__init__(url)
self.session.http.headers.update({"User-Agent": useragents.CHROME})
- self._session_attributes = Cache(filename="plugin-cache.json", key_prefix="wwenetwork:attributes")
- self._session_key = self.cache.get("session_key")
- self._authed = self._session_attributes.get("ipid") and self._session_attributes.get("fprt")
+ self.auth_token = None
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
+ def get_title(self):
+ if self.page_config:
+ for page in self.page_config["cache"]["page"].values():
+ return page['item']['title']
+
+ def request(self, method, url, **kwargs):
+ headers = kwargs.pop("headers", {})
+ headers.update({"x-api-key": self.API_KEY,
+ "Origin": "https://watch.wwe.com",
+ "Referer": "https://watch.wwe.com/signin",
+ "Accept": "application/json",
+ "Realm": "dce.wwe"})
+ if self.auth_token:
+ headers["Authorization"] = "Bearer {0}".format(self.auth_token)
+
+ kwargs["raise_for_status"] = False
+ log.debug("API request: {0} {1}".format(method, url))
+ res = self.session.http.request(method, url, headers=headers, **kwargs)
+ data = self.session.http.json(res)
+
+ if "status" in data and data["status"] != 200:
+ log.debug("API request failed: {0}:{1} ({2})".format(data["status"], data.get("code"), "; ".join(data.get("messages", []))))
+ return data
+
def login(self, email, password):
self.logger.debug("Attempting login as {0}", email)
# sets some required cookies to login
- self.session.http.get(self.login_page_url)
- # login
- res = self.session.http.post(self.login_url, data=dict(registrationAction='identify',
- emailAddress=email,
- password=password,
- submitButton=""),
- headers={"Referer": self.login_page_url},
- allow_redirects=False)
-
- self._authed = "Authentication Error" not in res.text
- if self._authed:
- self._session_attributes.set("ipid", res.cookies.get("ipid"), expires=3600 * 1.5)
- self._session_attributes.set("fprt", res.cookies.get("fprt"), expires=3600 * 1.5)
-
- return self._authed
-
- def _update_session_attribute(self, key, value):
- if value:
- self._session_attributes.set(key, value, expires=3600 * 1.5) # 1h30m expiry
- self.session.http.cookies.set(key, value)
+ data = self.request('POST', self.login_url,
+ data=json.dumps({"id": email, "secret": password}),
+ headers={"Content-Type": "application/json"})
+ if "authorisationToken" in data:
+ self.auth_token = data["authorisationToken"]
- @property
- def session_key(self):
- return self._session_key
+ return self.auth_token
- @session_key.setter
- def session_key(self, value):
- self.cache.set("session_key", value)
- self._session_key = value
+ @property
+ @memoize
+ def page_config(self):
+ log.debug("Loading page config")
+ res = self.session.http.get(self.url)
+ m = self.site_config_re.search(res.text)
+ return m and json.loads(m.group(1))
def _get_media_info(self, content_id):
"""
Get the info about the content, based on the ID
- :param content_id:
+ :param content_id: contentId for the video
:return:
"""
- params = {"identityPointId": self._session_attributes.get("ipid"),
- "fingerprint": self._session_attributes.get("fprt"),
- "contentId": content_id,
- "playbackScenario": self.playback_scenario,
- "platform": "WEB_MEDIAPLAYER_5",
- "subject": "LIVE_EVENT_COVERAGE",
- "frameworkURL": "https://ws.media.net.wwe.com",
- "_": int(time.time())}
- if self.session_key:
- params["sessionKey"] = self.session_key
- url = self.api_url.format(id=content_id)
- res = self.session.http.get(url, params=params)
- return self.session.http.xml(res, ignore_ns=True, schema=self._info_schema)
-
- def _get_content_id(self):
+ info = self.request('GET', self.stream_url.format(id=content_id))
+ return self.request('GET', info.get("playerUrlCallback"))
+
+ def _get_video_id(self):
# check the page to find the contentId
- res = self.session.http.get(self.url)
- m = self.content_id_re.search(res.text)
- if m:
- return m.group(1)
+ log.debug("Searching for content ID")
+ if self.page_config:
+ for page in self.page_config["cache"]["page"].values():
+ try:
+ if page['item']['type'] == "channel":
+ return self._get_live_id()
+ else:
+ return "vod/{id}".format(id=page['item']['customFields']['DiceVideoId'])
+ except KeyError:
+ log.error("Could not find video ID")
+ return
+
+ def _get_live_id(self):
+ log.debug("Loading live event")
+ res = self.request('GET', self.live_url)
+ for event in res.get('events', []):
+ return "event/{sportId}/{propertyId}/{tournamentId}/{id}".format(**event)
def _get_streams(self):
- email = self.get_option("email")
- password = self.get_option("password")
+ if not self.login(self.get_option("email"), self.get_option("password")):
+ raise PluginError("Login failed")
- if not self._authed and (not email and not password):
- self.logger.error("A login for WWE Network is required, use --wwenetwork-email/"
- "--wwenetwork-password to set them")
- return
+ try:
+ start_point = int(float(dict(parse_qsl(urlparse(self.url).query)).get("startPoint", 0.0)))
+ if start_point > 0:
+ log.info("Stream will start at {0}".format(seconds_to_hhmmss(start_point)))
+ except ValueError:
+ start_point = 0
- if not self._authed:
- if not self.login(email, password):
- self.logger.error("Failed to login, check your username/password")
- return
+ content_id = self._get_video_id()
- content_id = self._get_content_id()
if content_id:
self.logger.debug("Found content ID: {0}", content_id)
info = self._get_media_info(content_id)
- if info["status"]["code"] == 1:
- # update the session attributes
- self._update_session_attribute("fprt", info.get("fingerprint"))
- for attr in info["session_attributes"]:
- self._update_session_attribute(attr["name"], attr["value"])
-
- if info.get("session_key"):
- self.session_key = info.get("session_key")
- for url in info["urls"]:
- for s in HLSStream.parse_variant_playlist(self.session, url, name_fmt="{pixels}_{bitrate}").items():
- yield s
+ if info.get("hlsUrl"):
+ for s in HLSStream.parse_variant_playlist(self.session, info["hlsUrl"], start_offset=start_point).items():
+ yield s
else:
- raise PluginError("Could not load streams: {message} ({code})".format(**info["status"]))
+ log.error("Could not find the HLS URL")
__plugin__ = WWENetwork
diff --git a/src/streamlink/utils/times.py b/src/streamlink/utils/times.py
--- a/src/streamlink/utils/times.py
+++ b/src/streamlink/utils/times.py
@@ -48,6 +48,13 @@ def hours_minutes_seconds(value):
return s
+def seconds_to_hhmmss(seconds):
+ hours, seconds = divmod(seconds, 3600)
+ minutes, seconds = divmod(seconds, 60)
+ return "{0:02d}:{1:02d}:{2}".format(int(hours), int(minutes), "{0:02.1f}".format(seconds) if seconds % 1 else "{0:02d}".format(int(seconds)))
+
+
__all__ = [
"hours_minutes_seconds",
+ "seconds_to_hhmmss"
]
| diff --git a/tests/plugins/test_wwenetwork.py b/tests/plugins/test_wwenetwork.py
--- a/tests/plugins/test_wwenetwork.py
+++ b/tests/plugins/test_wwenetwork.py
@@ -6,7 +6,7 @@
class TestPluginWWENetwork(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
- 'http://network.wwe.com/shows/collections/267406022',
+ 'https://watch.wwe.com/in-ring/3622',
]
for url in should_match:
self.assertTrue(WWENetwork.can_handle_url(url))
diff --git a/tests/test_utils_times.py b/tests/test_utils_times.py
--- a/tests/test_utils_times.py
+++ b/tests/test_utils_times.py
@@ -1,6 +1,6 @@
import unittest
-from streamlink.utils.times import hours_minutes_seconds
+from streamlink.utils.times import hours_minutes_seconds, seconds_to_hhmmss
class TestUtilsTimes(unittest.TestCase):
@@ -37,3 +37,13 @@ def test_hours_minutes_seconds(self):
with self.assertRaises(ValueError):
hours_minutes_seconds("11:ERR:00")
+
+ def test_seconds_to_hhmmss(self):
+
+ self.assertEqual(seconds_to_hhmmss(0), "00:00:00")
+ self.assertEqual(seconds_to_hhmmss(1), "00:00:01")
+ self.assertEqual(seconds_to_hhmmss(60), "00:01:00")
+ self.assertEqual(seconds_to_hhmmss(3600), "01:00:00")
+
+ self.assertEqual(seconds_to_hhmmss(13997), "03:53:17")
+ self.assertEqual(seconds_to_hhmmss(13997.4), "03:53:17.4")
| Updated WWEN plugin PLZ
<!--
Thanks for reporting a plugin issue!
USE THE TEMPLATE. Otherwise your plugin issue may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed plugin issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Issue
WWE have now gone to 2.0 and is doing 1080p VOD, plugin needs updating PLZ
### Description
WWE have now gone to 2.0 and is doing 1080p VOD, plugin needs updating PLZ I have tried letmeatit and still same problem and adownloader. uses index.m3u8 and not bitrate.m3u8 master has added code as well.
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. ...
2. ...
3. ...
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a plugin issue!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
REPLACE THIS TEXT WITH THE LOG OUTPUT
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| I'd be willing to provide my WWE Network account temporarily if needed (although I'd recommend the devs who made free trial accounts for the development of the plugin check to see if they have any email offers from WWE, they've been offering 3 months for 99 cents lately).
The site has had a complete redesign and moved to a different streaming provider (used to use BAMTech, moved to Endeavor), so I imagine very little of the existing code will be of use (even the URL structure has changed, for example, Wrestlemania 20 used to be http://network.wwe.com/video/v31362293, and is now https://watch.wwe.com/episode/WrestleMania-20-5563)
99¢!? OUTRAGEOUS! Unfortunately they didn't give me that offer, but I'll see if I can get another free trial...
I would give my login details but its not mine as i used a friends account and don't think they would be happy. but @NikoofDeath is right.
I have a network account and am also a passable developer, I could try to hack in support for the new version, if someone is willing to mentor me a bit.
I won't be able to do this before next weekend (first of august) so if someone can get there first, go for it
I made a program in python that allows you to download videos from the WWE network. I finished it today, it's not robust so you have to be very careful when downloading, one mistake and it'll crash.
> I made a program in python that allows you to download videos from the WWE network. I finished it today, it's not robust so you have to be very careful when downloading, one mistake and it'll crash.
I use the python way but like it simple or when i want to run a batch code so wanted this plugin fixed.
I don't see any harm on your app.
I have put together an updated plugin that should work. I haven't tested it too much (only started writing it a few hours ago), but it seems to work got all VOD and the current live stream. It would be good to get some people to test it out :)
> I have put together an updated plugin that should work. I haven't tested it too much (only started writing it a few hours ago), but it seems to work got all VOD and the current live stream. It would be good to get some people to test it out :)
I can test if you like
> I have put together an updated plugin that should work. I haven't tested it too much (only started writing it a few hours ago), but it seems to work got all VOD and the current live stream. It would be good to get some people to test it out :)
I'll test it when I get back home tonight
To test the new plugin, grab [wwenetwork.py](https://raw.githubusercontent.com/beardypig/streamlink/wwenetwork-fix/src/streamlink/plugins/wwenetwork.py) and sideload it. Check in the docs for how to [Sideload a Plugin](https://streamlink.github.io/cli.html?highlight=sideload#sideloading-plugins) :)
Found one weird bug, for NXT Takeover XXV (https://watch.wwe.com/episode/WWE-NXT-TakeOver-XXV-95224), the normal show link plays the preshow (https://watch.wwe.com/program/WWE-NXT-TakeOver-XXV-Pre-Show-95222) in streamlink, and vice versa. Haven't noticed this with any other shows with preshows though.
Thanks @NikoofDeath, I'll take a look... weird, probably something to do with the contentId being misidentified :)
> Thanks @NikoofDeath, I'll take a look... weird, probably something to do with the contentId being misidentified :)
LetMeAtIt has sorted the plugin for his app, might be good to check and see what is missing?
@whitetop I dunno what that is, it might be useful- but the issues is likely a small bug, I just didn’t have time to look yet.
> @whitetop I dunno what that is, it might be useful- but the issues is likely a small bug, I just didn’t have time to look yet.
Its a app that people use to download from the WWEN.
No rush as life comes first.
@beardypig Another issue (and one that I had with the old plugin), might just be a player issue on my end - when using streaming mode, the playback ends prematurely (about 15 seconds or so), issue doesn't happen when using an output file. I believe this is due to streamlink loading the last part of the stream, recognizing the end of stream, and closing before finishing playback of the loaded content.
@NikoofDeath, try the `--player-no-close` option and see if that helps. Your assessment sounds correct and is probably a bug in streamlink in general, are you using Windows?
> @NikoofDeath, try the `--player-no-close` option and see if that helps. Your assessment sounds correct and is probably a bug in streamlink in general, are you using Windows?
I had that same issue and I'm using linux, will test this too later today
@beardypig Yup, that fixes it! I am using windows BTW, with MPC-HC as my player.
@NikoofDeath I believe I have resolved the issue where the preshow played instead of the actual show: [wwenetwork.py](https://raw.githubusercontent.com/beardypig/streamlink/wwenetwork-fix/src/streamlink/plugins/wwenetwork.py)
Hey guys I got this working but when I run it just plays on demand Smackville. How do I change to the live stream?
@Kamakzie, what URL did you put? Can you show me the out of of
```
streamlink -l debug YOUR_URL_HERE
```
?
D:\Program Files (x86)\Streamlink>streamlink -l debug watch.wwe.com
[Streamlink for Windows v1.0.0 - Git f7ac894]
[session][debug] Plugin wwenetwork is being overridden by D:\Program Files (x86)\Streamlink\plugins\wwenetwork.py
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.3
[cli][debug] Streamlink: 1.0.0+f7ac894
[cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.44.0) | 2019-07-29T11:41:50 |
streamlink/streamlink | 2,575 | streamlink__streamlink-2575 | [
"2457"
] | 3302f655a8309c944ffbfdd9e8000c59532b8911 | diff --git a/src/streamlink/plugins/tv1channel.py b/src/streamlink/plugins/tv1channel.py
--- a/src/streamlink/plugins/tv1channel.py
+++ b/src/streamlink/plugins/tv1channel.py
@@ -1,25 +1,32 @@
import re
from streamlink.plugin import Plugin
-
-_url_re = re.compile(r'''https?://(www\.)?tv1channel\.org/''')
-_embed_re = re.compile(r'''<iframe.+src="([^"]+)"''')
+from streamlink.plugin.api import useragents
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
class TV1Channel(Plugin):
+ _url_re = re.compile(r'https?://(?:www\.)?tv1channel\.org/(?!play/)(?:index\.php/livetv)?')
+
@classmethod
def can_handle_url(cls, url):
- return _url_re.match(url)
+ return cls._url_re.match(url) is not None
def _get_streams(self):
+ self.session.http.headers.update({'User-Agent': useragents.FIREFOX})
res = self.session.http.get(self.url)
- match = _embed_re.search(res.text)
+ for iframe in itertags(res.text, 'iframe'):
+ if 'cdn.netbadgers.com' not in iframe.attributes.get('src'):
+ continue
+
+ res = self.session.http.get(iframe.attributes.get('src'))
+ for source in itertags(res.text, 'source'):
+ if source.attributes.get('src') and source.attributes.get('src').endswith('.m3u8'):
+ return HLSStream.parse_variant_playlist(self.session,
+ source.attributes.get('src'))
- if match:
- url = match.group(1)
- if url.startswith('//'):
- url = 'https:{0}'.format(url)
- return self.session.streams(url)
+ break
__plugin__ = TV1Channel
| diff --git a/tests/plugins/test_tv1channel.py b/tests/plugins/test_tv1channel.py
--- a/tests/plugins/test_tv1channel.py
+++ b/tests/plugins/test_tv1channel.py
@@ -8,8 +8,8 @@ def test_can_handle_url(self):
# should match
self.assertTrue(TV1Channel.can_handle_url("http://tv1channel.org/"))
self.assertTrue(TV1Channel.can_handle_url("http://tv1channel.org/index.php/livetv"))
- self.assertTrue(TV1Channel.can_handle_url("http://www.tv1channel.org/play/video.php?id=325"))
- self.assertTrue(TV1Channel.can_handle_url("http://www.tv1channel.org/play/video.php?id=340"))
# shouldn't match
self.assertFalse(TV1Channel.can_handle_url("https://local.local"))
+ self.assertFalse(TV1Channel.can_handle_url("http://www.tv1channel.org/play/video.php?id=325"))
+ self.assertFalse(TV1Channel.can_handle_url("http://www.tv1channel.org/play/video.php?id=340"))
| TV1 Plugin - new player being used
## Bug Report
- [x] This is a bug report and I have read the contribution guidelines.
### Description
TV1 won't start, because they're using a different player now.
### Expected / Actual behavior
Should have worked?
### Reproduction steps / Explicit stream URLs to test
1. streamlink http://tv1channel.org/ best
2. ? ? ?
3. profit
| static url
```
streamlink "https://stream.bittubeapp.com/bittubelive/tv1channebg/playlist.m3u8" best --http-no-ssl-verify
```
---
**EDIT**:
they changed their service again | 2019-08-04T16:05:09 |
streamlink/streamlink | 2,576 | streamlink__streamlink-2576 | [
"2400"
] | 3302f655a8309c944ffbfdd9e8000c59532b8911 | diff --git a/src/streamlink/plugins/npo.py b/src/streamlink/plugins/npo.py
deleted file mode 100644
--- a/src/streamlink/plugins/npo.py
+++ /dev/null
@@ -1,132 +0,0 @@
-"""Plugin for NPO: Nederlandse Publieke Omroep
-
-Supports:
- VODs:
- - https://www.npo.nl/nos-journaal/07-07-2017/POW_03375651
- - https://www.zapp.nl/topdoks/gemist/VPWON_1276930
- - https://zappelin.nl/10-voor/gemist/VPWON_1271522
- - https://www.npostart.nl/nos-journaal/07-07-2017/POW_03375651
- Live:
- - https://www.npo.nl/live/npo-1
- - https://zappelin.nl/tv-kijken
- - https://www.npostart.nl/live/npo-1
-
-"""
-
-import re
-
-from streamlink.plugin import Plugin, PluginArguments, PluginArgument
-from streamlink.plugin.api import useragents
-from streamlink.plugin.api import validate
-from streamlink.stream import HLSStream
-from streamlink.stream import HTTPStream
-from streamlink.utils import parse_json
-
-
-class NPO(Plugin):
- api_url = "http://ida.omroep.nl/app.php/{endpoint}"
- url_re = re.compile(r"https?://(\w+\.)?(npostart\.nl|npo\.nl|zapp\.nl|zappelin\.nl)/")
- media_id_re = re.compile(r'''<npo-player\smedia-id=["'](?P<media_id>[^"']+)["']''')
- prid_re = re.compile(r'''(?:data(-alt)?-)?prid\s*[=:]\s*(?P<q>["'])(\w+)(?P=q)''')
- react_re = re.compile(r'''data-react-props\s*=\s*(?P<q>["'])(?P<data>.*?)(?P=q)''')
-
- auth_schema = validate.Schema({"token": validate.text}, validate.get("token"))
- streams_schema = validate.Schema({
- "items": [
- [{
- "label": validate.text,
- "contentType": validate.text,
- "url": validate.url(),
- "format": validate.text
- }]
- ]
- }, validate.get("items"), validate.get(0))
- stream_info_schema = validate.Schema(validate.any(
- validate.url(),
- validate.all({"errorcode": 0, "url": validate.url()},
- validate.get("url"))
- ))
- arguments = PluginArguments(
- PluginArgument(
- "subtitles",
- action="store_true",
- help="""
- Include subtitles for the deaf or hard of hearing, if available.
- """
- )
- )
-
- @classmethod
- def can_handle_url(cls, url):
- return cls.url_re.match(url) is not None
-
- def __init__(self, url):
- super(NPO, self).__init__(url)
- self._token = None
- self.session.http.headers.update({"User-Agent": useragents.CHROME})
-
- def api_call(self, endpoint, schema=None, params=None):
- url = self.api_url.format(endpoint=endpoint)
- res = self.session.http.get(url, params=params)
- return self.session.http.json(res, schema=schema)
-
- @property
- def token(self):
- if not self._token:
- self._token = self.api_call("auth", schema=self.auth_schema)
- return self._token
-
- def _get_prid(self, subtitles=False):
- res = self.session.http.get(self.url)
- bprid = None
-
- # Locate the asset id for the content on the page
- for alt, _, prid in self.prid_re.findall(res.text):
- if alt and subtitles:
- bprid = prid
- elif bprid is None:
- bprid = prid
-
- if bprid is None:
- m = self.react_re.search(res.text)
- if m:
- data = parse_json(m.group("data").replace(""", '"'))
- bprid = data.get("mid")
-
- if bprid is None:
- m = self.media_id_re.search(res.text)
- if m:
- bprid = m.group('media_id')
-
- return bprid
-
- def _get_streams(self):
- asset_id = self._get_prid(self.get_option("subtitles"))
-
- if asset_id:
- self.logger.debug("Found asset id: {0}", asset_id)
- streams = self.api_call(asset_id,
- params=dict(adaptive="yes",
- token=self.token),
- schema=self.streams_schema)
-
- for stream in streams:
- if stream["format"] in ("adaptive", "hls", "mp4"):
- if stream["contentType"] == "url":
- stream_url = stream["url"]
- else:
- # using type=json removes the javascript function wrapper
- info_url = stream["url"].replace("type=jsonp", "type=json")
-
- # find the actual stream URL
- stream_url = self.session.http.json(self.session.http.get(info_url),
- schema=self.stream_info_schema)
-
- if stream["format"] in ("adaptive", "hls"):
- for s in HLSStream.parse_variant_playlist(self.session, stream_url).items():
- yield s
- elif stream["format"] in ("mp3", "mp4"):
- yield "vod", HTTPStream(self.session, stream_url)
-
-
-__plugin__ = NPO
| diff --git a/tests/plugins/test_npo.py b/tests/plugins/test_npo.py
deleted file mode 100644
--- a/tests/plugins/test_npo.py
+++ /dev/null
@@ -1,23 +0,0 @@
-import unittest
-
-from streamlink.plugins.npo import NPO
-
-
-class TestPluginNPO(unittest.TestCase):
- def test_can_handle_url(self):
- should_match = [
- 'https://www.npo.nl/live/npo-1',
- 'https://www.npo.nl/live/npo-2',
- 'https://www.npo.nl/live/npo-zapp',
- 'https://www.zapp.nl/tv-kijken',
- 'https://zappelin.nl/schatkist/videos/VPWON_1284504',
- ]
- for url in should_match:
- self.assertTrue(NPO.can_handle_url(url))
-
- def test_can_handle_url_negative(self):
- should_not_match = [
- 'https://example.com/index.html',
- ]
- for url in should_not_match:
- self.assertFalse(NPO.can_handle_url(url))
| NPO plugin unable to open stream URL
<!--
Thanks for reporting an issue!
USE THE TEMPLATE. Otherwise your issue may be rejected.
This template should only be used if your issue doesn't match the other more specific ones.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed issues:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue
Please see the text preview to avoid unnecessary formatting errors.
-->
## Issue
<!-- Replace [ ] with [x] in order to check the box -->
- [ ] This is not a bug report, feature request, or plugin issue/request.
- [x] I have read the contribution guidelines.
### Description
NPO plugin unable to open stream URL.
streamlink http://www.npo.nl/live/npo-1
[cli][info] Found matching plugin npo for URL http://www.npo.nl/live/npo-1
error: Unable to open URL: http://ida.omroep.nl/app.php/LI_NL1_4188102 (500 Server Error: Internal Server Error for url: http://ida.omroep.nl/app.php/LI_NL1_4188102?adaptive=yes&token=2tap7477ib3kpqusr9t6gqs6s4)
### Expected / Actual behavior
Play stream
500 Server Error
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. streamlink http://www.npo.nl/live/npo-1
### Logs
<!--
TEXT LOG OUTPUT IS OPTIONAL for generic issues!
However, depending on the issue, log output can be useful for the developers to understand the problem. It also includes information about your platform. If you don't intend to include log output, please at least provide these platform details.
Thanks!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
N/A
### Additional comments, screenshots, etc.
N/A
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| DRM
Are there other streams that work? If not we should mark it as broken and consider removing it. If there are other streams that work then a better error message is needed for the ones that don’t :)
It seems that they completely removed the "old"API:
error: Unable to open URL: http://ida.omroep.nl/app.php/auth (410 Client Error: Gone for url: https://ida.omroep.nl/app.php/auth)
I'm afraid that no content from NPO is accessible anymore. | 2019-08-04T16:12:58 |
streamlink/streamlink | 2,580 | streamlink__streamlink-2580 | [
"2466"
] | d703306775a3afc6d22a7084bb2968ed557b94f3 | diff --git a/src/streamlink/plugins/lrt.py b/src/streamlink/plugins/lrt.py
--- a/src/streamlink/plugins/lrt.py
+++ b/src/streamlink/plugins/lrt.py
@@ -1,20 +1,16 @@
import logging
import re
-from functools import partial
from streamlink.plugin import Plugin
from streamlink.stream import HLSStream
-from streamlink.utils import parse_json
-from streamlink.compat import urlparse
log = logging.getLogger(__name__)
class LRT(Plugin):
- _url_re = re.compile(r"https?://(?:www\.)?lrt.lt/mediateka/.")
- _source_re = re.compile(r'sources\s*:\s*(\[{.*?}\]),', re.DOTALL | re.IGNORECASE)
- js_to_json = partial(re.compile(r'(?!<")(\w+)\s*:\s*(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2')
-
+ _url_re = re.compile(r"https?://(?:www\.)?lrt.lt/mediateka/tiesiogiai/.")
+ _video_id_re = re.compile(r"""var\svideo_id\s*=\s*["'](?P<video_id>\w+)["']""")
+ API_URL = "https://www.lrt.lt/servisai/stream_url/live/get_live_url.php?channel={0}"
@classmethod
def can_handle_url(cls, url):
@@ -22,21 +18,16 @@ def can_handle_url(cls, url):
def _get_streams(self):
page = self.session.http.get(self.url)
- m = self._source_re.search(page.text)
+ m = self._video_id_re.search(page.text)
if m:
- params = ""
- data = m.group(1)
- log.debug("Source data: {0}".format(data))
- if "location.hash.substring" in data:
- log.debug("Removing hash substring addition")
- data = re.sub(r"\s*\+\s*location.hash.substring\(\d+\)", "", data)
- params = urlparse(self.url).fragment
- data = self.js_to_json(data)
- for stream in parse_json(data):
- for s in HLSStream.parse_variant_playlist(self.session, stream['file'], params=params).items():
- yield s
+ video_id = m.group("video_id")
+ data = self.session.http.get(self.API_URL.format(video_id)).json()
+ hls_url = data["response"]["data"]["content"]
+
+ for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
+ yield s
else:
- log.debug("No match for sources regex")
+ log.debug("No match for video_id regex")
__plugin__ = LRT
| diff --git a/tests/plugins/test_lrt.py b/tests/plugins/test_lrt.py
--- a/tests/plugins/test_lrt.py
+++ b/tests/plugins/test_lrt.py
@@ -6,19 +6,22 @@
class TestPluginLRT(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-opus",
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-klasika",
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-radijas",
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica",
+ "https://www.lrt.lt/mediateka/tiesiogiai/lrt-plius",
"https://www.lrt.lt/mediateka/tiesiogiai/lrt-televizija",
- "https://www.lrt.lt/mediateka/tiesiogiai/lrt-kultura",
- "https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica"
- "https://www.lrt.lt/mediateka/irasas/1013694276/savanoriai-tures-galimybe-pamatyti-popieziu-is-arciau#wowzaplaystart=1511000&wowzaplayduration=168000"
]
for url in should_match:
- self.assertTrue(LRT.can_handle_url(url))
+ self.assertTrue(LRT.can_handle_url(url), url)
def test_can_handle_url_negative(self):
should_not_match = [
"https://www.lrt.lt",
"https://www.youtube.com",
+ "https://www.lrt.lt/mediateka/irasas/1013694276/savanoriai-tures-galimybe-pamatyti-popieziu-is-arciau",
]
for url in should_not_match:
- self.assertFalse(LRT.can_handle_url(url))
+ self.assertFalse(LRT.can_handle_url(url), url)
| Update lrt plugin to cover updated page
Hello, this piece of edit should resolve streamlink#2440
Btw first commit to other's projects.
P.S streamlink should also cover VOD part or not?
| # [Codecov](https://codecov.io/gh/streamlink/streamlink/pull/2466?src=pr&el=h1) Report
> Merging [#2466](https://codecov.io/gh/streamlink/streamlink/pull/2466?src=pr&el=desc) into [master](https://codecov.io/gh/streamlink/streamlink/commit/bd24ab87037d0749170b9f14cc45868866078954?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `0%`.
```diff
@@ Coverage Diff @@
## master #2466 +/- ##
=========================================
+ Coverage 52.6% 52.6% +<.01%
=========================================
Files 239 239
Lines 15059 15057 -2
=========================================
- Hits 7922 7921 -1
+ Misses 7137 7136 -1
```
> [plugin.lrt][debug] No match for sources regex
does not fix it
---
using the video_id is probably a better way to fix this | 2019-08-07T16:20:48 |
streamlink/streamlink | 2,586 | streamlink__streamlink-2586 | [
"2585"
] | 0f011ae9c95640f5d73f05e2ac9d8510508104ed | diff --git a/src/streamlink/plugins/wwenetwork.py b/src/streamlink/plugins/wwenetwork.py
--- a/src/streamlink/plugins/wwenetwork.py
+++ b/src/streamlink/plugins/wwenetwork.py
@@ -21,6 +21,7 @@ class WWENetwork(Plugin):
stream_url = "https://dce-frontoffice.imggaming.com/api/v2/stream/{id}"
live_url = "https://dce-frontoffice.imggaming.com/api/v2/event/live"
login_url = "https://dce-frontoffice.imggaming.com/api/v2/login"
+ page_config_url = "https://cdn.watch.wwe.com/api/page"
API_KEY = "cca51ea0-7837-40df-a055-75eb6347b2e7"
customer_id = 16
@@ -55,9 +56,7 @@ def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
def get_title(self):
- if self.page_config:
- for page in self.page_config["cache"]["page"].values():
- return page['item']['title']
+ return self.item_config['title']
def request(self, method, url, **kwargs):
headers = kwargs.pop("headers", {})
@@ -91,11 +90,22 @@ def login(self, email, password):
@property
@memoize
- def page_config(self):
+ def item_config(self):
log.debug("Loading page config")
- res = self.session.http.get(self.url)
- m = self.site_config_re.search(res.text)
- return m and json.loads(m.group(1))
+ p = urlparse(self.url)
+ res = self.session.http.get(self.page_config_url,
+ params=dict(device="web_browser",
+ ff="idp,ldp",
+ item_detail_expand="all",
+ lang="en-US",
+ list_page_size="1",
+ max_list_prefetch="1",
+ path=p.path,
+ segments="es",
+ sub="Registered",
+ text_entry_format="html"))
+ data = self.session.http.json(res)
+ return data["item"]
def _get_media_info(self, content_id):
"""
@@ -109,16 +119,14 @@ def _get_media_info(self, content_id):
def _get_video_id(self):
# check the page to find the contentId
log.debug("Searching for content ID")
- if self.page_config:
- for page in self.page_config["cache"]["page"].values():
- try:
- if page['item']['type'] == "channel":
- return self._get_live_id()
- else:
- return "vod/{id}".format(id=page['item']['customFields']['DiceVideoId'])
- except KeyError:
- log.error("Could not find video ID")
- return
+ try:
+ if self.item_config['type'] == "channel":
+ return self._get_live_id()
+ else:
+ return "vod/{id}".format(id=self.item_config['customFields']['DiceVideoId'])
+ except KeyError:
+ log.error("Could not find video ID")
+ return
def _get_live_id(self):
log.debug("Loading live event")
| New WWE Network Plugin stopped working
## Plugin Issue
- [x ] This is a plugin issue and I have read the contribution guidelines.
### Description
Presumably due to updates to the website (I know they have been working on fixing some issues with the new site), the WWE Network plugin is no longer able to find streams.
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. Install latest streamlink nightly
2. Try using any WWE Network link (i.e. https://watch.wwe.com/episode/NXT-TakeOver-Toronto-2019-102316)
### Log output
streamlink https://watch.wwe.com/episode/NXT-TakeOver-Toronto-2019-102316 best --loglevel debug
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.6
[cli][debug] Streamlink: 1.1.1+74.g0f011ae
[cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin wwenetwork for URL https://watch.wwe.com/episode/NXT-TakeOver-Toronto-2019-102316
[cli][debug] Plugin specific arguments:
[cli][debug] --wwenetwork-email= (email)
[cli][debug] --wwenetwork-password= (password)
[plugin.wwenetwork][debug] Attempting login as
[plugin.wwenetwork][debug] API request: POST https://dce-frontoffice.imggaming.com/api/v2/login
[plugin.wwenetwork][debug] Searching for content ID
[plugin.wwenetwork][debug] Loading page config
error: No playable streams found on this URL: https://watch.wwe.com/episode/NXT-TakeOver-Toronto-2019-102316
### Additional comments, screenshots, etc.
There had been audio sync problems with the network, although I believe this was across all sources and not a streamlink issue, and their solution for this issue might have caused the plugin to break.
| 2019-08-13T10:34:33 |
||
streamlink/streamlink | 2,596 | streamlink__streamlink-2596 | [
"2594"
] | a2e576b44d482d2ced4494732f643139ab769217 | diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -34,11 +34,8 @@ class BBCiPlayer(Plugin):
tvip_re = re.compile(r'channel"\s*:\s*{\s*"id"\s*:\s*"(\w+?)"')
tvip_master_re = re.compile(r'event_master_brand=(\w+?)&')
account_locals_re = re.compile(r'window.bbcAccount.locals\s*=\s*({.*?});')
- swf_url = "http://emp.bbci.co.uk/emp/SMPf/1.18.3/StandardMediaPlayerChromelessFlash.swf"
- hash = base64.b64decode(
- b"N2RmZjc2NzFkMGM2OTdmZWRiMWQ5MDVkOWExMjE3MTk5MzhiOTJiZg==")
- api_url = ("http://open.live.bbc.co.uk/mediaselector/6/select/"
- "version/2.0/mediaset/{platform}/vpid/{vpid}/format/json/atk/{vpid_hash}/asn/1/")
+ 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"
| BBC Links stopped working?
Anyone else BBC links stopped working?
| We really can't do anything with an issue report like this. Please review the template and provide the debug log and other output requested there. | 2019-08-19T08:19:11 |
|
streamlink/streamlink | 2,597 | streamlink__streamlink-2597 | [
"2592"
] | a2e576b44d482d2ced4494732f643139ab769217 | diff --git a/src/streamlink/plugins/nownews.py b/src/streamlink/plugins/nownews.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/nownews.py
@@ -0,0 +1,49 @@
+import logging
+import re
+import json
+
+from streamlink.plugin import Plugin
+from streamlink.stream import HLSStream
+
+log = logging.getLogger(__name__)
+
+
+class NowNews(Plugin):
+ _url_re = re.compile(r"https?://news.now.com/home/live")
+ epg_re = re.compile(r'''epg.getEPG\("(\d+)"\);''')
+ api_url = "https://hkt-mobile-api.nowtv.now.com/09/1/getLiveURL"
+ backup_332_api = "https://d7lz7jwg8uwgn.cloudfront.net/apps_resource/news/live.json"
+ backup_332_stream = "https://d3i3yn6xwv1jpw.cloudfront.net/live/now332/playlist.m3u8"
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_streams(self):
+ res = self.session.http.get(self.url)
+ m = self.epg_re.search(res.text)
+ channel_id = m and m.group(1)
+ if channel_id:
+ log.debug("Channel ID: {0}".format(channel_id))
+
+ if channel_id == "332":
+ # there is a special backup stream for channel 332
+ bk_res = self.session.http.get(self.backup_332_api)
+ bk_data = self.session.http.json(bk_res)
+ if bk_data and bk_data["backup"]:
+ log.info("Using backup stream for channel 332")
+ return HLSStream.parse_variant_playlist(self.session, self.backup_332_stream)
+
+ api_res = self.session.http.post(self.api_url,
+ headers={"Content-Type": 'application/json'},
+ data=json.dumps(dict(channelno=channel_id,
+ mode="prod",
+ audioCode="",
+ format="HLS",
+ callerReferenceNo="20140702122500")))
+ data = self.session.http.json(api_res)
+ for stream_url in data.get("asset", {}).get("hls", {}).get("adaptive", []):
+ return HLSStream.parse_variant_playlist(self.session, stream_url)
+
+
+__plugin__ = NowNews
| diff --git a/tests/plugins/test_nownews.py b/tests/plugins/test_nownews.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_nownews.py
@@ -0,0 +1,27 @@
+import unittest
+
+import pytest
+
+from streamlink.plugins.nownews import NowNews
+
+
+class TestPluginNowNews:
+ valid_urls = [
+ ("https://news.now.com/home/live",),
+ ("http://news.now.com/home/live",),
+ ("https://news.now.com/home/live331a",),
+ ("http://news.now.com/home/live331a",)
+ ]
+ invalid_urls = [
+ ("https://news.now.com/home/local",),
+ ("http://media.now.com.hk/",),
+ ("https://www.youtube.com",)
+ ]
+
+ @pytest.mark.parametrize(["url"], valid_urls)
+ def test_can_handle_url(self, url):
+ assert NowNews.can_handle_url(url), "url should be handled"
+
+ @pytest.mark.parametrize(["url"], invalid_urls)
+ def test_can_handle_url_negative(self, url):
+ assert not NowNews.can_handle_url(url), "url should not be handled"
| Now News Live (News and Live channel)
## Plugin Request
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
<!-- Explain the plugin and site as clearly as you can. What is the site about? Who runs it? What content does it provide? What value does it bring to Streamlink? Etc. -->
One of a local television station from Hong Kong which currently only accessible via Internet streaming or paid cable subscription. Now News is one of a few disinterested news channel which provide fare perspective reports compared to major aired television in Hong Kong.
### Example stream URLs
<!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. -->
1. https://news.now.com/home/live331a
2. https://news.now.com/home/live
### Additional comments, screenshots, etc.
![chrome_2019-08-18_20-27-07](https://user-images.githubusercontent.com/771955/63224427-92c4d700-c1f6-11e9-8010-500d19f97187.png)
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2019-08-19T11:35:30 |
|
streamlink/streamlink | 2,601 | streamlink__streamlink-2601 | [
"2595"
] | f38d4276ab359b33d7e8638ac3ffc0e5605e64a8 | diff --git a/src/streamlink/plugins/vk.py b/src/streamlink/plugins/vk.py
--- a/src/streamlink/plugins/vk.py
+++ b/src/streamlink/plugins/vk.py
@@ -2,7 +2,7 @@
import logging
import re
-from streamlink.compat import urlparse, unquote
+from streamlink.compat import html_unescape, urlparse, unquote
from streamlink.plugin import Plugin
from streamlink.plugin.api import useragents
from streamlink.plugin.api.utils import itertags
@@ -82,10 +82,7 @@ def _get_streams(self):
for _i in itertags(res.text, 'source'):
if _i.attributes.get('type') == 'application/vnd.apple.mpegurl':
- video_url = _i.attributes['src']
- # Remove invalid URL
- if video_url.startswith('https://vk.com/'):
- continue
+ video_url = html_unescape(_i.attributes['src'])
streams = HLSStream.parse_variant_playlist(self.session,
video_url)
if not streams:
| vk.com No playable streams
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
cant download video.
### Reproduction steps / Explicit stream URLs to test
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink> .\streamlink.bat https://vk.com/video-75371233_456246230
[cli][info] Found matching plugin vk for URL https://vk.com/video-75371233_456246230
error: No playable streams found on this URL: https://vk.com/video-75371233_456246230
### Log output
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink> .\streamlink.bat --loglevel debug https://vk.com/video-75371233_456246230 best
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin vk for URL https://vk.com/video-75371233_456246230
[plugin.vk][debug] video ID: -75371233_456246230
error: No playable streams found on this URL: https://vk.com/video-75371233_456246230
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink>
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink> .\streamlink.bat -p vlc --loglevel debug https://vk.com/video-75371233_456246230 best
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin vk for URL https://vk.com/video-75371233_456246230
[plugin.vk][debug] video ID: -75371233_456246230
error: No playable streams found on this URL: https://vk.com/video-75371233_456246230
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink> .\streamlink.bat -p vlc --loglevel debug https://vk.com/video-75371233_456246230 best --output video-75371233_456246230
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin vk for URL https://vk.com/video-75371233_456246230
[plugin.vk][debug] video ID: -75371233_456246230
error: No playable streams found on this URL: https://vk.com/video-75371233_456246230
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink> .\streamlink.bat -p vlc --loglevel debug https://vk.com/video-75371233_456246230 best --output video-75371233_456246230 --force
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin vk for URL https://vk.com/video-75371233_456246230
[plugin.vk][debug] video ID: -75371233_456246230
error: No playable streams found on this URL: https://vk.com/video-75371233_456246230
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink> .\streamlink.bat -p vlc --loglevel debug https://vk.com/video-75371233_456246230 best --output video-75371233_456246230 --force --record video-75371233_456246230
[cli][debug] OS: Windows 10
[cli][debug] Python: 3.6.5
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0)
[cli][info] Found matching plugin vk for URL https://vk.com/video-75371233_456246230
[plugin.vk][debug] video ID: -75371233_456246230
error: No playable streams found on this URL: https://vk.com/video-75371233_456246230
PS E:\Downloads\web\streamlink-portable-1.1.1-py3.6.5-amd64\streamlink>
### Additional comments, screenshots, etc.
-
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2019-08-25T06:14:42 |
||
streamlink/streamlink | 2,603 | streamlink__streamlink-2603 | [
"2496"
] | 64790e412a6e326e01f65fb45dcad8331f913907 | diff --git a/src/streamlink/plugins/willax.py b/src/streamlink/plugins/willax.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/willax.py
@@ -0,0 +1,26 @@
+import logging
+import re
+
+from streamlink.compat import html_unescape
+from streamlink.plugin import Plugin
+from streamlink.plugin.api import useragents
+from streamlink.plugin.api.utils import itertags
+
+log = logging.getLogger(__name__)
+
+
+class Willax(Plugin):
+ _url_re = re.compile(r'https?://(?:www\.)?willax\.tv/en-vivo')
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_streams(self):
+ self.session.http.headers.update({'User-Agent': useragents.FIREFOX})
+ res = self.session.http.get(self.url)
+ for iframe in itertags(res.text, 'iframe'):
+ return self.session.streams(html_unescape(iframe.attributes.get('src')))
+
+
+__plugin__ = Willax
| diff --git a/tests/plugins/test_willax.py b/tests/plugins/test_willax.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_willax.py
@@ -0,0 +1,19 @@
+import unittest
+
+from streamlink.plugins.willax import Willax
+
+
+class TestPluginWillax(unittest.TestCase):
+ def test_can_handle_url(self):
+ should_match = [
+ 'http://willax.tv/en-vivo/',
+ ]
+ for url in should_match:
+ self.assertTrue(Willax.can_handle_url(url), url)
+
+ def test_can_handle_url_negative(self):
+ should_not_match = [
+ 'http://willax.tv/',
+ ]
+ for url in should_not_match:
+ self.assertFalse(Willax.can_handle_url(url), url)
| [Plugin Request] Willax TV
## Plugin Request
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
Willax Television (better known as Willax ) is an open television channel in Lima / Peru. Centered on entertainment programs, animes, South Korean novels, miscellany and politics.
### Example stream URLs
http://willax.tv/en-vivo/
### Additional comments, screenshots, etc.
Occasionally geo-blocked in Europe.
| 2019-08-26T18:41:10 |
|
streamlink/streamlink | 2,617 | streamlink__streamlink-2617 | [
"2607"
] | 1fb9391de909c242482b41f32df08ec0ebd242c0 | diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py
--- a/src/streamlink/plugins/bbciplayer.py
+++ b/src/streamlink/plugins/bbciplayer.py
@@ -31,8 +31,7 @@ class BBCiPlayer(Plugin):
""", re.VERBOSE)
mediator_re = re.compile(
r'window\.__IPLAYER_REDUX_STATE__\s*=\s*({.*?});', re.DOTALL)
- tvip_re = re.compile(r'channel"\s*:\s*{\s*"id"\s*:\s*"(\w+?)"')
- tvip_master_re = re.compile(r'event_master_brand=(\w+?)&')
+ state_re = re.compile(r'window.__IPLAYER_REDUX_STATE__\s*=\s*({.*});')
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/"
@@ -96,8 +95,8 @@ def _hash_vpid(cls, vpid):
@classmethod
def _extract_nonce(cls, http_result):
"""
- Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it.
- We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests.
+ Given an HTTP response from the session endpoint, extract the nonce, so we can "sign" requests with it.
+ We don't really sign the requests in the traditional sense of a nonce, we just include them in the auth requests.
:param http_result: HTTP response from the bbc session endpoint.
:type http_result: requests.Response
@@ -105,16 +104,9 @@ def _extract_nonce(cls, http_result):
:rtype: string
"""
- # Extract the redirect URL from the last call
- last_redirect_url = urlparse(http_result.history[-1].request.url)
- last_redirect_query = dict(parse_qsl(last_redirect_url.query))
- # Extract the nonce from the query string in the redirect URL
- final_url = urlparse(last_redirect_query['goto'])
- goto_url = dict(parse_qsl(final_url.query))
- goto_url_query = parse_json(goto_url['state'])
-
- # Return the nonce we can use for future queries
- return goto_url_query['nonce']
+ p = urlparse(http_result.url)
+ d = dict(parse_qsl(p.query))
+ return d.get("nonce")
def find_vpid(self, url, res=None):
"""
@@ -135,13 +127,15 @@ def find_vpid(self, url, res=None):
return vpid
def find_tvip(self, url, master=False):
- log.debug("Looking for {0} tvip on {1}", "master" if master else "", url)
+ log.debug("Looking for {0} tvip on {1}".format("master" if master else "", url))
res = self.session.http.get(url)
- if master:
- m = self.tvip_master_re.search(res.text)
- else:
- m = self.tvip_re.search(res.text)
- return m and m.group(1)
+ 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)
@@ -183,6 +177,7 @@ def login(self, ptrt_url):
:return: Whether authentication was successful
:rtype: bool
"""
+
def auth_check(res):
return ptrt_url in ([h.url for h in res.history] + [res.url])
| diff --git a/tests/plugins/test_bbciplayer.py b/tests/plugins/test_bbciplayer.py
--- a/tests/plugins/test_bbciplayer.py
+++ b/tests/plugins/test_bbciplayer.py
@@ -27,20 +27,8 @@ def test_vpid_hash(self):
def test_extract_nonce(self):
mock_nonce = "mock-nonce-nse"
-
- last_response = Response()
- last_response.request = Request('GET', "http://example.com/?" + urlencode(dict(
- goto="http://example.com/?" + urlencode(dict(
- state=json.dumps(dict(nonce=mock_nonce))
- ))
- )))
-
mock_response = Response()
- mock_response.history = [
- Response(), # Add some extra dummy responses in to make sure we always get the last
- Response(),
- last_response
- ]
+ mock_response.url = "http://example.com/?" + urlencode(dict(nonce=mock_nonce))
self.assertEqual(BBCiPlayer._extract_nonce(mock_response), mock_nonce)
| BBC iplayer keyerror: goto
### Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
When trying to connect to bbc iplayer, live stream of bbc channel, it crashes with KeyError: 'goto'
### Reproduction steps / Explicit stream URLs to test
1. i updated streamlink to latest from github: pip-3.6 install --user git+https://github.com/streamlink/streamlink.git
2. i ran the following cmd: streamlink --loglevel debug --http-no-ssl-verify --bbciplayer-username "username" --bbciplayer-password password --player-external-http --player-external-http-port 3280 https://www.bbc.co.uk/iplayer/live/bbctwo best
### Log output
```
[cli][debug] OS: FreeBSD-12.0-RELEASE-p3-amd64-64bit-ELF
[cli][debug] Python: 3.6.8
[cli][debug] Streamlink: 1.2.0+12.g1fb9391
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.50.0)
[cli][info] Found matching plugin bbciplayer for URL https://www.bbc.co.uk/iplayer/live/bbctwo
[cli][debug] Plugin specific arguments:
[cli][debug] --bbciplayer-username=***@*** (username)
[cli][debug] --bbciplayer-password=******** (password)
[plugin.bbciplayer][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
Traceback (most recent call last):
File "/home/username/bin/streamlink", line 11, in <module>
load_entry_point('streamlink==1.2.0+12.g1fb9391', 'console_scripts', 'streamlink')()
File "/home/username/.local/lib/python3.6/site-packages/streamlink_cli/main.py", line 1038, in main
handle_url()
File "/home/username/.local/lib/python3.6/site-packages/streamlink_cli/main.py", line 578, in handle_url
streams = fetch_streams(plugin)
File "/home/username/.local/lib/python3.6/site-packages/streamlink_cli/main.py", line 458, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "/home/username/.local/lib/python3.6/site-packages/streamlink/plugin/plugin.py", line 323, in streams
ostreams = list(ostreams)
File "/home/username/.local/lib/python3.6/site-packages/streamlink/plugins/bbciplayer.py", line 225, in _get_streams
if not self.login(self.url):
File "/home/username/.local/lib/python3.6/site-packages/streamlink/plugins/bbciplayer.py", line 199, in login
http_nonce = self._extract_nonce(session_res)
File "/home/username/.local/lib/python3.6/site-packages/streamlink/plugins/bbciplayer.py", line 112, in _extract_nonce
final_url = urlparse(last_redirect_query['goto'])
KeyError: 'goto'
```
| Yup, same here too. I also updated to the latest git release via pip.
```
streamlink --config /home/mythtv-iptv-setup/conf/streamlinkrc -O bbc.co.uk/iplayer/live/bbcone 396p > /tmp/test.ts
[cli][info] streamlink is running as root! Be careful!
[cli][info] Found matching plugin bbciplayer for URL bbc.co.uk/iplayer/live/bbcone
[plugin.bbciplayer][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
Traceback (most recent call last):
File "/home/mythtv-iptv-setup/utils/streamlink/bin/streamlink", line 10, in <module>
sys.exit(main())
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 1038, in main
handle_url()
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 578, in handle_url
streams = fetch_streams(plugin)
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 458, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink/plugin/plugin.py", line 323, in streams
ostreams = list(ostreams)
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink/plugins/bbciplayer.py", line 225, in _get_streams
if not self.login(self.url):
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink/plugins/bbciplayer.py", line 199, in login
http_nonce = self._extract_nonce(session_res)
File "/home/mythtv-iptv-setup/utils/streamlink/local/lib/python2.7/site-packages/streamlink/plugins/bbciplayer.py", line 112, in _extract_nonce
final_url = urlparse(last_redirect_query['goto'])
KeyError: 'goto'
```
Appears to be an issue with the login flow.
streamlink -V
streamlink 1.2.0+12.g1fb9391
OS: Linux Mint 19.2
streamlink http://www.bbc.co.uk/iplayer/live/bbcone 540p --bbciplayer-username xxxxx --bbciplayer-password xxxxx
[cli][info] Found matching plugin bbciplayer for URL http://www.bbc.co.uk/iplayer/live/bbcone
[plugin.bbciplayer][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
Traceback (most recent call last):
File "/usr/local/bin/streamlink", line 11, in <module>
load_entry_point('streamlink==1.2.0+12.g1fb9391', 'console_scripts', 'streamlink')()
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink_cli/main.py", line 1038, in main
handle_url()
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink_cli/main.py", line 578, in handle_url
streams = fetch_streams(plugin)
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink_cli/main.py", line 458, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink/plugin/plugin.py", line 323, in streams
ostreams = list(ostreams)
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink/plugins/bbciplayer.py", line 225, in _get_streams
if not self.login(self.url):
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink/plugins/bbciplayer.py", line 199, in login
http_nonce = self._extract_nonce(session_res)
File "/usr/local/lib/python2.7/dist-packages/streamlink-1.2.0+12.g1fb9391-py2.7.egg/streamlink/plugins/bbciplayer.py", line 112, in _extract_nonce
final_url = urlparse(last_redirect_query['goto'])
KeyError: 'goto'
The attached diff for bbciplayer.py seems to fix it. I'm not suggesting it's the ideal solution, but it does work for me.
[bbciplayer.py.diff.txt](https://github.com/streamlink/streamlink/files/3569528/bbciplayer.py.diff.txt)
Comment edited to update supplied diff with minor improvements.
Thanks! The patch seems to have fix bbciplayer.py
My distro (UbuntuStusio 18.04 LTS) has Streamlink 1.1.1 which exhibits the same problem, starting last week. I tried the patch, but it doesn't seem to work for me.
```
streamlink www.bbc.co.uk/iplayer/live/bbcnews 540p --bbciplayer-username xxxxxxxx --bbciplayer-password xxxxxxxx
[cli][info] Found matching plugin bbciplayer for URL www.bbc.co.uk/iplayer/live/bbcnews
[plugin.bbciplayer][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
Traceback (most recent call last):
File "/usr/bin/streamlink", line 11, in <module>
load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')()
File "/usr/share/streamlink/streamlink_cli/main.py", line 1033, in main
handle_url()
File "/usr/share/streamlink/streamlink_cli/main.py", line 577, in handle_url
streams = fetch_streams(plugin)
File "/usr/share/streamlink/streamlink_cli/main.py", line 457, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "/usr/lib/python3/dist-packages/streamlink/plugin/plugin.py", line 323, in streams
ostreams = list(ostreams)
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 234, in _get_streams
if not self.login(self.url):
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 208, in login
http_nonce = self._extract_nonce(session_res)
File "/usr/lib/python3/dist-packages/streamlink/plugins/bbciplayer.py", line 116, in _extract_nonce
final_url = urlparse(last_redirect_query['goto'])
KeyError: 'goto'
```
I would say uninstall your Streamlink 1.1.1, and then install the latest Streamlink 1.2.0, using git clone to get the 1.2.0 version, then using git pull to get the latest and greatest from time to time.
I hope the bbciplayer.py patch will be added a.s.a.p., since many could get dangerous withdrawal if they can't watch their BBC iPlayer.
The patch worked for me, using Streamlink 1.2.0 (using git clone, then installing 'python setup.py install').
> Sorry if stupid question - how do I apply this patch in Windows?
You could get a windows patch binary, from here for example:
http://gnuwin32.sourceforge.net/packages/patch.htm
It's probably just as quick to open bbciplayer.py in notepad and then manually change the _exrtract_nonce method to look like below:
```
def _extract_nonce(cls, http_result):
"""
Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it.
We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests.
:param http_result: HTTP response from the bbc session endpoint.
:type http_result: requests.Response
:return: nonce to "sign" url requests with
:rtype: string
"""
# Extract the redirect URL from the last call
last_redirect_url = http_result.history[-1].headers['Location']
# Extract the nonce
nonce = re.match(r'.*nonce=(.*?)&.*', last_redirect_url)
# Return the nonce we can use for future queries
return nonce.group(1)
``` | 2019-09-05T09:15:47 |
streamlink/streamlink | 2,641 | streamlink__streamlink-2641 | [
"2636"
] | 949a2223a864bebdf1b2ec32bedef4f4577aeeea | diff --git a/src/streamlink/plugins/wasd.py b/src/streamlink/plugins/wasd.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/wasd.py
@@ -0,0 +1,87 @@
+import logging
+import re
+
+from streamlink.exceptions import PluginError
+from streamlink.plugin import Plugin
+from streamlink.stream import HLSStream
+from streamlink.plugin.api import validate
+
+log = logging.getLogger(__name__)
+
+
+class WASD(Plugin):
+ _url_re = re.compile(r'https?://(?:www\.)?wasd\.tv/channel/(?P<channel_id>\d+)(?:/videos/(?P<video_id>\d+))?')
+ _media_schema = validate.Schema({
+ 'user_id': int,
+ 'media_container_streams': [{
+ 'stream_status': validate.text,
+ 'stream_online_status': validate.text,
+ 'user_id': int,
+ 'stream_media': [{
+ 'media_id': int,
+ 'media_meta': {
+ 'media_url': validate.any(validate.text, None),
+ 'media_archive_url': validate.any(validate.text, None),
+ },
+ 'media_status': validate.any('STOPPED', 'RUNNING'),
+ 'media_type': 'HLS',
+ 'user_id': int,
+ }]
+ }],
+ })
+ _api_schema = validate.Schema({
+ 'result':
+ validate.any(
+ _media_schema,
+ validate.all(list,
+ validate.get(0),
+ _media_schema),
+ [],
+ ),
+ }, validate.get('result'))
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ def _get_streams(self):
+ m = self._url_re.match(self.url)
+ video_id = m.group('video_id')
+ channel_id = m.group('channel_id')
+
+ self.session.http.post('https://wasd.tv/api/auth/anon-token')
+
+ if video_id:
+ res = self.session.http.get('https://wasd.tv/api/media-containers/{0}'.format(video_id))
+ else:
+ res = self.session.http.get(
+ 'https://wasd.tv/api/media-containers',
+ params={
+ 'media_container_status': 'RUNNING',
+ 'limit': '1',
+ 'offset': '0',
+ 'channel_id': channel_id,
+ 'media_container_type': 'SINGLE,COOP',
+ }
+ )
+
+ json_res = self.session.http.json(res, schema=self._api_schema)
+ log.trace('{0!r}'.format(json_res))
+ if not json_res:
+ raise PluginError('No data returned from URL={0}'.format(res.url))
+
+ for stream in json_res['media_container_streams']:
+ if stream['user_id'] == json_res['user_id']:
+ log.debug('stream_status: {0}, stream_online_status: {1}'.format(
+ stream['stream_status'], stream['stream_online_status']))
+ for stream in stream['stream_media']:
+ if stream['media_status'] == 'STOPPED':
+ hls_url = stream['media_meta']['media_archive_url']
+ elif stream['media_status'] == 'RUNNING':
+ hls_url = stream['media_meta']['media_url']
+
+ for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
+ yield s
+
+
+__plugin__ = WASD
| diff --git a/tests/plugins/test_wasd.py b/tests/plugins/test_wasd.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_wasd.py
@@ -0,0 +1,20 @@
+import unittest
+
+from streamlink.plugins.wasd import WASD
+
+
+class TestPluginWasd(unittest.TestCase):
+ def test_can_handle_url(self):
+ should_match = [
+ 'https://wasd.tv/channel/12345',
+ 'https://wasd.tv/channel/12345/videos/67890'
+ ]
+ for url in should_match:
+ self.assertTrue(WASD.can_handle_url(url), url)
+
+ def test_can_handle_url_negative(self):
+ should_not_match = [
+ 'https://example.com/index.html',
+ ]
+ for url in should_not_match:
+ self.assertFalse(WASD.can_handle_url(url), url)
| Support for wasd.tv
There is 2 type of links. For example:
https://wasd.tv/channel/86692/videos/269793
https://wasd.tv/channel/86692
Both of them can be live stream or replay of past stream.
What I will say next is not confirmed by any documentation or anything its just how I think this website working.
For example user call streamlink for URL https://wasd.tv/channel/86692
Then we request
https://wasd.tv/api/media-containers?media_container_status=RUNNING&limit=1&offset=0&channel_id=86692&media_container_type=SINGLE,COOP
Response is in JSON format.
*I replaced `media_container_status=STOPPED,RUNNING` to just `RUNNING`. I think if user calls streamlink without /videos/ part in URL he wants live stream. Not past record.
If there is no live stream then response will be `{"result":[]}`
From response we need `json["result"][0]["user_id"]`. For example this channel's `user_id=179599`
Then we look into array `json["result"][0]["media_container_streams"]` and search for element where `json["result"][0]["media_container_streams"][i]["user_id"]` is equals to channel's `user_id=179599`
Then inside that element of array we get another element `json["result"][0]["media_container_streams"][i]["stream_media"]` which has different streams with different quality. For example:
`json["result"][0]["media_container_streams"][0]["stream_media"][0]["media_type"]="HLS"`
`json["result"][0]["media_container_streams"][0]["stream_media"][0]["media_status"]="RUNNING"`
`json["result"][0]["media_container_streams"][0]["stream_media"][0]["media_meta"]["media_current_resolution"]="1280x720"`
`json["result"][0]["media_container_streams"][0]["stream_media"][0]["media_meta"]["media_url"]="https://cdn.wasd.tv/live/179599/index.m3u8"`
Now if user call streamlink for URL https://wasd.tv/channel/86692/videos/269793
We request https://wasd.tv/api/media-containers/269793
And its basically same response and we need to do same job here.
If this is live stream then in `json["result"][0]["media_container_streams"][0]["stream_media"]` array will be element with `media_status="RUNNING"`
If this is replay of past stream then in `json["result"][0]["media_container_streams"][0]["stream_media"]` array will be element with `media_status="STOPPED"`
And instead of `media_url` we need to get `media_archive_url` which will be `.m3u8` file.
I have checked other plugins code and its too hard for me to make it myself.
I hope somebody will be able to do it with results of my "investigation".
| I attempted to do it myself and it was easier than I expected until I got to HLS part.
This is my firs experience with streamlink and third time using python. And I have no idea how HLS works.
WASD has array of resolutions in its JSON files but I can't find stream with more that one resolution to select. Looks like they not implemented that yet.
So I just give streamlink first HLS URL that I find (there is only one at the moment) and it works. And even detects resolution using some HLS voodoo magic.
So it works, but I don't know if I did everything correctly.
Both live streams and records works. | 2019-09-30T17:13:32 |
streamlink/streamlink | 2,643 | streamlink__streamlink-2643 | [
"2555"
] | 6ac9ee0fe70a66551e7a551d8bb0ac6d7f2908db | diff --git a/src/streamlink/plugins/itvplayer.py b/src/streamlink/plugins/itvplayer.py
--- a/src/streamlink/plugins/itvplayer.py
+++ b/src/streamlink/plugins/itvplayer.py
@@ -6,13 +6,14 @@
from streamlink.plugin import Plugin
from streamlink.plugin.api import useragents, validate
from streamlink.plugin.api.utils import itertags
-from streamlink.stream import HLSStream
+from streamlink.stream import HLSStream, RTMPStream
log = logging.getLogger(__name__)
class ITVPlayer(Plugin):
_url_re = re.compile(r"https?://(?:www.)?itv.com/hub/(?P<stream>.+)")
+ swf_url = "https://mediaplayer.itv.com/2.19.5%2Bbuild.a23aa62b1e/ITVMediaPlayer.swf"
_video_info_schema = validate.Schema({
"StatusCode": 200,
"AdditionalInfo": {
@@ -35,8 +36,7 @@ class ITVPlayer(Plugin):
@classmethod
def can_handle_url(cls, url):
- match = cls._url_re.match(url)
- return match is not None
+ return cls._url_re.match(url) is not None
@property
def device_info(self):
@@ -54,18 +54,11 @@ def video_info(self):
if div.attributes.get("id") == "video":
return div.attributes
- def _get_streams(self):
- """
- Find all the streams for the ITV url
- :return: Mapping of quality to stream
- """
- self.session.http.headers.update({"User-Agent": useragents.FIREFOX})
+ def _get_html5_streams(self, video_info_url):
video_info = self.video_info()
- video_info_url = video_info.get("data-html5-playlist") or video_info.get("data-video-id")
-
res = self.session.http.post(video_info_url,
- data=json.dumps(self.device_info),
- headers={"hmac": video_info.get("data-video-hmac")})
+ data=json.dumps(self.device_info),
+ headers={"hmac": video_info.get("data-video-hmac")})
data = self.session.http.json(res, schema=self._video_info_schema)
log.debug("Video ID info response: {0}".format(data))
@@ -78,6 +71,31 @@ def _get_streams(self):
for s in HLSStream.parse_variant_playlist(self.session, url, name_fmt=name_fmt).items():
yield s
+ def _get_rtmp_streams(self, video_info_url):
+ log.debug("XML data path: {0}".format(video_info_url))
+ res = self.session.http.get(video_info_url)
+ playlist = self.session.http.xml(res, ignore_ns=True)
+ mediafiles = playlist.find(".//Playlist/VideoEntries/Video/MediaFiles")
+ playpath = mediafiles.find("./MediaFile/URL")
+ return {"live": RTMPStream(self.session, {"rtmp": mediafiles.attrib.get("base"),
+ "playpath": playpath.text,
+ "live": True,
+ "swfVfy": self.swf_url
+ })}
+
+ def _get_streams(self):
+ """
+ Find all the streams for the ITV url
+ :return: Mapping of quality to stream
+ """
+ self.session.http.headers.update({"User-Agent": useragents.FIREFOX})
+ stream = self._url_re.match(self.url).group("stream")
+ video_info = self.video_info()
+ video_info_url = video_info.get("data-video-id" if stream.lower() in ("itv", "itv4") else "data-html5-playlist")
+ if video_info_url.endswith(".xml"):
+ return self._get_rtmp_streams(video_info_url)
+ else:
+ return self._get_html5_streams(video_info_url)
__plugin__ = ITVPlayer
| ITV Player unable to open URL
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
ITV Player/Hub for the main ITV channel do not open and give an error message.
### Reproduction steps / Explicit stream URLs to test
Type "streamlink itv.com/hub/itv".
Other ITV Hub URL's such as hub/itv2 or hub/citv continue to work.
### Log output
[cli][info] Found matching plugin itvplayer for URL itv.com/hub/itv
error: Unable to open URL: http://cdn.dar.itv.com/private/aHR0cDovL2NzbS1lLnBsYXkuZGFyLml0di5jb20vY3NtL2V4dGxpdmUvMjQ3MTYyMTUubTN1OD95by5hYz10cnVlJnlvLmFkPWZhbHNlJnBtPWZyZWUmcmFuZG9tPTU2OTk0ODU2ODc0ODA1NzE0MjAmYXJlYT1pdHZwbGF5ZXIuc2ltdWxjYXN0JnNvdXJjZT1zaW11bGNhc3QmaGRldmlkPXgmc2l6ZT1wYXR0ZXJuJnN1cGVydGFnPWRmbHQsc2ltJnVzPWFubyZzaXRlPWl0diZvc3Zlcj0xMCZjaGFuYnJhbmQ9aXR2MSZvcz13aW5kb3dzJmhtb2Q9NjYmcHY9YnJvd3Nlci40LjEmcGxheWVyPWh0bWw1LmRlc2t0b3AmZG09bmxpJmhtYW49Y2hyb21lJnRkdXI9MjE2MDAmdHBhcnRzPTEmYXJwPXgmZGVmYXVsdD1EZWZhdWx0UGF0dGVybiZwbGlzdD1zaW1hZHJlcGxhY2VtZW50JnBsZmNpZD1zaW1hZHJlcGxhY2VtZW50/endpoint?hdnea=st=1563543051~exp=1563564651~acl=/*~data=nohubplus~hmac=0ebaf6d4f22f101378a6c7ed3903c1999f6b28efd29ee05763e5ec7bf0d27896&yo.channel=24716215 (404 Client Error: for url: http://csm-e.play.dar.itv.com/csm/extlive/24716215.m3u8?yo.ac=true&yo.ad=false&pm=free&random=5699485687480571420&area=itvplayer.simulcast&source=simulcast&hdevid=x&size=pattern&supertag=dflt,sim&us=ano&site=itv&osver=10&chanbrand=itv1&os=windows&hmod=66&pv=browser.4.1&player=html5.desktop&dm=nli&hman=chrome&tdur=21600&tparts=1&arp=x&default=DefaultPattern&plist=simadreplacement&plfcid=simadreplacement)
### Additional comments, screenshots, etc.
I have noticed the site plays a ITV Hub promo when starting a livestream on the website itself before loading that stream. This does not occur for the other channels.
| Confirmed. I get the same error, will take a look a bit later.
if I made a comment here it was in my error.
I have nothing to comment on this issue.
Is there anything to differentiate getting the ad roll m3u8 and the livestream? I'd like to fix this but all I can think of doing is excluding elements in the playlist array (line 75+ of the plugin). I'm replying to ask for more information about the problem than I've been able to ascertain by myself.
Seems like only the flash stream is supported for ITV1 at the moment...
itv.com/hub/itv does point to the flash stream? it must be possible to skip over that segment of the playlist but i am unsure how to implement this. | 2019-10-02T21:07:30 |
|
streamlink/streamlink | 2,648 | streamlink__streamlink-2648 | [
"2476"
] | 2d2157954dd8426863eaa986bf4a89ccfbc3ca42 | diff --git a/src/streamlink/plugins/bloomberg.py b/src/streamlink/plugins/bloomberg.py
--- a/src/streamlink/plugins/bloomberg.py
+++ b/src/streamlink/plugins/bloomberg.py
@@ -1,11 +1,14 @@
-from functools import partial
+import logging
import re
+from functools import partial
from streamlink.plugin import Plugin
-from streamlink.plugin.api import validate
+from streamlink.plugin.api import validate, useragents
from streamlink.stream import HDSStream, HLSStream, HTTPStream
from streamlink.utils import parse_json, update_scheme
+log = logging.getLogger(__name__)
+
class Bloomberg(Plugin):
VOD_API_URL = 'https://www.bloomberg.com/api/embed?id={0}'
@@ -21,23 +24,26 @@ class Bloomberg(Plugin):
}
_url_re = re.compile(r'''
- https?://www\.bloomberg\.com/(
- news/videos/[^/]+/[^/]+ |
- (?P<channel>live/(?:stream|emea|asia_stream|europe|us|asia)|audio)/?
+ https?://(?:www\.)?bloomberg\.com/
+ (?:
+ news/videos/[^/]+/[^/]+|
+ live/(?P<channel>.+)/?
)
''', re.VERBOSE)
_live_player_re = re.compile(r'{APP_BUNDLE:"(?P<live_player_url>.+?/app.js)"')
_js_to_json_re = partial(re.compile(r'(\w+):(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2')
_video_id_re = re.compile(r'data-bmmr-id=\\"(?P<video_id>.+?)\\"')
_mp4_bitrate_re = re.compile(r'.*_(?P<bitrate>[0-9]+)\.mp4')
+ _preload_state_re = re.compile(r'window.__PRELOADED_STATE__\s*=\s*({.*});', re.DOTALL)
+ _live_stream_info_re = re.compile(r'12:.*t.exports=({.*})},{}],13:', re.DOTALL)
_live_streams_schema = validate.Schema(
validate.transform(_js_to_json_re),
validate.transform(lambda x: x.replace(':.', ':0.')),
validate.transform(parse_json),
- validate.Schema(
- {
- 'cdns': validate.all(
+ validate.Schema({
+ validate.text: {
+ validate.optional('cdns'): validate.all(
[
validate.Schema(
{
@@ -54,11 +60,21 @@ class Bloomberg(Plugin):
],
validate.transform(lambda x: [i for y in x for i in y])
)
- },
- validate.get('cdns')
+ }
+ },
)
)
+ _channel_list_schema = validate.Schema(
+ validate.transform(parse_json),
+ {"live": {"channels": {"byChannelId": {
+ validate.text: validate.all({"liveId": validate.text}, validate.get("liveId"))
+ }}}},
+ validate.get("live"),
+ validate.get("channels"),
+ validate.get("byChannelId"),
+ )
+
_vod_api_schema = validate.Schema(
{
'secureStreams': validate.all([
@@ -87,23 +103,39 @@ def _get_live_streams(self):
match = self._url_re.match(self.url)
channel = match.group('channel')
- # Retrieve live player URL
- res = self.session.http.get(self.PLAYER_URL)
- match = self._live_player_re.search(res.text)
- if match is None:
- return []
- live_player_url = update_scheme(self.url, match.group('live_player_url'))
-
- # Extract streams from the live player page
- res = self.session.http.get(live_player_url)
- stream_datas = re.findall(r'{0}(?:_MINI)?:({{.+?}}]}}]}})'.format(self.CHANNEL_MAP[channel]), res.text)
- streams = []
- for s in stream_datas:
- for u in self._live_streams_schema.validate(s):
- if u not in streams:
- streams.append(u)
-
- return streams
+ res = self.session.http.get(self.url, headers={
+ "authority": "www.bloomberg.com",
+ "upgrade-insecure-requests": "1",
+ "dnt": "1",
+ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"
+ })
+ if "Are you a robot?" in res.text:
+ log.error("Are you a robot?")
+ match = self._preload_state_re.search(res.text)
+ if match:
+ live_ids = self._channel_list_schema.validate(match.group(1))
+ live_id = live_ids.get(channel)
+ if live_id:
+ log.debug("Found liveId = {0}".format(live_id))
+ # Retrieve live player URL
+ res = self.session.http.get(self.PLAYER_URL)
+ match = self._live_player_re.search(res.text)
+ if match is None:
+ return []
+ live_player_url = update_scheme(self.url, match.group('live_player_url'))
+
+ # Extract streams from the live player page
+ log.debug("Player URL: {0}".format(live_player_url))
+ res = self.session.http.get(live_player_url)
+ match = self._live_stream_info_re.search(res.text)
+ if match:
+ stream_info = self._live_streams_schema.validate(match.group(1))
+ data = stream_info.get(live_id, {})
+ return data.get('cdns', [])
+ else:
+ log.error("Could not find liveId for channel '{0}'".format(channel))
+
+ return []
def _get_vod_streams(self):
# Retrieve URL page and search for video ID
@@ -118,6 +150,7 @@ def _get_vod_streams(self):
return streams
def _get_streams(self):
+ self.session.http.headers.update({"User-Agent": useragents.CHROME})
if '/news/videos/' in self.url:
# VOD
streams = self._get_vod_streams()
@@ -126,6 +159,7 @@ def _get_streams(self):
streams = self._get_live_streams()
for video_url in streams:
+ log.debug("Found stream: {0}".format(video_url))
if '.f4m' in video_url:
for stream in HDSStream.parse_manifest(self.session, video_url).items():
yield stream
| Bloomberg plugin stopped working
## Plugin Issue
- [x] This is a plugin issue and I have read the contribution guidelines.
### Description
Bloomberg plugin stopped working May 22. Now it displays "Failed to parse playlist: Missing #EXTM3U header" error message.
### Reproduction steps / Explicit stream URLs to test
streamlink -l debug https://www.bloomberg.com/live/us
### Log output
[cli][info] streamlink is running as root! Be careful!
[cli][debug] OS: Linux-4.9.0-9-amd64-x86_64-with-debian-9.9
[cli][debug] Python: 2.7.13
[cli][debug] Streamlink: 1.1.1
[cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin bloomberg for URL https://www.bloomberg.com/live/us
[utils.l10n][debug] Language code: en_US
error: Failed to parse playlist: Missing #EXTM3U header
| I can reproduce this. My browser is requesting https://d1g4mbj10o50ni.cloudfront.net/btv/desktop/us_live.m3u8 from https://www.bloomberg.com/live/us which still works.
It would be useful to be able to get _more_ debugging information out of the plugin - what is it trying to download, what playlist does it think it's getting that doesn't have #EXTM3U
Update: pretty sure this is triggering an "are you a robot" check
```
$ streamlink -l debug https://www.bloomberg.com/live/us
[cli][debug] OS: Linux-5.0.0-13-generic-x86_64-with-Ubuntu-19.04-disco
[cli][debug] Python: 3.7.3
[cli][debug] Streamlink: 1.1.1+27.gad0bee8.dirty
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.53.0)
[cli][info] Found matching plugin bloomberg for URL https://www.bloomberg.com/live/us
[plugin.bloomberg][debug] live_player_url is https://cdn.gotraffic.net/projector/v0.11.147/app.js
[plugin.bloomberg][debug] parsing m3u8 url at https://www.bloomberg.com/media-manifest/streams/phoenix-us.m3u8
[utils.l10n][debug] Language code: en_AU
[stream.hls_playlist][debug] First line of playlist was <!doctype html>
error: Failed to parse playlist: Missing #EXTM3U header
```
whereas if we chose https://liveproduseast.global.ssl.fastly.net/btv/desktop/us_live.m3u8 (second matching URL) I think it'd work.
This can probably be fixed by adding a User-Agent HTTP header to the HTTP requests. I haven't tested it though...
https://github.com/streamlink/streamlink/blob/1.1.1/src/streamlink/plugins/bloomberg.py#L91-L98
https://github.com/streamlink/streamlink/blob/1.1.1/src/streamlink/plugins/bloomberg.py#L110-L117
Example here:
https://github.com/streamlink/streamlink/blob/1.1.1/src/streamlink/plugins/welt.py#L74-L75
You don't need to add more debug logging, especially log calls which include HTTP response data, as you can simply use python debug tools to see what exactly is going on in detail while fixing/developing a plugin. Including response data can lead to other issues or could potentially be abused.
I understand the bit about not including response data, but I think including *some* debug logging is OK - I'm not using print(), it's only activated when -l debug is specified. The other thing is that the plugin finds multiple matching URLs but bails out after trying only one - perhaps a better behaviour would be to failover to another URL?
`self.session.http.headers.update({"User-Agent": useragents.CHROME})` at the start of _get_live_streams seems to work, but I can't work out why I can't get an `__init__(self)` method to work.
I added manually definition of user agent in beginning of _get_live_streams and during two days Bloomberg plugin works well. | 2019-10-03T23:57:30 |
|
streamlink/streamlink | 2,653 | streamlink__streamlink-2653 | [
"1825"
] | d78efc47e7d7de201372fe8481cf2f36236a4dae | diff --git a/src/streamlink/plugins/albavision.py b/src/streamlink/plugins/albavision.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/albavision.py
@@ -0,0 +1,117 @@
+"""
+Support for the live streams on Albavision sites
+ - http://www.tvc.com.ec
+ - http://www.rts.com.ec
+ - https://www.elnueve.com.ar
+"""
+import logging
+import re
+import time
+
+from streamlink import PluginError
+from streamlink.compat import quote, urlencode
+from streamlink.plugin import Plugin
+from streamlink.plugin.api.utils import itertags
+from streamlink.stream import HLSStream
+from streamlink.utils import update_scheme
+
+log = logging.getLogger(__name__)
+
+
+class Albavision(Plugin):
+ _url_re = re.compile(r"https?://(?:www\.)?(tvc.com.ec|rts.com.ec|elnueve.com.ar)/en-?vivo")
+ _token_input_re = re.compile(r"Math.floor\(Date.now\(\) / 3600000\),'([a-f0-9OK]+)'")
+ _live_url_re = re.compile(r"LIVE_URL = '(.*?)';")
+ _playlist_re = re.compile(r"file:\s*'(http.*m3u8)'")
+ _token_url_re = re.compile(r"https://.*/token/.*?\?rsk=")
+
+ _channel_urls = {
+ 'Quito': 'http://d3aacg6baj4jn0.cloudfront.net/reproductor_rts_o_quito.html?iut=',
+ 'Guayaquil': 'http://d2a6tcnofawcbm.cloudfront.net/player_rts.html?iut=',
+ 'Canal5': 'http://dxejh4fchgs18.cloudfront.net/player_televicentro.html?iut='
+ }
+
+ def __init__(self, url):
+ super(Albavision, self).__init__(url)
+ self._page = None
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ @property
+ def page(self):
+ if not self._page:
+ self._page = self.session.http.get(self.url)
+ return self._page
+
+ def _get_token_url(self):
+ token = self._get_live_url_token()
+ if token:
+ m = self._token_url_re.search(self.page.text)
+ token_url = m and m.group(0)
+ if token_url:
+ log.debug("token_url={0}{1}".format(token_url, token))
+ return token_url + token
+ else:
+ log.error("Could not find site token")
+
+ @staticmethod
+ def transform_token(token_in, date):
+ token_out = list(token_in)
+ offset = len(token_in)
+ for i in range(offset - 1, -1, -1):
+ p = (i * date) % offset
+ # swap chars at p and i
+ token_out[i], token_out[p] = token_out[p], token_out[i]
+ token_out = ''.join(token_out)
+ if token_out.endswith("OK"):
+ return token_out[:-2] # return token without OK suffix
+ else:
+ log.error("Invalid site token: {0} => {1}".format(token_in, token_out))
+
+ def _get_live_url_token(self):
+ m = self._token_input_re.search(self.page.text)
+ if m:
+ date = int(time.time()//3600)
+ return self.transform_token(m.group(1), date) or self.transform_token(m.group(1), date - 1)
+
+ def _get_token(self):
+ token_url = self._get_token_url()
+ if token_url:
+ res = self.session.http.get(token_url)
+ data = self.session.http.json(res)
+ if data['success']:
+ return data['token']
+
+ def _get_streams(self):
+ m = self._live_url_re.search(self.page.text)
+ playlist_url = m and update_scheme(self.url, m.group(1))
+ player_url = self.url
+ token = self._get_token()
+
+ if playlist_url:
+ log.debug("Found playlist URL in the page")
+ else:
+ live_channel = None
+ for div in itertags(self.page.text, "div"):
+ if div.attributes.get("id") == "botonLive":
+ live_channel = div.attributes.get("data-canal")
+
+ if live_channel:
+ log.debug("Live channel: {0}".format(live_channel))
+ player_url = self._channel_urls[live_channel]+quote(token)
+ page = self.session.http.get(player_url, raise_for_status=False)
+ if "block access from your country." in page.text:
+ raise PluginError("Content is geo-locked")
+ m = self._playlist_re.search(page.text)
+ playlist_url = m and update_scheme(self.url, m.group(1))
+ else:
+ log.error("Could not find the live channel")
+
+ if playlist_url:
+ stream_url = "{0}?{1}".format(playlist_url, urlencode({"iut": token}))
+ return HLSStream.parse_variant_playlist(self.session, stream_url, headers={"referer": player_url})
+
+
+__plugin__ = Albavision
| diff --git a/tests/plugins/test_albavision.py b/tests/plugins/test_albavision.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_albavision.py
@@ -0,0 +1,29 @@
+import unittest
+
+import pytest
+
+from streamlink.plugins.albavision import Albavision
+
+
+class TestPluginAlbavision:
+ valid_urls = [
+ ("https://www.elnueve.com.ar/en-vivo",),
+ ("http://www.rts.com.ec/envivo",),
+ ("https://www.tvc.com.ec/envivo",),
+ ]
+ invalid_urls = [
+ ("https://news.now.com/home/local",),
+ ("http://media.now.com.hk/",),
+ ("https://www.youtube.com",)
+ ]
+
+ @pytest.mark.parametrize(["url"], valid_urls)
+ def test_can_handle_url(self, url):
+ assert Albavision.can_handle_url(url), "url should be handled"
+
+ @pytest.mark.parametrize(["url"], invalid_urls)
+ def test_can_handle_url_negative(self, url):
+ assert not Albavision.can_handle_url(url), "url should not be handled"
+
+ def test_transform(self):
+ assert Albavision.transform_token(u'6b425761cc8a86569b1a05a9bf1870c95fca717dOK', 436171) == "6b425761cc8a86569b1a05a9bf1870c95fca717d"
| RTS and TVC
- [ ] This is a bug report.
- [ ] This is a feature request.
- [x] This is a plugin (improvement) request.
- [ ] I have read the contribution guidelines.
I'm requesting a plugin for cloudfront.net
its streamed it serves a generated .m3u8 (for 30ish seconds) along with its 1ish second chunk every second or so
Sites that use this server to stream:
http://www.rts.com.ec/envivo
http://www.tvc.com.ec/envivo
XHR:
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/playlist.m3u8
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3340.ts
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3341.ts
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3342.ts
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3343.ts
These links were captured with IDM:
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/chunklist_b899152.m3u8 (360p)
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/chunklist_b249152.m3u8 (160p)
http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/chunklist_b1073152.m3u8 (480p)
A look at the .m3u8:
```
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=899152,CODECS="avc1.77.31,mp4a.40.2",RESOLUTION=640x360
chunklist_b899152.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=249152,CODECS="avc1.66.21,mp4a.40.2",RESOLUTION=284x160
chunklist_b249152.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1073152,CODECS="avc1.77.32,mp4a.40.2",RESOLUTION=854x480
chunklist_b1073152.m3u8
```
When I tried to download the stream, usually Streamlink says "Error 403", but other times Streamlink says it does not have the plugin.
| You want plugins for http://www.rts.com.ec/envivo and http://www.tvc.com.ec/envivo? Rather than cloudfront, cloudfront is just the CDN they use.
I would like it to work for both sites. But what would happen if would there be more sites that also use cloudfront for their streams? For example these two web pages
http://www.elnueve.com.ar/envivo
http://www.repretel.com/envivo
There are other sites that are part of the same international network (Albavisión) and they use the same server, but have geoblocking.
So, you want a plugin for all the Albavisión sites? :)
I'm interested in RTS and TVC :)
I just set the example other similar streams that are from other countries in case someone could be useful in the future.
I guess nobody has worked on the plugin yet
Streamlink is an open source software project. You and anyone else can work on this. This is a community effort. Simply requesting a plugin (and asking for it again) doesn't mean that it'll be added. | 2019-10-04T23:44:29 |
streamlink/streamlink | 2,654 | streamlink__streamlink-2654 | [
"2620"
] | d78efc47e7d7de201372fe8481cf2f36236a4dae | diff --git a/src/streamlink/plugins/viutv.py b/src/streamlink/plugins/viutv.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/viutv.py
@@ -0,0 +1,46 @@
+import datetime
+import logging
+import random
+import re
+import json
+
+from streamlink.plugin import Plugin
+from streamlink.stream import HLSStream
+
+log = logging.getLogger(__name__)
+
+
+class ViuTV(Plugin):
+ _url_re = re.compile(r"https?://viu\.tv/ch/(\d+)")
+ api_url = "https://api.viu.now.com/p8/2/getLiveURL"
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ @property
+ def device_id(self):
+ return "".join(random.choice("abcdef0123456789") for _ in range(18))
+
+ @property
+ def channel_id(self):
+ return self._url_re.match(self.url).group(1)
+
+ def _get_streams(self):
+ api_res = self.session.http.post(self.api_url,
+ headers={"Content-Type": 'application/json'},
+ data=json.dumps({"callerReferenceNo": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
+ "channelno": self.channel_id.zfill(3),
+ "mode": "prod",
+ "deviceId": self.device_id,
+ "deviceType": "5",
+ "format": "HLS"}))
+ data = self.session.http.json(api_res)
+ if data['responseCode'] == 'SUCCESS':
+ for stream_url in data.get("asset", {}).get("hls", {}).get("adaptive", []):
+ return HLSStream.parse_variant_playlist(self.session, stream_url)
+ else:
+ log.error("Failed to get stream URL: {0}".format(data['responseCode']))
+
+
+__plugin__ = ViuTV
| diff --git a/tests/plugins/test_viutv.py b/tests/plugins/test_viutv.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_viutv.py
@@ -0,0 +1,23 @@
+import unittest
+
+import pytest
+
+from streamlink.plugins.viutv import ViuTV
+
+
+class TestPluginViuTV:
+ valid_urls = [
+ ("https://viu.tv/ch/99",),
+ ]
+ invalid_urls = [
+ ("https://viu.tv/encore/king-maker-ii/king-maker-iie4fuk-hei-baan-hui-ji-on-ji-sun-dang-cheung",),
+ ("https://www.youtube.com",)
+ ]
+
+ @pytest.mark.parametrize(["url"], valid_urls)
+ def test_can_handle_url(self, url):
+ assert ViuTV.can_handle_url(url), "url should be handled"
+
+ @pytest.mark.parametrize(["url"], invalid_urls)
+ def test_can_handle_url_negative(self, url):
+ assert not ViuTV.can_handle_url(url), "url should not be handled"
| ViuTV live
## Plugin Request
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
<!-- Explain the plugin and site as clearly as you can. What is the site about? Who runs it? What content does it provide? What value does it bring to Streamlink? Etc. -->
One of a local television station from Hong Kong which currently accessible via Internet streaming. ViuTV is one of a few disinterested news channel which provide fare perspective reports compared to major aired television in Hong Kong.
### Example stream URLs
<!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. -->
1. https://viu.tv/ch/99
### Additional comments, screenshots, etc.
![chrome_2019-09-07_22-29-31](https://user-images.githubusercontent.com/771955/64476235-071fe400-d1bf-11e9-964e-1807da742eed.png)
ViuTV is also run by Now, so the method for fetching playback should be the same as NowTV
https://github.com/streamlink/streamlink/issues/2592
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| Appears to be geo-locked, I cannot access it :(
> Appears to be geo-locked, I cannot access it :(
Check you email please | 2019-10-05T20:16:07 |
streamlink/streamlink | 2,671 | streamlink__streamlink-2671 | [
"2544"
] | cc32730ea7c9749169df34e2f1a82c1fdb704df4 | diff --git a/src/streamlink/plugins/vlive.py b/src/streamlink/plugins/vlive.py
new file mode 100644
--- /dev/null
+++ b/src/streamlink/plugins/vlive.py
@@ -0,0 +1,55 @@
+import re
+import json
+
+from streamlink.plugin import Plugin, PluginError
+from streamlink.stream import HLSStream
+
+
+class Vlive(Plugin):
+ _url_re = re.compile(r"https?://(?:www.)vlive\.tv/video/(\d+)")
+ _video_status = re.compile(r'oVideoStatus = (.+)<', re.DOTALL)
+ _video_init_url = "https://www.vlive.tv/video/init/view"
+
+ @classmethod
+ def can_handle_url(cls, url):
+ return cls._url_re.match(url) is not None
+
+ @property
+ def video_id(self):
+ return self._url_re.match(self.url).group(1)
+
+ def _get_streams(self):
+ vinit_req = self.session.http.get(self._video_init_url,
+ params=dict(videoSeq=self.video_id),
+ headers=dict(referer=self.url))
+ if vinit_req.status_code != 200:
+ raise PluginError('Could not get video init page (HTTP Status {})'
+ .format(vinit_req.status_code))
+
+ video_status_js = self._video_status.search(vinit_req.text)
+ if not video_status_js:
+ raise PluginError('Could not find video status information!')
+
+ video_status = json.loads(video_status_js.group(1))
+
+ if video_status['viewType'] == 'vod':
+ raise PluginError('VODs are not supported')
+
+ if 'liveStreamInfo' not in video_status:
+ raise PluginError('Stream is offline')
+
+ stream_info = json.loads(video_status['liveStreamInfo'])
+
+ streams = dict()
+ # All "resolutions" have a variant playlist with only one entry, so just combine them
+ for i in stream_info['resolutions']:
+ res_streams = HLSStream.parse_variant_playlist(self.session, i['cdnUrl'])
+ if len(res_streams.values()) > 1:
+ self.logger.warning('More than one stream in variant playlist, using first entry!')
+
+ streams[i['name']] = res_streams.popitem()[1]
+
+ return streams
+
+
+__plugin__ = Vlive
| diff --git a/tests/plugins/test_vlive.py b/tests/plugins/test_vlive.py
new file mode 100644
--- /dev/null
+++ b/tests/plugins/test_vlive.py
@@ -0,0 +1,23 @@
+import unittest
+
+import pytest
+
+from streamlink.plugins.vlive import Vlive
+
+
+class TestPluginVlive:
+ valid_urls = [
+ ("https://www.vlive.tv/video/156824",),
+ ]
+ invalid_urls = [
+ ("https://www.vlive.tv/events/2019vheartbeat?lang=en",),
+ ("https://twitch.tv/",)
+ ]
+
+ @pytest.mark.parametrize(["url"], valid_urls)
+ def test_can_handle_url(self, url):
+ assert Vlive.can_handle_url(url), "url should be handled"
+
+ @pytest.mark.parametrize(["url"], invalid_urls)
+ def test_can_handle_url_negative(self, url):
+ assert not Vlive.can_handle_url(url), "url should not be handled"
| [Plugin Request] Vlive.tv
<!--
Thanks for requesting a plugin!
USE THE TEMPLATE. Otherwise your plugin request may be rejected.
First, see the contribution guidelines and plugin request requirements:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Plugin requests which fall into the categories we will not implement will be closed immediately.
Also check the list of open and closed plugin requests:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+request%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Plugin Request
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements.
### Description
This is a live streaming site.
This site was originally mainly for idols who want to interact with fans, but now it has grown more, many people have registered and broadcast a number of more diverse programs.
<!-- Explain the plugin and site as clearly as you can. What is the site about? Who runs it? What content does it provide? What value does it bring to Streamlink? Etc. -->
### Example stream URLs
<!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. -->
1. https://www.vlive.tv/ (Home page)
2. https://www.vlive.tv/upcoming (Upcoming broadcasts will be show here)
### Additional comments, screenshots, etc.
This site has no live streaming 24/7 so you can visit the homepage and look down, sometimes seeing some people broadcasting there (IMG: https://i.imgur.com/rHBMmli.jpg).
Or visit this page to see upcoming shows: https://www.vlive.tv/upcoming
Hope you can support this page, thanks so much.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| 2019-10-25T12:25:46 |
|
streamlink/streamlink | 2,722 | streamlink__streamlink-2722 | [
"2721"
] | 9253fc5128da0c7fb01375de9c0d051f7f835b61 | diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -374,6 +374,12 @@ class Twitch(Plugin):
help="""
Skip embedded advertisement segments at the beginning or during a stream.
Will cause these segments to be missing from the stream.
+ """
+ ),
+ PluginArgument("disable-reruns",
+ action="store_true",
+ help="""
+ Do not open the stream if the target channel is currently broadcasting a rerun.
"""
))
@@ -697,12 +703,19 @@ def _check_for_host(self):
self.logger.info("{0} is hosting {1}".format(self.channel, host_info["target_login"]))
return host_info["target_login"]
+ def _check_for_rerun(self):
+ return self.api.streams(self.channel_id)["stream"]["stream_type"] == "rerun"
+
def _get_hls_streams(self, stream_type="live"):
self.logger.debug("Getting {0} HLS streams for {1}".format(stream_type, self.channel))
self._authenticate()
self._hosted_chain.append(self.channel)
if stream_type == "live":
+ if self._check_for_rerun() and self.options.get("disable_reruns"):
+ self.logger.info("Reruns were disabled by command line option")
+ return {}
+
hosted_channel = self._check_for_host()
if hosted_channel and self.options.get("disable_hosting"):
self.logger.info("hosting was disabled by command line option")
| Twitch disable reruns
<!--
Thanks for filing a feature request!
USE THE TEMPLATE. Otherwise your feature request may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Open a plugin request if you're requesting a new plugin instead of a new feature.
Also check the list of open and closed feature requests:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22feature+request%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Feature Request
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a feature request and I have read the contribution guidelines.
### Description
<!-- Explain the feature as clearly as you can. What is it, how would you expect it to work, and what value does it bring to Streamlink? -->
There are disabling hosts (--twitch-disable-hosting), can you also add disabling reruns?
### Expected / Actual behavior
<!-- What do you expect to happen with this new feature, and what is happening currently that does not satisfy this need? -->
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| I don't think the reruns are actually public like the hosting is since the host is simply a redirect right? Try running with the debug log on and see if it mentions anything about a rerun like it does for a host. If it doesn't there probably isn't anything we can do.
Nothing about reruns in log. Sad :( | 2019-12-01T23:57:39 |
|
streamlink/streamlink | 2,724 | streamlink__streamlink-2724 | [
"2722"
] | 11370e58bd4f707c34610f7df48d688a02aa39da | diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -96,6 +96,15 @@
},
validate.get("display_name")
)
+_stream_schema = validate.Schema(
+ {
+ "stream": validate.any(None, {
+ "stream_type": validate.any("live", "rerun"),
+ "broadcast_platform": validate.any("live", "rerun")
+ })
+ },
+ validate.get("stream")
+)
_video_schema = validate.Schema(
{
"chunks": {
@@ -450,7 +459,7 @@ def __init__(self, url):
self.video_type = self.params["video"][0]
self.video_id = self.params["video"][1:]
except IndexError:
- self.logger.debug("Invalid video param: {0}", self.params["video"])
+ log.debug("Invalid video param: {0}".format(self.params["video"]))
self._channel = self.params.get("channel")
elif self.subdomain == "clips":
# clip share URL
@@ -520,27 +529,25 @@ def _authenticate(self):
cookies = self.options.get("cookie")
if oauth_token:
- self.logger.info("Attempting to authenticate using OAuth token")
+ log.info("Attempting to authenticate using OAuth token")
self.api.oauth_token = oauth_token
user = self.api.user(schema=_user_schema)
if user:
- self.logger.info("Successfully logged in as {0}", user)
+ log.info("Successfully logged in as {0}".format(user))
else:
- self.logger.error("Failed to authenticate, the access token "
- "is invalid or missing required scope")
+ log.error("Failed to authenticate, the access token is invalid or missing required scope")
elif cookies:
- self.logger.info("Attempting to authenticate using cookies")
+ log.info("Attempting to authenticate using cookies")
self.api.add_cookies(cookies)
self.api.oauth_token = self.api.token(schema=_viewer_token_schema)
login = self.api.viewer_info(schema=_viewer_info_schema)
if login:
- self.logger.info("Successfully logged in as {0}", login)
+ log.info("Successfully logged in as {0}".format(login))
else:
- self.logger.error("Failed to authenticate, your cookies "
- "may have expired")
+ log.error("Failed to authenticate, your cookies may have expired")
def _create_playlist_streams(self, videos):
start_offset = int(videos.get("start_offset", 0))
@@ -550,9 +557,7 @@ def _create_playlist_streams(self, videos):
for quality, chunks in videos.get("chunks").items():
if not chunks:
if videos.get("restrictions", {}).get(quality) == "chansub":
- self.logger.warning("The quality '{0}' is not available "
- "since it requires a subscription.",
- quality)
+ log.warning("The quality '{0}' is not available since it requires a subscription.".format(quality))
continue
# Rename 'live' to 'source'
@@ -561,8 +566,7 @@ def _create_playlist_streams(self, videos):
chunks_filtered = list(filter(lambda c: c["url"], chunks))
if len(chunks) != len(chunks_filtered):
- self.logger.warning("The video '{0}' contains invalid chunks. "
- "There will be missing data.", quality)
+ log.warning("The video '{0}' contains invalid chunks. There will be missing data.".format(quality))
chunks = chunks_filtered
chunks_duration = sum(c.get("length") for c in chunks)
@@ -583,8 +587,7 @@ def _create_playlist_streams(self, videos):
start_offset,
stop_offset)
except StreamError as err:
- self.logger.error("Error while creating video '{0}': {1}",
- quality, err)
+ log.error("Error while creating video '{0}': {1}".format(quality, err))
continue
streams[quality] = stream
@@ -650,7 +653,7 @@ def _create_video_clip(self, chunks, start_offset, stop_offset):
tags=playlist_tags, duration=playlist_duration)
def _get_video_streams(self):
- self.logger.debug("Getting video steams for {0} (type={1})".format(self.video_id, self.video_type))
+ log.debug("Getting video steams for {0} (type={1})".format(self.video_id, self.video_type))
self._authenticate()
if self.video_type == "b":
@@ -700,29 +703,31 @@ def _access_token(self, type="live"):
def _check_for_host(self):
host_info = self.api.hosted_channel(include_logins=1, host=self.channel_id).json()["hosts"][0]
if "target_login" in host_info and host_info["target_login"].lower() != self.channel.lower():
- self.logger.info("{0} is hosting {1}".format(self.channel, host_info["target_login"]))
+ log.info("{0} is hosting {1}".format(self.channel, host_info["target_login"]))
return host_info["target_login"]
def _check_for_rerun(self):
- return self.api.streams(self.channel_id)["stream"]["stream_type"] == "rerun"
+ stream = self.api.streams(self.channel_id, schema=_stream_schema)
+
+ return stream and (stream["stream_type"] == "rerun" or stream["broadcast_platform"] == "rerun")
def _get_hls_streams(self, stream_type="live"):
- self.logger.debug("Getting {0} HLS streams for {1}".format(stream_type, self.channel))
+ log.debug("Getting {0} HLS streams for {1}".format(stream_type, self.channel))
self._authenticate()
self._hosted_chain.append(self.channel)
if stream_type == "live":
- if self._check_for_rerun() and self.options.get("disable_reruns"):
- self.logger.info("Reruns were disabled by command line option")
+ if self.options.get("disable_reruns") and self._check_for_rerun():
+ log.info("Reruns were disabled by command line option")
return {}
hosted_channel = self._check_for_host()
if hosted_channel and self.options.get("disable_hosting"):
- self.logger.info("hosting was disabled by command line option")
+ log.info("hosting was disabled by command line option")
elif hosted_channel:
- self.logger.info("switching to {0}", hosted_channel)
+ log.info("switching to {0}".format(hosted_channel))
if hosted_channel in self._hosted_chain:
- self.logger.error(
+ log.error(
u"A loop of hosted channels has been detected, "
"cannot find a playable stream. ({0})".format(
u" -> ".join(self._hosted_chain + [hosted_channel])))
@@ -737,7 +742,7 @@ def _get_hls_streams(self, stream_type="live"):
sig, token = self._access_token(stream_type)
url = self.usher.video(self.video_id, nauthsig=sig, nauth=token)
else:
- self.logger.debug("Unknown HLS stream type: {0}".format(stream_type))
+ log.debug("Unknown HLS stream type: {0}".format(stream_type))
return {}
time_offset = self.params.get("t", 0)
@@ -767,9 +772,7 @@ def _get_hls_streams(self, stream_type="live"):
token = parse_json(token, schema=_token_schema)
for name in token["restricted_bitrates"]:
if name not in streams:
- self.logger.warning("The quality '{0}' is not available "
- "since it requires a subscription.",
- name)
+ log.warning("The quality '{0}' is not available since it requires a subscription.".format(name))
except PluginError:
pass
| diff --git a/tests/plugins/test_twitch.py b/tests/plugins/test_twitch.py
--- a/tests/plugins/test_twitch.py
+++ b/tests/plugins/test_twitch.py
@@ -187,3 +187,88 @@ def test_hls_scte35_in_between(self, mock_logging):
call("Will skip ads beginning with segment 6"),
call("Will stop skipping ads beginning with segment 14")
])
+
+
+@patch("streamlink.plugins.twitch.log")
+class TestTwitchReruns(unittest.TestCase):
+ log_call = call("Reruns were disabled by command line option")
+
+ class StopError(Exception):
+ """Stop when trying to get an access token in _get_hls_streams..."""
+
+ @patch("streamlink.plugins.twitch.Twitch._authenticate", return_value=None)
+ @patch("streamlink.plugins.twitch.Twitch._check_for_host", return_value=None)
+ @patch("streamlink.plugins.twitch.Twitch._access_token", side_effect=StopError())
+ def start(self, *mocked, **params):
+ with requests_mock.Mocker() as mock:
+ mocked_users = mock.get(
+ "https://api.twitch.tv/kraken/users.json?login=foo",
+ json={"users": [{"_id": 1234}]}
+ )
+ mocked_stream = mock.get(
+ "https://api.twitch.tv/kraken/streams/1234.json",
+ json={"stream": None} if params.pop("offline", False) else {"stream": {
+ "stream_type": params.pop("stream_type", "rerun"),
+ "broadcast_platform": params.pop("broadcast_platform", "rerun")
+ }}
+ )
+
+ session = Streamlink()
+ Twitch.bind(session, "tests.plugins.test_twitch")
+ plugin = Twitch("https://www.twitch.tv/foo")
+ plugin.options.set("disable-reruns", params.pop("disable", True))
+ try:
+ streams = plugin.streams()
+ except TestTwitchReruns.StopError:
+ streams = None
+ pass
+
+ return streams, mocked_users, mocked_stream, mocked[0]
+
+ def test_disable_reruns(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(stream_type="rerun", broadcast_platform="rerun")
+ self.assertTrue(api_users.called_once)
+ self.assertTrue(api_stream.called_once)
+ self.assertFalse(access_token.called)
+ self.assertDictEqual(streams, {})
+ self.assertIn(self.log_call, mock_log.info.call_args_list)
+
+ def test_disable_reruns_mixed(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(stream_type="rerun", broadcast_platform="live")
+ self.assertTrue(api_users.called_once)
+ self.assertTrue(api_stream.called_once)
+ self.assertFalse(access_token.called)
+ self.assertDictEqual(streams, {})
+ self.assertIn(self.log_call, mock_log.info.call_args_list)
+
+ def test_disable_reruns_mixed2(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(stream_type="live", broadcast_platform="rerun")
+ self.assertTrue(api_users.called_once)
+ self.assertTrue(api_stream.called_once)
+ self.assertFalse(access_token.called)
+ self.assertDictEqual(streams, {})
+ self.assertIn(self.log_call, mock_log.info.call_args_list)
+
+ def test_disable_reruns_live(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(stream_type="live", broadcast_platform="live")
+ self.assertTrue(api_users.called_once)
+ self.assertTrue(api_stream.called_once)
+ self.assertTrue(access_token.called_once)
+ self.assertIsNone(streams)
+ self.assertNotIn(self.log_call, mock_log.info.call_args_list)
+
+ def test_disable_reruns_offline(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(offline=True)
+ self.assertTrue(api_users.called_once)
+ self.assertTrue(api_stream.called_once)
+ self.assertTrue(access_token.called_once)
+ self.assertIsNone(streams)
+ self.assertNotIn(self.log_call, mock_log.info.call_args_list)
+
+ def test_enable_reruns(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(disable=False)
+ self.assertFalse(api_users.called)
+ self.assertFalse(api_stream.called)
+ self.assertTrue(access_token.called_once)
+ self.assertIsNone(streams)
+ self.assertNotIn(self.log_call, mock_log.info.call_args_list)
| Allow to disable twitch reruns
This adds the option to disable twitch reruns similar to disabling hosted streams.
~I know the check for the `stream_type` could also be directly done in `_get_hls_streams`. If you like that better tell me and I can change it :)~
Edit: I decided to change it. This should have less changes and I think my previous solution broke the tests for the skip-ads option.
Closes #2721
| # [Codecov](https://codecov.io/gh/streamlink/streamlink/pull/2722?src=pr&el=h1) Report
> Merging [#2722](https://codecov.io/gh/streamlink/streamlink/pull/2722?src=pr&el=desc) into [master](https://codecov.io/gh/streamlink/streamlink/commit/9253fc5128da0c7fb01375de9c0d051f7f835b61?src=pr&el=desc) will **decrease** coverage by `0.01%`.
> The diff coverage is `20%`.
```diff
@@ Coverage Diff @@
## master #2722 +/- ##
==========================================
- Coverage 52.47% 52.46% -0.02%
==========================================
Files 246 246
Lines 15431 15436 +5
==========================================
+ Hits 8098 8099 +1
- Misses 7333 7337 +4
```
Thanks @skulblakka, I didn't realize the reruns were flagged by the stream type.
Thank you!
There also a problem occurs when stream is offline
![1](https://user-images.githubusercontent.com/51099894/69998846-55e3dc80-1568-11ea-8c62-2baced39c4df.png)
@skulblakka Do you have time to try and fix this at some point? Otherwise maybe we should revert since this is kind of hard to test. I only know of a few streamers like followgrubby that regularly have reruns. Seems like the items bastimeyer noted might be biting us in the butt a bit here, might be worth adding some tests as well? I didn't think about how poorly patched together the API is when I merged this.
I'm sorry for the mess I caused.
@bastimeyer Like I mentioned I assumed the OP of the issue was talking about reruns made via the Rerun-Feature. That's why I didn't consider "live"-streams that broadcasted a video. Getting streams by type was [removed March 2018](https://discuss.dev.twitch.tv/t/new-twitch-api-deprecating-get-streams-by-type/14554) on Helix (although the field there is only called `type`) and other values than `live` were removed from the documentation. Do you think filtering by `stream_type` is enough or should I also add `broadcast_platform`?
@gravyboat I have to leave for work now but I will try fixing this in the evening (and will also see about some tests).
@skulblakka There is no need to apologize or any reason to stress about it. Your contribution and desire to implement this is appreciated. There's no release currently planned so we're not in a rush, I just wanted to clarify whether you wanted to work on it or if you were going to be too busy to do so and we should back it out. Don't pressure yourself or inconvenience your personal time.
I'll submit a PR with a fix later. Currently adding some tests... No pressure... | 2019-12-03T11:19:44 |
streamlink/streamlink | 2,765 | streamlink__streamlink-2765 | [
"2764"
] | f90d560511523d67c71387eb67bb91fd577ec1bb | diff --git a/src/streamlink_cli/output.py b/src/streamlink_cli/output.py
--- a/src/streamlink_cli/output.py
+++ b/src/streamlink_cli/output.py
@@ -190,7 +190,7 @@ def _create_arguments(self):
if self.player_name == "mpv":
# see https://mpv.io/manual/stable/#property-expansion, allow escaping with \$, respect mpv's $>
self.title = self._mpv_title_escape(self.title)
- extra_args.extend(["--title", self.title])
+ extra_args.append("--title={}".format(self.title))
# potplayer
if self.player_name == "potplayer":
@@ -202,7 +202,7 @@ def _create_arguments(self):
args = self.args.format(filename=filename)
cmd = self.cmd
-
+
# player command
if is_win32:
eargs = maybe_decode(subprocess.list2cmdline(extra_args))
| diff --git a/tests/test_cmdline_title.py b/tests/test_cmdline_title.py
--- a/tests/test_cmdline_title.py
+++ b/tests/test_cmdline_title.py
@@ -26,7 +26,7 @@ def test_open_player_with_default_title_vlc_args(self):
def test_open_player_with_title_mpv(self):
self._test_args(["streamlink", "-p", "/usr/bin/mpv", "--title", "{title}", "http://test.se", "test"],
- ["/usr/bin/mpv", "--title", 'Test Title', "-"])
+ ["/usr/bin/mpv", "--title=Test Title", "-"])
@unittest.skipIf(not is_win32, "test only applicable on Windows")
| Change in mpv options for 2 dashes options breaks it connection to Streamlink
lately mpv changed the way they handle [2 dashes options](https://github.com/mpv-player/mpv/commit/d3cef97ad38fb027262a905bd82e1d3d2549aec7)
```
--- mpv 0.31.1 ---
- change behavior when using legacy option syntax with options that start
with two dashes (``--`` instead of a ``-``). Now, using the recommended
syntax is required for options starting with ``--``, which means an option
value must be strictly passed after a ``=``, instead of as separate
argument. For example, ``--log-file f.txt`` was previously accepted and
behaved like ``--log-file=f.txt``, but now causes an error. Use of legacy
syntax that is still supported now prints a deprecation warning.
```
So now mpv just closes with no errors when used with streamlink as streamlink creates an mpv command with --title "title" instead of --title="title"
```
[15:57] zouhair@box <5402:63> [~] -> :)
┖╴$ streamlink --verbose-player --loglevel debug https://www.twitch.tv/videos/533706108 best
[cli][debug] OS: CYGWIN_NT-10.0-18362-3.1.2-340.x86_64-x86_64-64bit-WindowsPE
[cli][debug] Python: 3.7.4
[cli][debug] Streamlink: 1.3.0
[cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0)
[cli][info] Found matching plugin twitch for URL https://www.twitch.tv/videos/533706108
[plugin.twitch][debug] Getting video HLS streams for gamesdonequick
[utils.l10n][debug] Language code: en_US
[cli][info] Available streams: audio, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)
[cli][info] Opening stream: 1080p60 (hls)
[cli][info] Starting player: /home/zouhair/mpv.exe --cache 2048
[cli.output][debug] Calling: /home/zouhair/mpv.exe --cache 2048 --title https://www.twitch.tv/videos/533706108 https://vod-secure.twitch.tv/7dc8f3a102cc1793f7bc_gamesdonequick_36629634272_1358097847/chunked/index-dvr.m3u8
[15:57] zouhair@box <5403:64> [~] -> :)
┖╴$ echo $?
0
[15:57] zouhair@box <5404:65> [~] -> :)
┖╴$
```
| 2020-01-12T23:18:51 |
|
streamlink/streamlink | 2,780 | streamlink__streamlink-2780 | [
"2779"
] | 48aa67977b1e69730d582a32641ec5cbfe63971d | diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py
--- a/src/streamlink/plugins/twitch.py
+++ b/src/streamlink/plugins/twitch.py
@@ -99,8 +99,11 @@
_stream_schema = validate.Schema(
{
"stream": validate.any(None, {
- "stream_type": validate.any("live", "rerun"),
- "broadcast_platform": validate.any("live", "rerun")
+ "stream_type": validate.text,
+ "broadcast_platform": validate.text,
+ "channel": validate.any(None, {
+ "broadcaster_software": validate.text
+ })
})
},
validate.get("stream")
@@ -709,7 +712,11 @@ def _check_for_host(self):
def _check_for_rerun(self):
stream = self.api.streams(self.channel_id, schema=_stream_schema)
- return stream and (stream["stream_type"] == "rerun" or stream["broadcast_platform"] == "rerun")
+ return stream and (
+ stream["stream_type"] != "live"
+ or stream["broadcast_platform"] == "rerun"
+ or stream["channel"] and stream["channel"]["broadcaster_software"] == "watch_party_rerun"
+ )
def _get_hls_streams(self, stream_type="live"):
log.debug("Getting {0} HLS streams for {1}".format(stream_type, self.channel))
| diff --git a/tests/plugins/test_twitch.py b/tests/plugins/test_twitch.py
--- a/tests/plugins/test_twitch.py
+++ b/tests/plugins/test_twitch.py
@@ -208,8 +208,11 @@ def start(self, *mocked, **params):
mocked_stream = mock.get(
"https://api.twitch.tv/kraken/streams/1234.json",
json={"stream": None} if params.pop("offline", False) else {"stream": {
- "stream_type": params.pop("stream_type", "rerun"),
- "broadcast_platform": params.pop("broadcast_platform", "rerun")
+ "stream_type": params.pop("stream_type", "live"),
+ "broadcast_platform": params.pop("broadcast_platform", "live"),
+ "channel": {
+ "broadcaster_software": params.pop("broadcaster_software", "")
+ }
}}
)
@@ -220,13 +223,21 @@ def start(self, *mocked, **params):
try:
streams = plugin.streams()
except TestTwitchReruns.StopError:
- streams = None
+ streams = True
pass
return streams, mocked_users, mocked_stream, mocked[0]
- def test_disable_reruns(self, mock_log):
- streams, api_users, api_stream, access_token = self.start(stream_type="rerun", broadcast_platform="rerun")
+ def test_disable_reruns_live(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start()
+ self.assertTrue(api_users.called_once)
+ self.assertTrue(api_stream.called_once)
+ self.assertTrue(access_token.called_once)
+ self.assertTrue(streams)
+ self.assertNotIn(self.log_call, mock_log.info.call_args_list)
+
+ def test_disable_reruns_not_live(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(stream_type="rerun")
self.assertTrue(api_users.called_once)
self.assertTrue(api_stream.called_once)
self.assertFalse(access_token.called)
@@ -249,20 +260,20 @@ def test_disable_reruns_mixed2(self, mock_log):
self.assertDictEqual(streams, {})
self.assertIn(self.log_call, mock_log.info.call_args_list)
- def test_disable_reruns_live(self, mock_log):
- streams, api_users, api_stream, access_token = self.start(stream_type="live", broadcast_platform="live")
+ def test_disable_reruns_broadcaster_software(self, mock_log):
+ streams, api_users, api_stream, access_token = self.start(broadcaster_software="watch_party_rerun")
self.assertTrue(api_users.called_once)
self.assertTrue(api_stream.called_once)
self.assertTrue(access_token.called_once)
- self.assertIsNone(streams)
- self.assertNotIn(self.log_call, mock_log.info.call_args_list)
+ self.assertDictEqual(streams, {})
+ self.assertIn(self.log_call, mock_log.info.call_args_list)
def test_disable_reruns_offline(self, mock_log):
streams, api_users, api_stream, access_token = self.start(offline=True)
self.assertTrue(api_users.called_once)
self.assertTrue(api_stream.called_once)
self.assertTrue(access_token.called_once)
- self.assertIsNone(streams)
+ self.assertTrue(streams)
self.assertNotIn(self.log_call, mock_log.info.call_args_list)
def test_enable_reruns(self, mock_log):
@@ -270,5 +281,5 @@ def test_enable_reruns(self, mock_log):
self.assertFalse(api_users.called)
self.assertFalse(api_stream.called)
self.assertTrue(access_token.called_once)
- self.assertIsNone(streams)
+ self.assertTrue(streams)
self.assertNotIn(self.log_call, mock_log.info.call_args_list)
| --twitch-disable-reruns error
<!--
Thanks for reporting a bug!
USE THE TEMPLATE. Otherwise your bug report may be rejected.
First, see the contribution guidelines:
https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink
Also check the list of open and closed bug reports:
https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22
Please see the text preview to avoid unnecessary formatting errors.
-->
## Bug Report
<!-- Replace [ ] with [x] in order to check the box -->
- [x] This is a bug report and I have read the contribution guidelines.
### Description
<!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. -->
Reruns disabling seems to be working but this error accurs in cmd
![cmd_ZJg3To8rUo](https://user-images.githubusercontent.com/51099894/73242786-f5af9680-41b6-11ea-973e-aaf14b37f472.png)
### Expected / Actual behavior
<!-- What do you expect to happen, and what is actually happening? -->
### Reproduction steps / Explicit stream URLs to test
<!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. -->
1. ...
2. ...
3. ...
### Log output
<!--
TEXT LOG OUTPUT IS REQUIRED for a bug report!
Use the `--loglevel debug` parameter and avoid using parameters which suppress log output.
https://streamlink.github.io/cli.html#cmdoption-l
Make sure to **remove usernames and passwords**
You can copy the output to https://gist.github.com/ or paste it below.
-->
```
REPLACE THIS TEXT WITH THE LOG OUTPUT
```
### Additional comments, screenshots, etc.
[Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
| Oh boy, here we go... Looks like the [validation scheme implemented in #2724](https://github.com/streamlink/streamlink/pull/2724/commits/d3130ca464234d8f0a05874b31c9e5a08b75b75c#diff-195bebeb65dac1f6a8e94f1957a95ec1R103) is a bit too strict for the returned Twitch API response. According to Twitch's website (which runs off of their GQL API, and not the kraken or helix REST APIs), the channel you've posted (welovegames) is currently streaming a rerun of a previous broadcast. But when looking at the API response from the kraken API, the stream properties `stream_type` and `broadcast_platform` which are used for checking the status don't indicate a rerun. See here:
```bash
$ curl -s \
-H "Accept: application/vnd.twitchtv.v5+json" \
-H "Client-ID: phiay4sq36lfv9zu7cbqwz2ndnesfd8" \
"https://api.twitch.tv/kraken/streams/30814134" \
| jq
```
```json
{
"stream": {
"_id": 36780183456,
"game": "Just Chatting",
"broadcast_platform": "other",
"community_id": "",
"community_ids": null,
"viewers": 0,
"video_height": 720,
"average_fps": 60,
"delay": 0,
"created_at": "2020-01-28T01:39:27Z",
"is_playlist": false,
"stream_type": "live",
"preview": {
"small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-80x45.jpg",
"medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-320x180.jpg",
"large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-640x360.jpg",
"template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-{width}x{height}.jpg"
},
"channel": {
"mature": false,
"status": "BB",
"broadcaster_language": "ru",
"broadcaster_software": "watch_party_rerun",
"display_name": "WELOVEGAMES",
"game": "Just Chatting",
"language": "ru",
"_id": 30814134,
"name": "welovegames",
"created_at": "2012-05-26T11:18:26.294212Z",
"updated_at": "2020-01-28T07:12:34.107982Z",
"partner": true,
"logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/welovegames-profile_image-15afef2e74a108da-300x300.png",
"video_banner": null,
"profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/welovegames-profile_banner-5700d3683ec069c3-480.png",
"profile_banner_background_color": "",
"url": "https://www.twitch.tv/welovegames",
"views": 74717818,
"followers": 387170,
"broadcaster_type": "partner",
"description": "vk.com/welovegames",
"private_video": false,
"privacy_options_enabled": false
}
}
}
```
What's unexpected here is that `broadcast_platform` is set to `other`, which makes the validation scheme fail. As I've mentioned [in my review of #2722](https://github.com/streamlink/streamlink/pull/2722/files#r352730608), these two properties are super inconsistent and are a result of Twitch not documenting properly and changing stuff several times throughout the recent years. If you take a look at my comment over there, you can see in the added API response log that the `broadcast_platform` property can indeed be set to `rerun`, which means it has to be validated here in addition to `stream_type`, because as you can also see, `stream_type` is set to `live` in the API response posted above, even though the documentation says that it should not be `live` for offline stream reruns. What's surprising though is that there's an additional `channel.broadcaster_software` property which is set to `watch_party_rerun`. It's a total mess and checking this third property makes it even more confusing as it's not documented as well.
https://dev.twitch.tv/docs/v5/reference/streams#get-stream-by-user
So how can we check whether a stream is a rerun now? As I've said, checking for `stream_type` alone is not sufficient and checking for `broadcast_platform==rerun` is also not correct. Checking for other values like `other` is a bit weird though, because the value can also be `ps3` for channels streaming from a console. I guess we'll have to add this additional third property to the validation scheme and also make it less strict. :weary:
> Oh boy, here we go... Looks like the [validation scheme implemented in #2724](https://github.com/streamlink/streamlink/pull/2724/commits/d3130ca464234d8f0a05874b31c9e5a08b75b75c#diff-195bebeb65dac1f6a8e94f1957a95ec1R103) is a bit too strict for the returned Twitch API response. According to Twitch's website (which runs off of their GQL API, and not the kraken or helix REST APIs), the channel you've posted (welovegames) is currently streaming a rerun of a previous broadcast. But when looking at the API response from the kraken API, the stream properties `stream_type` and `broadcast_platform` which are used for checking the status don't indicate a rerun. See here:
>
> ```shell
> $ curl -s \
> -H "Accept: application/vnd.twitchtv.v5+json" \
> -H "Client-ID: phiay4sq36lfv9zu7cbqwz2ndnesfd8" \
> "https://api.twitch.tv/kraken/streams/30814134" \
> | jq
> ```
>
> ```json
> {
> "stream": {
> "_id": 36780183456,
> "game": "Just Chatting",
> "broadcast_platform": "other",
> "community_id": "",
> "community_ids": null,
> "viewers": 0,
> "video_height": 720,
> "average_fps": 60,
> "delay": 0,
> "created_at": "2020-01-28T01:39:27Z",
> "is_playlist": false,
> "stream_type": "live",
> "preview": {
> "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-80x45.jpg",
> "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-320x180.jpg",
> "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-640x360.jpg",
> "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_welovegames-{width}x{height}.jpg"
> },
> "channel": {
> "mature": false,
> "status": "BB",
> "broadcaster_language": "ru",
> "broadcaster_software": "watch_party_rerun",
> "display_name": "WELOVEGAMES",
> "game": "Just Chatting",
> "language": "ru",
> "_id": 30814134,
> "name": "welovegames",
> "created_at": "2012-05-26T11:18:26.294212Z",
> "updated_at": "2020-01-28T07:12:34.107982Z",
> "partner": true,
> "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/welovegames-profile_image-15afef2e74a108da-300x300.png",
> "video_banner": null,
> "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/welovegames-profile_banner-5700d3683ec069c3-480.png",
> "profile_banner_background_color": "",
> "url": "https://www.twitch.tv/welovegames",
> "views": 74717818,
> "followers": 387170,
> "broadcaster_type": "partner",
> "description": "vk.com/welovegames",
> "private_video": false,
> "privacy_options_enabled": false
> }
> }
> }
> ```
>
> What's unexpected here is that `broadcast_platform` is set to `other`, which makes the validation scheme fail. As I've mentioned [in my review of #2722](https://github.com/streamlink/streamlink/pull/2722/files#r352730608), these two properties are super inconsistent and are a result of Twitch not documenting properly and changing stuff several times throughout the recent years. If you take a look at my comment over there, you can see in the added API response log that the `broadcast_platform` property can indeed be set to `rerun`, which means it has to be validated here in addition to `stream_type`, because as you can also see, `stream_type` is set to `live` in the API response posted above, even though the documentation says that it should not be `live` for offline stream reruns. What's surprising though is that there's an additional `channel.broadcaster_software` property which is set to `watch_party_rerun`. It's a total mess and checking this third property makes it even more confusing as it's not documented as well.
> https://dev.twitch.tv/docs/v5/reference/streams#get-stream-by-user
>
> So how can we check whether a stream is a rerun now? As I've said, checking for `stream_type` alone is not sufficient and checking for `broadcast_platform==rerun` is also not correct. Checking for other values like `other` is a bit weird though, because the value can also be `ps3` for channels streaming from a console. I guess we'll have to add this additional third property to the validation scheme and also make it less strict. 😩
Ok. Thanks for your work.
| 2020-01-28T08:41:32 |