8000 Supporting changes for DiscordKit rearchitect by cryptoAlgorithm · Pull Request #64 · SwiftcordApp/Swiftcord · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Supporting changes for DiscordKit rearchitect #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Swiftcord.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
3684BB59283C696E005045AE /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 3684BB58283C696E005045AE /* Sparkle */; };
3684BB5B283C69C5005045AE /* Sparkle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3684BB5A283C69C5005045AE /* Sparkle.swift */; };
900F6DA1284A1C0C000B6D29 /* GeneratedBuildSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 900F6DA0284A1C0C000B6D29 /* GeneratedBuildSettings.swift */; };
DA03DA3F284F1E9200257790 /* Keychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA03DA3E284F1E9200257790 /* Keychain.swift */; };
DA2384A127CB9714009E15E0 /* Font+.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA2384A027CB9714009E15E0 /* Font+.swift */; };
DA2384BA27CBC2CE009E15E0 /* GintoBold.otf in Resources */ = {isa = PBXBuildFile; fileRef = DA2384B827CBC2CE009E15E0 /* GintoBold.otf */; };
DA2384BB27CBC2CE009E15E0 /* GintoMedium.otf in Resources */ = {isa = PBXBuildFile; fileRef = DA2384B927CBC2CE009E15E0 /* GintoMedium.otf */; };
Expand Down Expand Up @@ -104,6 +105,7 @@
900F6D9F284A1AE6000B6D29 /* Project Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Project Release.xcconfig"; sourceTree = "<group>"; };
900F6DA0284A1C0C000B6D29 /* GeneratedBuildSettings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedBuildSettings.swift; sourceTree = "<group>"; };
90F77AAA284C87E900166BF3 /* AppCenter.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppCenter.xcconfig; sourceTree = "<group>"; };
DA03DA3E284F1E9200257790 /* Keychain.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Keychain.swift; sourceTree = "<group>"; };
DA23843827CB934D009E15E0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
DA2384A027CB9714009E15E0 /* Font+.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Font+.swift"; sourceTree = "<group>"; };
DA2384B827CBC2CE009E15E0 /* GintoBold.otf */ = {isa = PBXFileReference; lastKnownFileType = file; path = GintoBold.otf; sourceTree = "<group>"; };
Expand Down Expand Up @@ -333,6 +335,7 @@
children = (
DA520AE327D76BF8009FD740 /* Extensions */,
DA520AC127D37863009FD740 /* MergeStructs */,
DA03DA3E284F1E9200257790 /* Keychain.swift */,
DA4A889B27C0B23C00720909 /* WebView.swift */,
DAAFB5C6282AB56B00807B54 /* AudioCenterManager.swift */,
3684BB5A283C69C5005045AE /* Sparkle.swift */,
Expand Down Expand Up @@ -643,6 +646,7 @@
DA54D57F28460F3A00B11857 /* ReferenceMessageView.swift in Sources */,
DA32EF2427C6249000A9ED72 /* MessagesView.swift in Sources */,
DA97BA8C2849C0FA00059FD7 /* Cache.swift in Sources */,
DA03DA3F284F1E9200257790 /* Keychain.swift in Sources */,
E7AF1C27282FA3ED001F78DF /* Array.Channel+.swift in Sources */,
DA520AC327D37873009FD740 /* MergePartialMessage.swift in Sources */,
E7AF1C36282FC2E8001F78DF /* NSTextView+.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"location" : "https://github.com/SwiftcordApp/DiscordKit",
"state" : {
"branch" : "main",
"revision" : "9a27e869196df8926e1d47af6c73e3135debf51f"
"revision" : "213e0b8817f56cb7cf7fe03443386c330d59009d"
}
},
{
Expand Down
28 changes: 18 additions & 10 deletions Swiftcord/SwiftcordApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,21 @@
//

import DiscordKit
import DiscordKitCore
import SwiftUI

// There's probably a better place to put global constants
let appName = Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String

@main
struct SwiftcordApp: App, Equatable {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
let persistenceController = PersistenceController.shared
@StateObject var updaterViewModel = UpdaterViewModel()
struct SwiftcordApp: App {
static internal let tokenKeychainKey = "authToken"

// @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
// let persistenceController = PersistenceController.shared
@StateObject var updaterViewModel = UpdaterViewModel()
@StateObject private var gateway = DiscordGateway()
@StateObject private var restAPI = DiscordREST()
@StateObject private var state = UIState()

@AppStorage("theme") private var selectedTheme = "system"
Expand All @@ -28,11 +31,20 @@ struct SwiftcordApp: App, Equatable {
.overlay(LoadingView())
.environmentObject(gateway)
.environmentObject(state)
.environmentObject(restAPI)
// .environment(\.locale, .init(identifier: "zh-Hans"))
.environment(\.managedObjectContext, persistenceController.container.viewContext)
// .environment(\.managedObjectContext, persistenceController.container.viewContext)
.preferredColorScheme(selectedTheme == "dark"
? .dark
: (selectedTheme == "light" ? .light : .none))
: (selectedTheme == "light" ? .light : nil))
.onAppear {
guard let token = Keychain.load(key: SwiftcordApp.tokenKeychainKey) else {
state.attemptLogin = true
return
}
gateway.connect(token: token)
restAPI.setToken(token: token)
}
}
.commands {
CommandGroup(after: .appInfo) {
Expand All @@ -53,8 +65,4 @@ struct SwiftcordApp: App, Equatable {
// .environment(\.locale, .init(identifier: "zh-Hans"))
}
}

static func == (lhs: SwiftcordApp, rhs: SwiftcordApp) -> Bool {
lhs.gateway == rhs.gateway && lhs.state == rhs.state
}
}
2 changes: 1 addition & 1 deletion Swiftcord/Utils/Extensions/DiscordAPI/Array.Channel+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// Created by royal on 14/05/2022.
//

import DiscordKit
import DiscordKitCommon

extension Array where Element == Channel {
func discordSorted() -> Self {
Expand Down
2 changes: 1 addition & 1 deletion Swiftcord/Utils/Extensions/DiscordAPI/Channel+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// Created by royal on 14/05/2022.
//

import DiscordKit
import DiscordKitCommon

extension Channel {
func label(_ users: [Snowflake: User] = [:]) -> String? {
Expand Down
6 changes: 3 additions & 3 deletions Swiftcord/Utils/Extensions/DiscordAPI/CurrentUser+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
//

import Foundation
import DiscordKit
import DiscordKitCommon

extension CurrentUser {
func avatarURL(size: Int = 160) -> URL {
if let avatar = avatar {
return URL(string: "\(GatewayConfig.default.cdnURL)avatars/\(self.id)/\(avatar).webp?size=\(size)")!
return URL(string: "\(DiscordKitConfig.default.cdnURL)avatars/\(self.id)/\(avatar).webp?size=\(size)")!
} else {
return URL(string: "\(GatewayConfig.default.cdnURL)embed/avatars/\((Int(self.discriminator) ?? 0) % 5).png")!
return URL(string: "\(DiscordKitConfig.default.cdnURL)embed/avatars/\((Int(self.discriminator) ?? 0) % 5).png")!
}
}
}
2 changes: 1 addition & 1 deletion Swiftcord/Utils/Extensions/DiscordAPI/Guild+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// Created by royal on 14/05/2022.
//

import DiscordKit
import DiscordKitCommon

extension Guild {
var isDMChannel: Bool { id == "@me" }
Expand Down
2 changes: 1 addition & 1 deletion Swiftcord/Utils/Extensions/DiscordAPI/Message+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//

import Foundation
import DiscordKit
import DiscordKitCommon

extension Message {
func messageIsShrunk(prev: Message) -> Bool {
Expand Down
2 changes: 1 addition & 1 deletion Swiftcord/Utils/Extensions/DiscordAPI/User+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//

import Foundation
import DiscordKit
import DiscordKitCommon

extension User {
func avatarURL(size: Int = 160) -> URL {
Expand Down
6 changes: 4 additions & 2 deletions Swiftcord/Utils/Extensions/MessagesView+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import Foundation
import DiscordKit
import DiscordKitCommon
import DiscordKitCore

extension MessagesView {
internal func fetchMoreMessages() {
Expand All @@ -22,7 +24,7 @@ extension MessagesView {
fetchMessagesTask = Task {
let lastMsg = messages.isEmpty ? nil : messages[messages.count - 1].id

guard let newMessages = await DiscordAPI.getChannelMsgs(
guard let newMessages = await restAPI.getChannelMsgs(
id: channel.id,
before: lastMsg
) else {
Expand Down Expand Up @@ -55,7 +57,7 @@ extension MessagesView {
newMessage = ""
showingInfoBar = false
Task {
guard (await DiscordAPI.createChannelMsg(
guard (await restAPI.createChannelMsg(
message: NewMessage(
content: message,
attachments: attachments.isEmpty ? nil : attachments.enumerated()
Expand Down
90 changes: 90 additions & 0 deletions Swiftcord/Utils/Keychain.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//
// Keychain.swift
// DiscordKitCommon
//
// Created by Vincent Kwok on 21/2/22.
//
// Adapted from: https://stackoverflow.com/a/37539998 (actually had a Swift 5 example)

import Foundation
import Security

public class Keychain {
static let tag = Bundle.main.bundleIdentifier!.data(using: .utf8)!

@discardableResult
public class func save(key: String, data: String) -> OSStatus {
return save(key: key, data: data.data(using: .utf8)!)
}

@discardableResult
public class func save(key: String, data: Data) -> OSStatus {
let query = [
kSecClass as String: kSecClassGenericPassword as String,
kSecAttrAccount as String: "\(Bundle.main.bundleIdentifier!).\(key)",
kSecAttrApplicationTag as String: tag,
kSecValueData as String: data
] as [String: Any]

SecItemDelete(query as CFDictionary)

return SecItemAdd(query as CFDictionary, nil)
}

@discardableResult
public class func remove(key: String) -> OSStatus {
let query = [
kSecClass as String: kSecClassGenericPassword as String,
kSecAttrAccount as String: "\(Bundle.main.bundleIdentifier!).\(key)",
kSecAttrApplicationTag as String: tag,
kSecMatchLimit as String: kSecMatchLimitOne
] as [String: Any]

return SecItemDelete(query as CFDictionary)
}

public class func load(key: String) -> String? {
guard let data: Data = loadData(key: key) else { return nil }
return String(data: data, encoding: .utf8)
}

public class func loadData(key: String) -> Data? {
let query = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "\(Bundle.main.bundleIdentifier!).\(key)",
kSecReturnData as String: kCFBooleanTrue!,
kSecAttrApplicationTag as String: tag,
kSecMatchLimit as String: kSecMatchLimitOne
] as [String: Any]

var dataTypeRef: AnyObject?

let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)

guard status == noErr else { return nil }
return dataTypeRef as? Data
}

public class func createUniqueID() -> String {
let uuid: CFUUID = CFUUIDCreate(nil)
let cfStr: CFString = CFUUIDCreateString(nil, uuid)

let swiftString: String = cfStr as String
return swiftString
}
}

public extension Data {
init<T>(from value: T) {
var value = value
var tempData = Data()
withUnsafePointer(to: &value, { (ptr: UnsafePointer<T>) -> Void in
tempData = Data( buffer: UnsafeBufferPointer(start: ptr, count: 1))
})
self.init(tempData)
}

func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.load(as: T.self) }
}
}
2 changes: 1 addition & 1 deletion Swiftcord/Utils/MergeStructs/MergePartialMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
// Fields from PartialMessage are favored

import Foundation
import DiscordKit
import DiscordKitCommon

extension Message {
mutating func mergeWithPartialMsg(_ partial: PartialMessage) {
Expand Down
15 changes: 8 additions & 7 deletions Swiftcord/Views/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import SwiftUI
import CoreData
import os
import DiscordKit
import DiscordKitCore
import DiscordKitCommon

struct CustomHorizontalDivider: View {
Expand All @@ -33,6 +34,7 @@ struct ContentView: View {
@StateObject private var audioManager = AudioCenterManager()

@EnvironmentObject var gateway: DiscordGateway
@EnvironmentObject var restAPI: DiscordREST
@EnvironmentObject var state: UIState

private let log = Logger(category: "ContentView")
Expand Down Expand Up @@ -129,8 +131,6 @@ struct ContentView: View {
)
}

// Using the .equatable() modifier on this View causes a swift-frontend
// bus error when compiling for release. F438 I have no idea why that happens.
ServerView(
guild: selectedGuildID == nil
? nil
Expand Down Expand Up @@ -166,8 +166,9 @@ struct ContentView: View {
.onChange(of: loginWVModel.token, perform: { token in
if let token = token {
state.attemptLogin = false
Keychain.save(key: "authToken", data: token)
gateway.connect() // Reconnect to the socket
Keychain.save(key: SwiftcordApp.tokenKeychainKey, data: token)
gateway.connect(token: token) // Reconnect to the socket with the new token
restAPI.setToken(token: token)
}
})
.onAppear {
Expand All @@ -176,15 +177,15 @@ struct ContentView: View {
_ = gateway.onAuthFailure.addHandler {
state.attemptLogin = true
state.loadingState = .initial
log.debug("User isn't logged in, attempting login")
log.debug("Attempting login")
}
_ = gateway.onEvent.addHandler { (evt, _) in
switch evt {
case .ready:
state.loadingState = .gatewayConn
fallthrough
case .resumed:
gateway.socket.send(op: .voiceStateUpdate, data: GatewayVoiceStateUpdate(
gateway.send(op: .voiceStateUpdate, data: GatewayVoiceStateUpdate(
guild_id: nil,
channel_id: nil,
self_mute: state.selfMute,
Expand All @@ -194,7 +195,7 @@ struct ContentView: View {
default: break
}
}
_ = gateway.socket.onSessionInvalid.addHandler { state.loadingState = .initial }
_ = gateway.socket?.onSessionInvalid.addHandler { state.loadingState = .initial }
}
}

Expand Down
9 changes: 1 addition & 8 deletions Swiftcord/Views/EnvObjects/UIStateEnv.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,9 @@ enum LoadingState {
case messageLoad
}

class UIState: ObservableObject, Equatable {
class UIState: ObservableObject {
@Published var loadingState: LoadingState = .initial
@Published var attemptLogin = false
@Published var selfMute = false
@Published var selfDeaf = false

static func == (lhs: UIState, rhs: UIState) -> Bool {
return lhs.loadingState == rhs.loadingState &&
lhs.attemptLogin == rhs.attemptLogin &&
lhs.selfMute == rhs.selfMute &&
lhs.selfDeaf == rhs.selfDeaf
}
}
2 changes: 1 addition & 1 deletion Swiftcord/Views/Message/AttachmentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import SwiftUI
import AVKit
import CachedAsyncImage
import QuickLook
import DiscordKit
import DiscordKitCommon

struct AttachmentError: View {
let height: Int
Expand Down
2 changes: 1 addition & 1 deletion Swiftcord/Views/Message/EmbedView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import SwiftUI
import CachedAsyncImage
import DiscordKit
import DiscordKitCommon

struct EmbedView: View {
let embed: Embed
Expand Down
Loading
0