forked from open-dynaMIX/simple-mpv-webui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebui.lua
473 lines (417 loc) · 13 KB
/
webui.lua
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
require 'mp.options'
require 'mp.msg'
local socket = require("socket")
local dec64 = require("mime").decode("base64")
local msg_prefix = "[webui] "
local options = {
port = 8888,
disable = false,
logging = false,
ipv4 = true,
ipv6 = true,
audio_devices = '',
}
read_options(options, "webui")
local function validate_number_param(param)
if not tonumber(param) then
return false, 'Parameter needs to be an integer or float'
else
return true, nil
end
end
local commands = {
play = function()
return pcall(mp.set_property_bool, "pause", false)
end,
pause = function()
return pcall(mp.set_property_bool, "pause", true)
end,
toggle_pause = function()
local curr = mp.get_property_bool("pause")
return pcall(mp.set_property_bool, "pause", not curr)
end,
fullscreen = function()
local curr = mp.get_property_bool("fullscreen")
return pcall(mp.set_property_bool, "fullscreen", not curr)
end,
seek = function(t)
local valid, msg = validate_number_param(t)
if not valid then
return true, false, msg
end
return pcall(mp.command, "seek "..t)
end,
set_position = function(t)
local valid, msg = validate_number_param(t)
if not valid then
return true, false, msg
end
return pcall(mp.command, "seek "..t.." absolute")
end,
playlist_prev = function()
local position = tonumber(mp.get_property("time-pos") or 0)
if position > 1 then
return pcall(mp.command, "seek "..-position)
else
return pcall(mp.command, "playlist-prev")
end
end,
playlist_next = function()
return pcall(mp.command, "playlist-next")
end,
playlist_jump = function(p)
local valid, msg = validate_number_param(p)
if not valid then
return true, false, msg
end
return pcall(mp.set_property('playlist-pos', p))
end,
add_volume = function(v)
local valid, msg = validate_number_param(v)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'add volume '..v)
end,
set_volume = function(v)
local valid, msg = validate_number_param(v)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'set volume '..v)
end,
add_sub_delay = function(ms)
local valid, msg = validate_number_param(ms)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'add sub-delay '..ms)
end,
set_sub_delay = function(ms)
local valid, msg = validate_number_param(ms)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'set sub-delay '..ms)
end,
add_audio_delay = function(ms)
local valid, msg = validate_number_param(ms)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'add audio-delay '..ms)
end,
set_audio_delay = function(ms)
local valid, msg = validate_number_param(ms)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'set audio-delay '..ms)
end,
cycle_sub = function()
return pcall(mp.command, "cycle sub")
end,
cycle_audio = function()
return pcall(mp.command, "cycle audio")
end,
cycle_audio_device = function()
return pcall(mp.command, "cycle_values audio-device " .. options.audio_devices)
end,
add_chapter = function(num)
local valid, msg = validate_number_param(num)
if not valid then
return true, false, msg
end
return pcall(mp.command, 'add chapter '..num)
end
}
local function get_content_type(file_type)
if file_type == 'html' then
return 'text/html; charset=UTF-8'
elseif file_type == 'plain' then
return 'text/plain; charset=UTF-8'
elseif file_type == 'json' then
return 'application/json; charset=UTF-8'
elseif file_type == 'js' then
return 'application/javascript; charset=UTF-8'
elseif file_type == 'png' then
return 'image/png'
elseif file_type == 'ico' then
return 'image/x-icon'
elseif file_type == 'svg' then
return 'image/svg+xml'
elseif file_type == 'xml' then
return 'application/xml; charset=UTF-8'
elseif file_type == 'css' then
return 'text/css; charset=UTF-8'
elseif file_type == 'woff2' then
return 'font/woff2; charset=UTF-8'
elseif file_type == 'mp3' then
return 'audio/mpeg'
elseif file_type == 'webmanifest' then
return 'application/manifest+json'
end
end
local function header(code, content_type, content_length)
local common = '\nAccess-Control-Allow-Origin: *'..
'\nContent-Type: '..content_type..
'\nContent-Length: '..content_length..
'\nServer: simple-mpv-webui'..
'\nConnection: close\n\n'
if code == 200 then
return 'HTTP/1.1 200 OK'..common
elseif code == 400 then
return 'HTTP/1.1 400 Bad Request'..common
elseif code == 401 then
return 'HTTP/1.1 401 Unauthorized\nWWW-Authenticate: Basic realm="Simple MPV WebUI"'..common
elseif code == 404 then
return 'HTTP/1.1 404 Not Found'..common
elseif code == 405 then
return 'HTTP/1.1 405 Method Not Allowed\nAllow: GET,POST'..common
elseif code == 503 then
return 'HTTP/1.1 503 Service Unavailable'..common
end
end
local function round(a)
return (a - a % 1) / 1
end
function string.starts(String, Start)
return string.sub(String,1,string.len(Start))==Start
end
local function concatkeys(tab, sep)
local inter = {}
for key,_ in pairs(tab) do
inter[#inter+1] = key
end
return table.concat(inter, sep)
end
local function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
local function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
local function lines_from(file)
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
local function read_file(path)
local file = io.open(path, "rb")
if not file then return nil end
local content = file:read "*a"
file:close()
return content
end
local function log_line(request, code, length)
if not options.logging then
return
end
local referer = request['referer'] or '-'
local agent = request['agent'] or '-'
local time = os.date('%d/%b/%Y:%H:%M:%S %z', os.time())
mp.msg.info(
request["clientip"]..' - - ['..time..'] "'..request['request']..'" '..code..' '..length..' "'..referer..'" "'..agent..'"')
end
local function build_status_response()
local values = {
filename = mp.get_property('filename') or '',
duration = mp.get_property("duration") or '',
position = mp.get_property("time-pos") or '',
pause = tostring(mp.get_property_native("pause")) or '',
remaining = mp.get_property("playtime-remaining") or '',
sub_delay = mp.get_property_osd("sub-delay") or '',
audio_delay = mp.get_property_osd("audio-delay") or '',
metadata = mp.get_property("metadata") or '',
volume = mp.get_property("volume") or '',
volume_max = mp.get_property("volume-max") or '',
playlist = mp.get_property("playlist") or '',
track_list = mp.get_property("track-list") or '',
fullscreen = tostring(mp.get_property_native("fullscreen")) or ''
}
-- We need to check if the value is available.
-- If the file just started playing, mp-functions return nil for a short time.
fail = false
for k, v in pairs(values) do
if v == '' then
mp.msg.log("WARN", 'Could not fetch "'.. k .. '" from mpv.')
fail = true
end
end
if fail then
mp.msg.log("WARN", 'This is normal during startup.')
return false
end
return '{"audio-delay":'..values['audio_delay']:sub(1, -4)..',' ..
'"duration":'..round(values['duration'])..',' ..
'"filename":"'..values['filename']..'",' ..
'"fullscreen":'..values['fullscreen']..',' ..
'"metadata":'..values['metadata']..',' ..
'"pause":'..values['pause']..',' ..
'"playlist":'..values['playlist']..',' ..
'"position":'..round(values['position'])..',' ..
'"remaining":'..round(values['remaining'])..',' ..
'"sub-delay":'..values['sub_delay']:sub(1, -4)..',' ..
'"track-list":'..values['track_list']..',' ..
'"volume":'..round(values['volume'])..',' ..
'"volume-max":'..round(values['volume_max'])..'}'
end
local function handle_post(path)
local components = string.gmatch(path, "[^/]+")
local api_prefix = components()
if api_prefix ~= 'api' then
return 404, get_content_type('plain'), "Error: Requested URL /"..path.." not found"
end
local command = components()
local param = components() or ""
local f = commands[command]
if f ~= nil then
local _, err, ret = f(param)
if err then
return 200, get_content_type('json'), '{"message": "success"}'
else
return 400, get_content_type('json'), '{"message": "'..ret..'"}'
end
else
return 404, get_content_type('plain'), "Error: Requested URL /"..path.." not found"
end
end
local function handle_status_get()
local json = build_status_response()
if not json then
return 503, get_content_type('plain'), "Error: Not ready to handle requests."
else
return 200, get_content_type("json"), json
end
end
local function handle_static_get(path)
if string.find(path, '%.%./') then
return nil, nil
end
if path == "" then
path = 'index.html'
end
local content = read_file(script_path()..'webui-page/'..path)
local extension = path:match("[^.]+$") or ""
local content_type = get_content_type(extension)
if content == nil or content_type == nil then
return 404, get_content_type('plain'), "Error: Requested URL /"..path.." not found"
else
return 200, content_type, content
end
end
local function is_authenticated(request, passwd)
if not request['user'] or not request['password'] then
return false
end
for _,line in ipairs(passwd) do
if line == request['user']..':'..request['password'] then
return true
end
end
return false
end
local function handle_request(request, passwd)
if passwd ~= nil then
if not is_authenticated(request, passwd) then
return 401, get_content_type('plain'), "Authentication required."
end
end
if request["method"] == "POST" then
return handle_post(request['path'])
elseif request["method"] == "GET" then
if request["path"] == "api/status" or request["path"] == "api/status/" then
return handle_status_get()
else
return handle_static_get(request["path"])
end
else
return 405, get_content_type('plain'), "Error: Method not allowed"
end
end
local function parse_request(connection)
local request = {}
request['clientip'] = connection:getpeername()
local line = connection:receive()
while line ~= nil and line ~= "" do
if not request['request'] then
local raw_request = string.gmatch(line, "%S+")
request["request"] = line
request["method"] = raw_request()
request["path"] = string.sub(raw_request(), 2)
end
if string.starts(line, "User-Agent") then
request["agent"] = string.sub(line, 13)
elseif string.starts(line, "Referer") then
request["referer"] = string.sub(line, 10)
elseif string.starts(line, "Authorization: Basic ") then
local auth64 = string.sub(line, 22)
local auth_components = string.gmatch(dec64(auth64), "[^:]+")
request["user"] = auth_components()
request["password"] = auth_components()
end
line = connection:receive()
end
return request
end
local function listen(server, passwd)
local connection = server:accept()
if connection == nil then
return
end
local request = parse_request(connection)
local code, content_type, content = handle_request(request, passwd)
connection:send(header(code, content_type, #content))
connection:send(content)
connection:close()
log_line(request, code, #content)
return
end
local function get_passwd()
if file_exists(script_path()..".htpasswd") then
mp.msg.info('Found .htpasswd file. Basic authentication is enabled.')
return lines_from(script_path()..".htpasswd")
end
end
local function init_servers()
local servers = {}
if not options.ipv4 and not options.ipv6 then
mp.msg.error("Error: ipv4 and ipv6 is disabled!")
return servers
end
if options.ipv6 then
local address = '::0'
servers[address] = socket.bind(address, options.port)
end
if options.ipv4 then
local address = '0.0.0.0'
servers[address] = socket.bind(address, options.port)
end
return servers
end
if options.audio_devices == '' then
for _, device in pairs(mp.get_property_native("audio-device-list")) do
options.audio_devices = options.audio_devices .. ' ' .. device['name']
end
end
if options.disable then
mp.osd_message(msg_prefix.."disabled", 2)
return
else
local passwd = get_passwd()
local servers = init_servers()
if next(servers) == nil then
mp.msg.error("Error: Couldn't spawn server on port "..options.port)
else
for _, server in pairs(servers) do
server:settimeout(0)
mp.add_periodic_timer(0.2, function() listen(server, passwd) end)
end
mp.osd_message(msg_prefix.."Serving on "..concatkeys(servers, ' and ').." port "..options.port, 5)
end
end