Skip to content

Commit

Permalink
fix: main thread checking
Browse files Browse the repository at this point in the history
ref: serverlistview modularizing
  • Loading branch information
tealbathingsuit committed May 18, 2022
1 parent e3f1f8e commit 3f53369
Show file tree
Hide file tree
Showing 17 changed files with 212 additions and 121 deletions.
5 changes: 5 additions & 0 deletions .periphery.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
project: Accord.xcodeproj
schemes:
- Accord
targets:
- Accord
8 changes: 8 additions & 0 deletions Accord.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
9E8F8CA82774037F00A77600 /* MentionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E8F8CA72774037F00A77600 /* MentionsView.swift */; };
9E96EB7A27DEC33D00BB3C8A /* Gateway+VoiceState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E96EB7927DEC33D00BB3C8A /* Gateway+VoiceState.swift */; };
9EA295212753D1490014927D /* MemberList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EA295202753D1480014927D /* MemberList.swift */; };
9EB3303828344929007D38EF /* PrivateChannelsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EB3303728344929007D38EF /* PrivateChannelsView.swift */; };
9EB3303A28344A10007D38EF /* DMButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EB3303928344A10007D38EF /* DMButton.swift */; };
9EB3582427BFFD3E0046A136 /* Collection++.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EB3582327BFFD3E0046A136 /* Collection++.swift */; };
9ECB0F3F2766D3DA0019ADAE /* MessageCellView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ECB0F3E2766D3DA0019ADAE /* MessageCellView.swift */; };
9ECE08F5277286E3001BA0F7 /* PinsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ECE08F4277286E3001BA0F7 /* PinsView.swift */; };
Expand Down Expand Up @@ -171,6 +173,8 @@
9E8F8CA72774037F00A77600 /* MentionsView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MentionsView.swift; sourceTree = "<group>"; };
9E96EB7927DEC33D00BB3C8A /* Gateway+VoiceState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Gateway+VoiceState.swift"; sourceTree = "<group>"; };
9EA295202753D1480014927D /* MemberList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemberList.swift; sourceTree = "<group>"; };
9EB3303728344929007D38EF /* PrivateChannelsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateChannelsView.swift; sourceTree = "<group>"; };
9EB3303928344A10007D38EF /* DMButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DMButton.swift; sourceTree = "<group>"; };
9EB3582327BFFD3E0046A136 /* Collection++.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Collection++.swift"; sourceTree = "<group>"; };
9ECB0F3E2766D3DA0019ADAE /* MessageCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageCellView.swift; sourceTree = "<group>"; };
9ECE08F4277286E3001BA0F7 /* PinsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PinsView.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -539,6 +543,8 @@
370AF4112834504C0055AA1D /* JoinServerSheetView.swift */,
9E82874E27BB522600953A7B /* ServerListView+Init.swift */,
9E3B48DA280C348E00B131B7 /* ServerListViewCell.swift */,
9EB3303728344929007D38EF /* PrivateChannelsView.swift */,
9EB3303928344A10007D38EF /* DMButton.swift */,
);
path = Base;
sourceTree = "<group>";
Expand Down Expand Up @@ -715,6 +721,7 @@
A82A062426D98259007B9B27 /* ReadState.swift in Sources */,
A8B1F29826CB166C00E8FDC5 /* Events.swift in Sources */,
A89BE786266BDFB3007B0CBF /* Socket.swift in Sources */,
9EB3303828344929007D38EF /* PrivateChannelsView.swift in Sources */,
9E7834D22781F2D500ABB9F8 /* Combine++.swift in Sources */,
A8C73D1226F5812D00CF0350 /* Songlink.swift in Sources */,
9E7BC56D27472317008E3FAB /* Markdown.swift in Sources */,
Expand Down Expand Up @@ -781,6 +788,7 @@
A8CD4CA5267D27F300E2C4F1 /* ServerListView.swift in Sources */,
9EB3582427BFFD3E0046A136 /* Collection++.swift in Sources */,
9E7E4D30279B69D7008FAF15 /* Storage.swift in Sources */,
9EB3303A28344A10007D38EF /* DMButton.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
66 changes: 38 additions & 28 deletions Accord/App/AccordApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,22 @@ import Foundation
import SwiftUI
import UserNotifications

var reachability: Reachability?
var reachability: Reachability? = {
var reachability = try? Reachability()
reachability?.whenReachable = { status in
print("reconnecting reachable")
concurrentQueue.async {
if wss?.connection?.state != .preparing {
wss?.reset()
}
}
}
reachability?.whenUnreachable = {
print($0, "unreachable")
}
try? reachability?.startNotifier()
return reachability
}()

@main
struct AccordApp: App {
Expand All @@ -23,6 +38,10 @@ struct AccordApp: App {
case general, rpc
}

init() {
_ = reachability
}

@SceneBuilder
var body: some Scene {
WindowGroup {
Expand Down Expand Up @@ -62,23 +81,24 @@ struct AccordApp: App {
// DispatchQueue(label: "socket").async {
// let rpc = IPC().start()
// }
Request.fetch(url: URL(string: "https://accounts.spotify.com/api/token"), headers: Headers(
contentType: "application/x-www-form-urlencoded",
token: "Basic " + ("b5d5657a93c248a88b83c630a4488a78" + ":" + "faa98c11d92e493689fd797761bc1849").toBase64(),
bodyObject: ["grant_type":"client_credentials"],
type: .POST
)) {
switch $0 {
case .success(let data):
let packet = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
if let token = packet?["access_token"] as? String {
spotifyToken = token

DispatchQueue.global().async {
Request.fetch(url: URL(string: "https://accounts.spotify.com/api/token"), headers: Headers(
contentType: "application/x-www-form-urlencoded",
token: "Basic " + ("b5d5657a93c248a88b83c630a4488a78" + ":" + "faa98c11d92e493689fd797761bc1849").toBase64(),
bodyObject: ["grant_type":"client_credentials"],
type: .POST
)) {
switch $0 {
case .success(let data):
let packet = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
if let token = packet?["access_token"] as? String {
spotifyToken = token
}
case .failure(let error):
print(error)
}
case .failure(let error):
print(error)
}
}
DispatchQueue.global().async {
NetworkCore.shared = NetworkCore()
}
DispatchQueue.global(qos: .background).async {
Expand Down Expand Up @@ -176,18 +196,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}

func applicationDidFinishLaunching(_: Notification) {

reachability = try? Reachability()
reachability?.whenReachable = { status in
print("reconnecting reachable")
concurrentQueue.async {
wss?.reset()
}
}
reachability?.whenUnreachable = {
print($0, "unreachable")
}
try? reachability?.startNotifier()
NSApp.dockTile.badgeLabel = nil
NSApp.dockTile.showsApplicationBadge = false

guard UserDefaults.standard.bool(forKey: "MentionsMenuBarItemEnabled") else { return }

Expand Down
2 changes: 1 addition & 1 deletion Accord/Backend/Markdown/AsyncMarkdown.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ extension View {

struct AsyncMarkdown: View, Equatable {
static func == (_ lhs: AsyncMarkdown, _ rhs: AsyncMarkdown) -> Bool {
lhs.model.markdown == rhs.model.markdown
lhs.text == rhs.text
}

@StateObject var model: AsyncMarkdownModel
Expand Down
2 changes: 1 addition & 1 deletion Accord/Backend/RPC/MediaRemoteWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ final class MediaRemoteWrapper {
class func getCurrentlyPlayingSong() -> Future<Song, Error> {
Future { promise in
// Get song info
MRMediaRemoteGetNowPlayingInfo(DispatchQueue.main) { information in
MRMediaRemoteGetNowPlayingInfo(DispatchQueue.global()) { information in
guard let name = information["kMRMediaRemoteNowPlayingInfoTitle"] as? String else { return promise(.failure(NowPlayingErrors.noName)) }
let isMusic = information["kMRMediaRemoteNowPlayingInfoIsMusicApp"] as? Bool ?? false
let timestamp = information["kMRMediaRemoteNowPlayingInfoTimestamp"] as? String
Expand Down
5 changes: 5 additions & 0 deletions Accord/Misc/PlusPlus/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import Combine
import Foundation
import SwiftUI

// thanks osy
extension String: Error {
var localizedString: String { self }
}

public var doNothing: (Any) -> Void = { _ in }

@propertyWrapper
Expand Down
4 changes: 2 additions & 2 deletions Accord/Objects/DiscordTypes/ReadState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class ReadState: Decodable {
}

class ReadStateEntry: Decodable, Identifiable {
var mention_count: Int
var last_pin_timestamp: String
var mention_count: Int?
var last_pin_timestamp: String?
var last_message_id: String?
var id: String // Channel ID
}
60 changes: 60 additions & 0 deletions Accord/UI/Base/DMButton.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//
// DMButton.swift
// Accord
//
// Created by evelyn on 2022-05-17.
//

import SwiftUI

struct DMButton: View {
@Binding var selection: Int?
@Binding var selectedServer: Int?
@StateObject var updater: ServerListView.UpdateView
@State var mentionCount: Int?
@State var iconHovered: Bool = false
var body: some View {
ZStack(alignment: .bottomTrailing) {
Button(action: {
selection = nil
DispatchQueue.global().async {
wss?.cachedMemberRequest.removeAll()
ServerListView.privateChannels = ServerListView.privateChannels.sorted(by: { $0.last_message_id ?? "" > $1.last_message_id ?? "" })
}
selectedServer = 201
let prevSelection = selection
if let selectionPrevious = UserDefaults.standard.object(forKey: "AccordChannelDMs") as? Int {
self.selection = selectionPrevious
}
if let selection = prevSelection {
UserDefaults.standard.set(selection, forKey: "AccordChannelDMs")
}
}) {
Image(systemName: "bubble.right.fill")
.imageScale(.medium)
.frame(width: 45, height: 45)
.background(selectedServer == 201 ? Color.accentColor.opacity(0.5) : Color(NSColor.windowBackgroundColor))
.cornerRadius(iconHovered || selectedServer == 201 ? 13.5 : 23.5)
.if(selectedServer == 201, transform: { $0.foregroundColor(Color.white) })
.onHover(perform: { h in withAnimation(Animation.linear(duration: 0.1)) { self.iconHovered = h } })
}
if let mentionCount = mentionCount, mentionCount != 0 {
ZStack {
Circle()
.foregroundColor(Color.red)
.frame(width: 15, height: 15)
Text(String(mentionCount))
.foregroundColor(Color.white)
.fontWeight(.semibold)
.font(.caption)
}
}
}
.buttonStyle(BorderlessButtonStyle())
.onReceive(self.updater.$updater, perform: { _ in
DispatchQueue.global().async {
self.mentionCount = ServerListView.privateChannels.compactMap({ $0.read_state?.mention_count }).reduce(0, +)
}
})
}
}
18 changes: 6 additions & 12 deletions Accord/UI/Base/FolderListView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,28 +62,22 @@ struct ServerIconCell: View {

func updateSelection(old: Int?, new: Int?) {
DispatchQueue.global().async {
if old == 201 {
if let selection = selection {
UserDefaults.standard.set(selection, forKey: "AccordChannelDMs")
}
if let selection = selection, old == 201 {
UserDefaults.standard.set(selection, forKey: "AccordChannelDMs")
}
let map = Array(ServerListView.folders.compactMap { $0.guilds }.joined())
guard let selectedServer = old,
let new = new,
let newID = map[safe: new]?.id else {
DispatchQueue.main.async {
guard let new = new else {
return DispatchQueue.main.async {
self.selectedServer = new
self.selectedGuild = guild
}
return
}
if let selection = selection, let id = map[safe: selectedServer]?.id {
if let selection = selection, let id = selectedGuild?.id {
UserDefaults.standard.set(selection, forKey: "AccordChannelIn\(id)")
}
DispatchQueue.main.async {
self.selection = nil
withAnimation(old == 201 ? nil : Animation.linear(duration: 0.1)) {
if let value = UserDefaults.standard.object(forKey: "AccordChannelIn\(newID)") as? Int {
if let value = UserDefaults.standard.object(forKey: "AccordChannelIn\(guild.id)") as? Int {
self.selection = value
self.selectedGuild = guild
self.selectedServer = new
Expand Down
59 changes: 59 additions & 0 deletions Accord/UI/Base/PrivateChannelsView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//
// PrivateChannelsView.swift
// Accord
//
// Created by evelyn on 2022-05-17.
//

import SwiftUI

struct PrivateChannelsView: View {
var privateChannels: [Channel]
@Binding var selection: Int?
@StateObject var viewUpdater: ServerListView.UpdateView
var body: some View {
ForEach(privateChannels, id: \.id) { channel in
NavigationLink(destination: NavigationLazyView(ChannelView(channel).equatable()), tag: Int(channel.id) ?? 0, selection: self.$selection) {
ServerListViewCell(channel: channel, updater: self.viewUpdater)
.onChange(of: self.selection, perform: { [selection] new in
if new == Int(channel.id) {
channel.read_state?.mention_count = 0
channel.read_state?.last_message_id = channel.last_message_id
viewUpdater.updateView()
} else if selection == Int(channel.id) {
print("wow")
channel.read_state?.mention_count = 0
channel.read_state?.last_message_id = channel.last_message_id
}
})
}
.contextMenu {
Button("Copy Channel ID") {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(channel.id, forType: .string)
}
Button("Close DM") {
let headers = Headers(
userAgent: discordUserAgent,
contentType: nil,
token: AccordCoreVars.token,
type: .DELETE,
discordHeaders: true,
referer: "https://discord.com/channels/@me",
empty: true
)
Request.ping(url: URL(string: "\(rootURL)/channels/\(channel.id)"), headers: headers)
guard let index = ServerListView.privateChannels[indexOf: channel.id] else { return }
ServerListView.privateChannels.remove(at: index)
}
Button("Mark as read") {
channel.read_state?.mention_count = 0
channel.read_state?.last_message_id = channel.last_message_id
}
Button("Open in new window") {
showWindow(channel)
}
}
}
}
}
4 changes: 2 additions & 2 deletions Accord/UI/Base/ServerListView+Mentions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ extension ServerListView: MentionSenderDelegate {
if guild == "@me" {
guard channel != String(self.selection ?? 0) else { print("currently reading already"); return }
guard let index = Self.privateChannels.generateKeyMap()[channel] else { return }
Self.privateChannels[index].read_state?.mention_count += 1
Self.privateChannels[index].read_state?.mention_count? += 1
}
guard channel != String(self.selection ?? 0) else { print("currently reading already"); return }
let index = Self.folders.map { ServerListView.fastIndexGuild(guild, array: $0.guilds) }
for (i, v) in index.enumerated() {
guard let v = v, var folderList = Self.folders[i].guilds[v].channels else { continue }
folderList.append(contentsOf: Self.privateChannels)
if let index = fastIndexChannels(channel, array: folderList) {
Self.folders[i].guilds[v].channels?[index].read_state?.mention_count += 1
Self.folders[i].guilds[v].channels?[index].read_state?.mention_count? += 1
}
}
DispatchQueue.main.async {
Expand Down
Loading

0 comments on commit 3f53369

Please sign in to comment.