forked from streamlink/streamlink
/
nicolive.py
298 lines (252 loc) · 9.78 KB
/
nicolive.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
$description Japanese live-streaming and video hosting social platform.
$url live.nicovideo.jp
$type live, vod
$account Required by some streams
$notes Timeshift is supported
"""
import logging
import re
from threading import Event
from streamlink.compat import urljoin
from streamlink.exceptions import FatalPluginError
from streamlink.plugin import Plugin, PluginError, pluginargument, pluginmatcher
from streamlink.plugin.api import useragents, validate
from streamlink.plugin.api.websocket import WebsocketClient
from streamlink.stream.hls import HLSStream, HLSStreamReader
from streamlink.utils.parse import parse_json
from streamlink.utils.times import hours_minutes_seconds
from streamlink.utils.url import update_qsd
log = logging.getLogger(__name__)
class NicoLiveWsClient(WebsocketClient):
STREAM_OPENED_TIMEOUT = 6
def __init__(self, *args, **kwargs):
super(NicoLiveWsClient, self).__init__(*args, **kwargs)
self.opened = Event()
self.ready = Event()
def on_open(self, wsapp):
super(NicoLiveWsClient, self).on_open(wsapp)
self.send_playerversion()
self.send_getpermit()
def on_message(self, wsapp, data):
log.debug(u"Received: {0}".format(data))
message = parse_json(data)
msgtype = message.get("type")
msgdata = message.get("data", {})
if msgtype == "ping":
self.send_pong()
elif msgtype == "stream" and msgdata.get("protocol") == "hls" and msgdata.get("uri"):
self.hls_stream_url = msgdata.get("uri")
self.ready.set()
if self.opened.wait(self.STREAM_OPENED_TIMEOUT):
log.debug("Stream opened, keeping websocket connection alive")
else:
log.info("Closing websocket connection")
self.close()
elif msgtype == "disconnect":
reason = msgdata.get("reason", "Unknown reason")
log.info("Received disconnect message: {0}".format(reason))
self.close()
def send_playerversion(self):
self.send_json({
"type": "startWatching",
"data": {
"stream": {
"quality": "abr",
"protocol": "hls",
"latency": "high",
"chasePlay": False
},
"room": {
"protocol": "webSocket",
"commentable": True
},
"reconnect": False
}
})
def send_getpermit(self):
self.send_json({
"type": "getAkashic",
"data": {
"chasePlay": False
}
})
def send_pong(self):
self.send_json({"type": "pong"})
self.send_json({"type": "keepSeat"})
class NicoLiveHLSStreamReader(HLSStreamReader):
def open(self):
self.stream.wsclient.opened.set()
super(NicoLiveHLSStreamReader, self).open()
def close(self):
super(NicoLiveHLSStreamReader, self).close()
self.stream.wsclient.close()
class NicoLiveHLSStream(HLSStream):
__reader__ = NicoLiveHLSStreamReader
def set_wsclient(self, wsclient):
self.wsclient = wsclient
@pluginmatcher(re.compile(
r"https?://(?P<domain>live\d*\.nicovideo\.jp)/watch/(lv|co)\d+"
))
@pluginargument(
"email",
sensitive=True,
argument_name="niconico-email",
metavar="EMAIL",
help="The email or phone number associated with your Niconico account",
)
@pluginargument(
"password",
sensitive=True,
argument_name="niconico-password",
metavar="PASSWORD",
help="The password of your Niconico account",
)
@pluginargument(
"user-session",
sensitive=True,
argument_name="niconico-user-session",
metavar="VALUE",
help="""
Value of the user-session token.
Can be used as an alternative to providing a password.
""",
)
@pluginargument(
"purge-credentials",
argument_name="niconico-purge-credentials",
action="store_true",
help="Purge cached Niconico credentials to initiate a new session and reauthenticate.",
)
@pluginargument(
"timeshift-offset",
type=hours_minutes_seconds,
argument_name="niconico-timeshift-offset",
metavar="[HH:]MM:SS",
default=None,
help="""
Amount of time to skip from the beginning of a stream.
Default is 00:00:00.
""",
)
class NicoLive(Plugin):
STREAM_READY_TIMEOUT = 6
LOGIN_URL = "https://account.nicovideo.jp/login/redirector"
LOGIN_URL_PARAMS = {
"show_button_twitter": 1,
"show_button_facebook": 1,
"next_url": "/",
}
def _get_streams(self):
if self.get_option("purge_credentials"):
self.clear_cookies()
log.info("All credentials were successfully removed")
self.session.http.headers.update({
"User-Agent": useragents.CHROME,
})
self.niconico_web_login()
wss_api_url = self.get_wss_api_url()
if not wss_api_url:
log.error(
"Failed to get wss_api_url. "
"Please check if the URL is correct, "
"and make sure your account has access to the video."
)
return
self.wsclient = NicoLiveWsClient(self.session, wss_api_url)
self.wsclient.start()
hls_stream_url = self._get_hls_stream_url()
if not hls_stream_url:
return
offset = self.get_option("timeshift-offset")
if offset and "timeshift" in wss_api_url:
hls_stream_url = update_qsd(hls_stream_url, {"start": offset})
for quality, stream in NicoLiveHLSStream.parse_variant_playlist(self.session, hls_stream_url).items():
stream.set_wsclient(self.wsclient)
yield quality, stream
def _get_hls_stream_url(self):
log.debug("Waiting for permit (for at most {0} seconds)...".format(self.STREAM_READY_TIMEOUT))
if not self.wsclient.ready.wait(self.STREAM_READY_TIMEOUT) or not self.wsclient.is_alive():
log.error("Waiting for permit timed out.")
self.wsclient.close()
return
return self.wsclient.hls_stream_url
def get_wss_api_url(self):
try:
data = self.session.http.get(self.url, schema=validate.Schema(
validate.parse_html(),
validate.xml_find(".//script[@id='embedded-data'][@data-props]"),
validate.get("data-props"),
validate.parse_json(),
{"site": {
"relive": {
"webSocketUrl": validate.url(scheme="wss")
},
validate.optional("frontendId"): int
}},
validate.get("site"),
validate.union_get(("relive", "webSocketUrl"), "frontendId")
))
except PluginError:
return
wss_api_url, frontend_id = data
if frontend_id is not None:
wss_api_url = update_qsd(wss_api_url, {"frontend_id": frontend_id})
return wss_api_url
def niconico_web_login(self):
user_session = self.get_option("user-session")
email = self.get_option("email")
password = self.get_option("password")
if user_session is not None:
log.info("Logging in via provided user session cookie")
self.session.http.cookies.set(
"user_session",
user_session,
path="/",
domain="nicovideo.jp"
)
self.save_cookies()
elif self.session.http.cookies.get("user_session"):
log.info("Logging in via cached user session cookie")
elif email is not None and password is not None:
log.info("Logging in via provided email and password")
root = self.session.http.post(
self.LOGIN_URL,
data={"mail_tel": email, "password": password},
params=self.LOGIN_URL_PARAMS,
schema=validate.Schema(validate.parse_html()),
)
if self.session.http.cookies.get("user_session"):
log.info("Logged in.")
self.save_cookies()
return
input_with_value = {}
for elem in root.xpath(".//form[@action]//input"):
if elem.attrib.get("value"):
input_with_value[elem.attrib.get("name")] = elem.attrib.get("value")
else:
if elem.attrib.get("id") == "oneTimePw":
maxlength = int(elem.attrib.get("maxlength"))
try:
oneTimePw = self.input_ask("Enter the 6 digit number included in email")
if len(oneTimePw) > maxlength:
log.error("invalid user input")
return
except FatalPluginError:
return
input_with_value[elem.attrib.get("name")] = oneTimePw
else:
log.debug("unknown input: {0}".format(elem.attrib.get('name')))
root = self.session.http.post(
urljoin("https://account.nicovideo.jp", root.xpath("string(.//form[@action]/@action)")),
data=input_with_value,
schema=validate.Schema(validate.parse_html()),
)
log.debug("Cookies: {0}".format(self.session.http.cookies.get_dict()))
if self.session.http.cookies.get("user_session") is None:
error = root.xpath("string(//div[@class='formError']/div/text())")
log.warning("Login failed: {0}".format(error or 'unknown reason'))
else:
log.info("Logged in.")
self.save_cookies()
__plugin__ = NicoLive