1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-12 14:23:32 +00:00

cleanup swift type unwrapping (#1300)

This commit is contained in:
Chad Scharf
2020-06-19 09:12:22 -04:00
committed by GitHub
parent bbe0b3ad97
commit 2481852170

View File

@@ -59,59 +59,64 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
if message.name != "bitwardenApp" { if message.name != "bitwardenApp" {
return return
} }
let messageBody = message.body as! String guard let messageBody = message.body as? String else {
let m: AppMessage? = jsonDeserialize(json: messageBody)
if m == nil {
return return
} }
let command = m!.command guard let m: AppMessage = jsonDeserialize(json: messageBody) else {
return
}
let command = m.command
NSLog("Command: \(command)") NSLog("Command: \(command)")
if command == "storage_get" { if command == "storage_get" {
if m!.data != nil { if let data = m.data {
let obj = UserDefaults.standard.string(forKey: m!.data!) let obj = UserDefaults.standard.string(forKey: data)
m!.responseData = obj m.responseData = obj
replyMessage(message: m!) replyMessage(message: m)
} }
} else if command == "storage_save" { } else if command == "storage_save" {
let data: StorageData? = jsonDeserialize(json: m!.data) guard let data: StorageData = jsonDeserialize(json: m.data) else {
if data?.key != nil { return
if data?.obj == nil { }
UserDefaults.standard.removeObject(forKey: data!.key) if let obj = data.obj {
UserDefaults.standard.set(obj, forKey: data.key)
} else { } else {
UserDefaults.standard.set(data?.obj, forKey: data!.key) UserDefaults.standard.removeObject(forKey: data.key)
}
replyMessage(message: m!)
} }
replyMessage(message: m)
} else if command == "storage_remove" { } else if command == "storage_remove" {
if m!.data != nil { if let data = m.data {
UserDefaults.standard.removeObject(forKey: m!.data!) UserDefaults.standard.removeObject(forKey: data)
replyMessage(message: m!) replyMessage(message: m)
} }
} else if command == "getLocaleStrings" { } else if command == "getLocaleStrings" {
let language = m!.data ?? "en" let language = m.data ?? "en"
let bundleURL = Bundle.main.resourceURL!.absoluteURL guard let bundleUrl = Bundle.main.resourceURL?.absoluteURL else {
let messagesUrl = bundleURL.appendingPathComponent("app/_locales/\(language)/messages.json") return
}
let messagesUrl = bundleUrl.appendingPathComponent("app/_locales/\(language)/messages.json")
do { do {
let json = try String(contentsOf: messagesUrl, encoding: .utf8) let json = try String(contentsOf: messagesUrl, encoding: .utf8)
webView.evaluateJavaScript("window.bitwardenLocaleStrings = \(json);", completionHandler: nil) webView.evaluateJavaScript("window.bitwardenLocaleStrings = \(json);", completionHandler: nil)
} catch { } catch {
NSLog("ERROR on getLocaleStrings, \(error)") NSLog("ERROR on getLocaleStrings, \(error)")
} }
replyMessage(message: m!) replyMessage(message: m)
} else if command == "tabs_query" { } else if command == "tabs_query" {
let options: TabQueryOptions? = jsonDeserialize(json: m!.data) guard let options: TabQueryOptions = jsonDeserialize(json: m.data) else {
if options?.currentWindow ?? false { return
}
if options.currentWindow ?? false {
SFSafariApplication.getActiveWindow { win in SFSafariApplication.getActiveWindow { win in
if win != nil { if win != nil {
processWindowsForTabs(wins: [win!], options: options, complete: { tabs in processWindowsForTabs(wins: [win!], options: options, complete: { tabs in
m!.responseData = jsonSerialize(obj: tabs) m.responseData = jsonSerialize(obj: tabs)
self.replyMessage(message: m!) self.replyMessage(message: m)
}) })
} else { } else {
SFSafariApplication.getAllWindows { wins in SFSafariApplication.getAllWindows { wins in
processWindowsForTabs(wins: wins, options: options, complete: { tabs in processWindowsForTabs(wins: wins, options: options, complete: { tabs in
m!.responseData = jsonSerialize(obj: tabs) m.responseData = jsonSerialize(obj: tabs)
self.replyMessage(message: m!) self.replyMessage(message: m)
}) })
} }
} }
@@ -119,18 +124,20 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
} else { } else {
SFSafariApplication.getAllWindows { wins in SFSafariApplication.getAllWindows { wins in
processWindowsForTabs(wins: wins, options: options, complete: { tabs in processWindowsForTabs(wins: wins, options: options, complete: { tabs in
m!.responseData = jsonSerialize(obj: tabs) m.responseData = jsonSerialize(obj: tabs)
self.replyMessage(message: m!) self.replyMessage(message: m)
}) })
} }
} }
} else if command == "tabs_message" { } else if command == "tabs_message" {
let tabMsg: TabMessage? = jsonDeserialize(json: m!.data) guard let tabMsg: TabMessage = jsonDeserialize(json: m.data) else {
return
}
SFSafariApplication.getAllWindows { wins in SFSafariApplication.getAllWindows { wins in
var theWin: SFSafariWindow? var theWin: SFSafariWindow?
var winIndex = 0 var winIndex = 0
for win in wins { for win in wins {
if tabMsg?.tab.windowId == winIndex { if tabMsg.tab.windowId == winIndex {
theWin = win theWin = win
break break
} }
@@ -140,20 +147,20 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
theWin?.getAllTabs { tabs in theWin?.getAllTabs { tabs in
var tabIndex = 0 var tabIndex = 0
for tab in tabs { for tab in tabs {
if tabMsg?.tab.index == tabIndex { if tabMsg.tab.index == tabIndex {
theTab = tab theTab = tab
break break
} }
tabIndex = tabIndex + 1 tabIndex = tabIndex + 1
} }
theTab?.getActivePage { activePage in theTab?.getActivePage { activePage in
activePage?.dispatchMessageToScript(withName: "bitwarden", userInfo: ["msg": tabMsg!.obj]) activePage?.dispatchMessageToScript(withName: "bitwarden", userInfo: ["msg": tabMsg.obj])
} }
} }
} }
} else if command == "hidePopover" { } else if command == "hidePopover" {
dismissPopover() dismissPopover()
replyMessage(message: m!) replyMessage(message: m)
} else if command == "showPopover" { } else if command == "showPopover" {
if popoverOpenCount <= 0 { if popoverOpenCount <= 0 {
SFSafariApplication.getActiveWindow { win in SFSafariApplication.getActiveWindow { win in
@@ -163,38 +170,42 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
} }
} }
} else if command == "isPopoverOpen" { } else if command == "isPopoverOpen" {
m!.responseData = popoverOpenCount > 0 ? "true" : "false" m.responseData = popoverOpenCount > 0 ? "true" : "false"
replyMessage(message: m!) replyMessage(message: m)
} else if command == "createNewTab" { } else if command == "createNewTab" {
if m!.data != nil { if let data = m.data, let url = URL(string: data) {
SFSafariApplication.getActiveWindow { win in SFSafariApplication.getActiveWindow { win in
win?.openTab(with: URL(string: m!.data!)!, makeActiveIfPossible: true, completionHandler: { _ in win?.openTab(with: url, makeActiveIfPossible: true, completionHandler: nil)
// Tab opened
})
} }
} }
} else if command == "reloadExtension" { } else if command == "reloadExtension" {
webView?.reload() webView?.reload()
replyMessage(message: m!) replyMessage(message: m)
} else if command == "copyToClipboard" { } else if command == "copyToClipboard" {
let pasteboard = NSPasteboard.general let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(m!.data ?? "", forType: NSPasteboard.PasteboardType.string) pasteboard.setString(m.data ?? "", forType: NSPasteboard.PasteboardType.string)
replyMessage(message: m!) replyMessage(message: m)
} else if command == "readFromClipboard" { } else if command == "readFromClipboard" {
let pasteboard = NSPasteboard.general let pasteboard = NSPasteboard.general
m!.responseData = pasteboard.pasteboardItems?.first?.string(forType: .string) m.responseData = pasteboard.pasteboardItems?.first?.string(forType: .string)
replyMessage(message: m!) replyMessage(message: m)
} else if command == "downloadFile" { } else if command == "downloadFile" {
if m!.data != nil { guard let jsonData = m.data else {
if let dlMsg: DownloadFileMessage = jsonDeserialize(json: m!.data) { return
var data: Data? }
if dlMsg.blobOptions?.type == "text/plain" { guard let dlMsg: DownloadFileMessage = jsonDeserialize(json: jsonData) else {
data = dlMsg.blobData?.data(using: .utf8) return
} else if dlMsg.blobData != nil { }
data = Data(base64Encoded: dlMsg.blobData!) var blobData: Data?
if dlMsg.blobOptions?.type == "text/plain" {
blobData = dlMsg.blobData?.data(using: .utf8)
} else if let blob = dlMsg.blobData {
blobData = Data(base64Encoded: blob)
}
guard let data = blobData else {
return
} }
if data != nil {
let panel = NSSavePanel() let panel = NSSavePanel()
panel.canCreateDirectories = true panel.canCreateDirectories = true
panel.nameFieldStringValue = dlMsg.fileName panel.nameFieldStringValue = dlMsg.fileName
@@ -207,7 +218,7 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
fileManager.createFile(atPath: url.absoluteString, contents: Data(), fileManager.createFile(atPath: url.absoluteString, contents: Data(),
attributes: nil) attributes: nil)
} }
try data!.write(to: url) try data.write(to: url)
} catch { } catch {
print(error) print(error)
NSLog("ERROR in downloadFile, \(error)") NSLog("ERROR in downloadFile, \(error)")
@@ -217,9 +228,6 @@ class SafariExtensionViewController: SFSafariExtensionViewController, WKScriptMe
} }
} }
} }
}
}
}
func replyMessage(message: AppMessage) { func replyMessage(message: AppMessage) {
if webView == nil { if webView == nil {
@@ -301,17 +309,17 @@ func makeTabObject(tab: SFSafariTab, activeTab: SFSafariTab?, windowIndex: Int,
t.index = tabIndex t.index = tabIndex
t.id = "\(windowIndex)_\(tabIndex)" t.id = "\(windowIndex)_\(tabIndex)"
tab.getActivePage { page in tab.getActivePage { page in
if page == nil { guard let activePage = page else {
complete(t) complete(t)
} else { return
page!.getPropertiesWithCompletionHandler({ props in }
activePage.getPropertiesWithCompletionHandler({ props in
t.title = props?.title t.title = props?.title
t.url = props?.url?.absoluteString t.url = props?.url?.absoluteString
complete(t) complete(t)
}) })
} }
} }
}
func jsonSerialize<T: Encodable>(obj: T?) -> String? { func jsonSerialize<T: Encodable>(obj: T?) -> String? {
let encoder = JSONEncoder() let encoder = JSONEncoder()