Skip to content

Instantly share code, notes, and snippets.

@zhongfly
Last active May 16, 2025 09:02
Show Gist options
  • Save zhongfly/2a4e47b844edc22d0cc816f751fe9128 to your computer and use it in GitHub Desktop.
Save zhongfly/2a4e47b844edc22d0cc816f751fe9128 to your computer and use it in GitHub Desktop.
Get windows system proxy(only support http proxy) and auto set proxy for mpv and ytdl_hook
local mp = require 'mp'
local block = true
function string:trim()
return (self:gsub("^%s*(.-)%s*$", "%1"))
end
-- safe protocol (copied from mpv ytdl_hook.lua)
------------------------------------------------------------------------
local function Set (t)
local set = {}
for _, v in pairs(t) do set[v] = true end
return set
end
local safe_protos = Set {
"http", "https", "ftp", "ftps",
"rtmp", "rtmps", "rtmpe", "rtmpt", "rtmpts", "rtmpte",
"data"
}
------------------------------------------------------------------------
local function is_safe_protocol(path)
local proto = type(path) == "string" and path:match("^(%a[%w+.-]*):") or nil
return proto and safe_protos[proto]
end
local function pwshexec(command)
local ret = mp.command_native({
name = "subprocess",
args = {"powershell", "-NoProfile", "-Command", command},
playback_only = false,
capture_stdout = true,
capture_stderr = true
})
if ret.killed_by_us or (ret.status ~= 0) or ret.stdout == "" then
return ""
else
return (ret.stdout:gsub("\r\n$", "")):trim()
end
end
local function get_proxy()
-- 合并两次PowerShell调用为一次,减少进程创建开销
local result = pwshexec([[
$settings = Get-ItemProperty -Path 'Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
if ($settings.ProxyEnable -eq 1) {
$proxy = $settings.ProxyServer
if ($proxy -match '(\w+\.?)*:\d+') {
$matches[0]
}
}
]])
if result ~= "" then
return "http://" .. result
end
return nil
end
mp.command_native_async({name='ignore'},function()
-- 获取代理信息
local proxy = get_proxy()
--mp.msg.debug(proxy)
if proxy then
-- 设置http-proxy
if mp.get_property("http-proxy") == "" then
mp.set_property("http-proxy", proxy)
mp.msg.info("Auto set http-proxy: " .. proxy)
end
-- 设置youtube-dl代理
local raw_options = mp.get_property_native("options/ytdl-raw-options")
if not raw_options["proxy"] or raw_options["proxy"] == "" then
mp.commandv('no-osd', 'change-list', 'ytdl-raw-options', 'append', 'proxy='..proxy)
end
end
block = false
end)
-- 在ytdl_hook.lua运行前等待代理设置完成
mp.add_hook("on_load", 9, function()
local url = mp.get_property("stream-open-filename", "")
if is_safe_protocol(url) then
while block do
end
end
if not block then
exit()
end
end)
@lixueshu
Copy link

这个怎么用,放到哪个文件夹里

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment