Revert to use api control when in develop mode

This commit is contained in:
yicheng 2019-10-09 20:33:57 +08:00
parent 882954ad26
commit 5138931c04
4 changed files with 116 additions and 61 deletions

View File

@ -186,7 +186,9 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func updateProxyList() {
if ConfigManager.shared.isRunning {
updateProxyList(withMenus: MenuItemFactory.menuItems())
MenuItemFactory.menuItems() { [weak self] items in
self?.updateProxyList(withMenus: items)
}
} else {
updateProxyList(withMenus: [])
}
@ -266,27 +268,30 @@ class AppDelegate: NSObject, NSApplicationDelegate {
startProxy()
guard ConfigManager.shared.isRunning else {return}
if let error = ApiRequest.requestConfigUpdate() {
if showNotification {
NSUserNotificationCenter.default
.post(title: NSLocalizedString("Reload Config Fail", comment: "")+error,
info: error)
}
} else {
syncConfig()
resetStreamApi()
selectProxyGroupWithMemory()
selectOutBoundModeWithMenory()
selectAllowLanWithMenory()
ConfigFileManager.checkFinalRuleAndShowAlert()
if showNotification {
NSUserNotificationCenter.default
.post(title: NSLocalizedString("Reload Config Succeed", comment: ""),
info: NSLocalizedString("Succees", comment: ""))
ApiRequest.requestConfigUpdate() {
[weak self] err in
guard let self = self else {return}
if let error = err {
if showNotification {
NSUserNotificationCenter.default
.post(title: NSLocalizedString("Reload Config Fail", comment: "")+error,
info: error)
}
} else {
self.syncConfig()
self.resetStreamApi()
self.selectProxyGroupWithMemory()
self.selectOutBoundModeWithMenory()
self.selectAllowLanWithMenory()
ConfigFileManager.checkFinalRuleAndShowAlert()
if showNotification {
NSUserNotificationCenter.default
.post(title: NSLocalizedString("Reload Config Succeed", comment: ""),
info: NSLocalizedString("Succees", comment: ""))
}
}
}
}
}
// MARK: Main actions

View File

@ -20,6 +20,8 @@ enum RequestError: Error {
case decodeFail
}
typealias ErrorString = String
class ApiRequest {
static let shared = ApiRequest()
private init(){
@ -66,6 +68,23 @@ class ApiRequest {
static func requestConfig(completeHandler:@escaping ((ClashConfig)->())){
if ConfigManager.developerMode {
req("/configs").responseData {
res in
do {
let data = try res.result.get()
guard let config = ClashConfig.fromData(data) else {
throw RequestError.decodeFail
}
completeHandler(config)
} catch let err {
Logger.log(err.localizedDescription)
}
}
return
}
let data = clashGetConfigs()?.toString().data(using: .utf8) ?? Data()
guard let config = ClashConfig.fromData(data) else {
NSUserNotificationCenter.default.post(title: "Error", info: "Get clash config failed. Try Fix your config file then reload config or restart ClashX.")
@ -76,15 +95,40 @@ class ApiRequest {
}
static func requestConfigUpdate() -> String?{
static func requestConfigUpdate(callback: @escaping ((ErrorString?)->())){
let filePath = "\(kConfigFolderPath)\(ConfigManager.selectConfigName).yaml"
let res = clashUpdateConfig(filePath.goStringBuffer())?.toString() ?? "unknown error"
if res == "success" {
return nil
let placeHolderErrorDesp = "Error occoured, Please try to fix it by restarting ClashX. "
let errorHanlder: (ErrorString)->Void = {
err in
if err.contains("no such file or directory") {
ConfigManager.selectConfigName = "config"
} else {
callback(err)
}
}
// DEV MODE: Use API
if ConfigManager.developerMode {
req("/configs", method: .put,parameters: ["Path":filePath],encoding: JSONEncoding.default).responseJSON {res in
if (res.response?.statusCode == 204) {
ConfigManager.shared.isRunning = true
callback(nil)
} else {
let errorJson = try? res.result.get()
let err = JSON(errorJson ?? "")["message"].string ?? placeHolderErrorDesp
errorHanlder(err)
}
}
return
}
// NORMAL MODE: Use internal api
let res = clashUpdateConfig(filePath.goStringBuffer())?.toString() ?? placeHolderErrorDesp
if res == "success" {
callback(nil)
} else {
errorHanlder(res)
}
return res
}
static func updateOutBoundMode(mode:ClashProxyMode, callback:@escaping ((Bool)->())) {
@ -99,9 +143,18 @@ class ApiRequest {
}
}
static func requestProxyGroupList() -> ClashProxyResp {
static func requestProxyGroupList(completeHandler:@escaping ((ClashProxyResp)->Void)) {
if ConfigManager.developerMode {
req("/proxies").responseJSON{
res in
let proxies = ClashProxyResp(try? res.result.get())
completeHandler(proxies)
}
return
}
let json = JSON(parseJSON: clashGetProxies()?.toString() ?? "")
return ClashProxyResp(json.object)
completeHandler(ClashProxyResp(json.object))
}
static func updateAllowLan(allow:Bool,completeHandler:@escaping (()->())) {
@ -126,12 +179,14 @@ class ApiRequest {
}
static func getAllProxyList(callback:@escaping (([ClashProxyName])->())) {
let proxyInfo = requestProxyGroupList()
let proxyGroupType:[ClashProxyType] = [.urltest,.fallback,.loadBalance,.select,.direct,.reject]
let lists:[ClashProxyName] = proxyInfo.proxies
.filter{$0.name == "GLOBAL" && proxyGroupType.contains($0.type)}
.first?.all ?? []
callback(lists)
requestProxyGroupList() {
proxyInfo in
let proxyGroupType:[ClashProxyType] = [.urltest,.fallback,.loadBalance,.select,.direct,.reject]
let lists:[ClashProxyName] = proxyInfo.proxies
.filter{$0.name == "GLOBAL" && proxyGroupType.contains($0.type)}
.first?.all ?? []
callback(lists)
}
}
static func getProxyDelay(proxyName:String,callback:@escaping ((Int)->())) {

View File

@ -129,15 +129,7 @@ class ConfigManager {
}
}
static var developerMode:Bool {
get{
return UserDefaults.standard.bool(forKey: "kDeveloperMode")
}
set {
UserDefaults.standard.set(newValue, forKey: "kDeveloperMode")
}
}
static var developerMode = UserDefaults.standard.bool(forKey: "kDeveloperMode")
}

View File

@ -11,31 +11,34 @@ import SwiftyJSON
import RxCocoa
class MenuItemFactory {
static func menuItems() -> [NSMenuItem]{
static func menuItems(completionHandler: @escaping (([NSMenuItem])->Void)){
if ConfigManager.shared.currentConfig?.mode == .direct {
return []
completionHandler([])
return
}
let proxyInfo = ApiRequest.requestProxyGroupList()
var menuItems = [NSMenuItem]()
for proxy in proxyInfo.proxyGroups {
var menu:NSMenuItem?
switch proxy.type {
case .select: menu = self.generateSelectorMenuItem(proxyGroup: proxy, proxyInfo: proxyInfo)
case .urltest,.fallback: menu = generateUrlTestFallBackMenuItem(proxyGroup: proxy, proxyInfo: proxyInfo)
case .loadBalance:
menu = generateLoadBalanceMenuItem(proxyGroup: proxy, proxyInfo: proxyInfo)
default: continue
}
ApiRequest.requestProxyGroupList() {
proxyInfo in
var menuItems = [NSMenuItem]()
if let menu = menu {
menuItems.append(menu)
menu.isEnabled=true
for proxy in proxyInfo.proxyGroups {
var menu:NSMenuItem?
switch proxy.type {
case .select: menu = self.generateSelectorMenuItem(proxyGroup: proxy, proxyInfo: proxyInfo)
case .urltest,.fallback: menu = generateUrlTestFallBackMenuItem(proxyGroup: proxy, proxyInfo: proxyInfo)
case .loadBalance:
menu = generateLoadBalanceMenuItem(proxyGroup: proxy, proxyInfo: proxyInfo)
default: continue
}
if let menu = menu {
menuItems.append(menu)
menu.isEnabled=true
}
}
completionHandler(menuItems.reversed())
}
return menuItems.reversed()
}
static func proxygroupTitle(name:String,now:String) -> NSAttributedString? {