mirror of
https://github.com/Baipyrus/ProxySwitcher.git
synced 2024-12-26 12:41:45 +00:00
103 lines
2.4 KiB
Go
103 lines
2.4 KiB
Go
package proxy
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/Baipyrus/ProxySwitcher/util"
|
|
"golang.org/x/sys/windows/registry"
|
|
)
|
|
|
|
func readArgs(replaceVariable bool, args []string, configCmd string) ([]string, string) {
|
|
var configArgs []string
|
|
|
|
for _, arg := range args {
|
|
if !replaceVariable {
|
|
configArgs = append(configArgs, arg)
|
|
continue
|
|
}
|
|
|
|
configCmd = strings.Replace(configCmd, "$PRSW_ARG", arg, 1)
|
|
}
|
|
|
|
return configArgs, configCmd
|
|
}
|
|
|
|
func applyProxy(configArgs []string, configCmd string, proxyServer string, variant *util.Variant) ([]string, string) {
|
|
if proxyServer == "" {
|
|
return configArgs, configCmd
|
|
}
|
|
|
|
if variant.Type == util.VARIABLE && strings.Count(configCmd, "$PRSW_ARG") == 1 {
|
|
configCmd = strings.Replace(configCmd, "$PRSW_ARG", proxyServer, 1)
|
|
return configArgs, configCmd
|
|
}
|
|
|
|
if variant.Equator != "" {
|
|
configArgs[len(configArgs)-1] += variant.Equator + proxyServer
|
|
return configArgs, configCmd
|
|
}
|
|
|
|
configArgs = append(configArgs, proxyServer)
|
|
|
|
return configArgs, configCmd
|
|
}
|
|
|
|
func getVariants(variants []*util.Variant, configCmd, proxyServer string) []*util.Command {
|
|
var commands []*util.Command
|
|
|
|
for _, variant := range variants {
|
|
replaceVariable := variant.Type == util.VARIABLE
|
|
|
|
configArgs, configCmd := readArgs(replaceVariable, variant.Arguments, configCmd)
|
|
|
|
configArgs, configCmd = applyProxy(configArgs, configCmd, proxyServer, variant)
|
|
|
|
commands = append(commands, &util.Command{Name: configCmd, Arguments: configArgs})
|
|
}
|
|
|
|
return commands
|
|
}
|
|
|
|
func ReadSystemProxy() (*Proxy, error) {
|
|
key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer key.Close()
|
|
|
|
enabled, _, err := key.GetIntegerValue("proxyEnable")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
server, _, err := key.GetStringValue("proxyServer")
|
|
if err != nil && !errors.Is(err, registry.ErrNotExist) {
|
|
return nil, err
|
|
}
|
|
|
|
return &Proxy{Enabled: enabled != 0, Server: server}, nil
|
|
}
|
|
|
|
func SetSystemProxy(state bool) error {
|
|
key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.SET_VALUE)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer key.Close()
|
|
|
|
var value uint32
|
|
if state {
|
|
value = 1
|
|
} else {
|
|
value = 0
|
|
}
|
|
|
|
err = key.SetDWordValue("proxyEnable", value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|