-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathftp-browser.lua
94 lines (78 loc) · 2.47 KB
/
ftp-browser.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
--[[
An addon for mpv-file-browser which adds support for ftp servers
]]--
local mp = require 'mp'
local msg = require 'mp.msg'
local utils = require 'mp.utils'
local fb = require 'file-browser'
---@type ParserConfig
local ftp = {
priority = 100,
api_version = "1.1.0"
}
function ftp:can_parse(directory)
return directory:sub(1, 6) == "ftp://"
end
---In my experience curl has been somewhat unreliable when it comes to ftp requests,
---this fuction retries the request a few times just in case.
---@async
---@param args string[]
---@return MPVSubprocessResult
local function execute(args)
msg.debug(utils.to_string(args))
---@type boolean, MPVSubprocessResult
local _, cmd = fb.get_parse_state():yield(
mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
capture_stderr = true,
args = args
}, fb.coroutine.callback())
)
return cmd
end
---Encodes special characters using the URL percent encoding format.
---@param url string
---@return string
local function urlEncode(url)
local domain, path = string.match(url, '(ftp://[^/]-/)(.*)')
if not path then return url end
-- these are the unreserved URI characters according to RFC 3986
-- https://www.rfc-editor.org/rfc/rfc3986#section-2.3
path = string.gsub(path, '[^%w.~_%-]', function(c)
return ('%%%x'):format(string.byte(c))
end)
return domain..path
end
---@async
function ftp:parse(directory)
msg.verbose(directory)
local res = execute({"curl", "-k", "-g", "--retry", "4", urlEncode(directory)})
local entries = execute({"curl", "-k", "-g", "-l", "--retry", "4", urlEncode(directory)})
if entries.status == 28 then
msg.error(entries.stderr)
elseif entries.status ~= 0 or res.status ~= 0 then
msg.error(entries.stderr)
return
end
local response = {}
for str in string.gmatch(res.stdout, "[^\r\n]+") do
table.insert(response, str)
end
local list = {}
local i = 1
for str in string.gmatch(entries.stdout, "[^\r\n]+") do
if str and response[i] then
msg.trace(str .. ' | ' .. response[i])
if response[i]:sub(1,1) == "d" then
table.insert(list, { name = str..'/', type = "dir" })
else
table.insert(list, { name = str, type = "file" })
end
i = i+1
end
end
return list
end
return ftp