aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Models/Hotline.swift
blob: b2a948909c8daa88e5c1271e0c4f0c7d0d19236a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import SwiftUI

enum NewsCategoryType {
  case bundle
  case category
}

@Observable class NewsCategory: Identifiable, Hashable {
  let id: UUID = UUID()
  
  let name: String
  let count: UInt16
  let type: NewsCategoryType
  
  init(hotlineNewsCategory: HotlineNewsCategory) {
    self.name = hotlineNewsCategory.name
    self.count = hotlineNewsCategory.count
    
    if hotlineNewsCategory.type == 2 {
      self.type = .bundle
    }
    else {
      self.type = .category
    }
  }
  
  func hash(into hasher: inout Hasher) {
    hasher.combine(self.id)
  }
  
  static func == (lhs: NewsCategory, rhs: NewsCategory) -> Bool {
    return lhs.id == rhs.id
  }
}

@Observable class FileInfo: Identifiable {
  let id: UUID = UUID()
  
  let path: [String]
  let name: String
  
  let type: String
  let creator: String
  let fileSize: UInt
  
  let isFolder: Bool
  var children: [FileInfo]? = nil
  
  init(hotlineFile: HotlineFile) {
    self.path = hotlineFile.path
    self.name = hotlineFile.name
    self.type = hotlineFile.type
    self.creator = hotlineFile.creator
    self.fileSize = UInt(hotlineFile.fileSize)
    self.isFolder = hotlineFile.isFolder
    if self.isFolder {
      self.children = []
    }
  }
  
  static func == (lhs: FileInfo, rhs: FileInfo) -> Bool {
    return lhs.id == rhs.id
  }
}

enum ChatMessageType {
  case agreement
  case status
  case message
  case server
}

struct ChatMessage: Identifiable {
  let id = UUID()
  
  let text: String
  let type: ChatMessageType
  let date: Date
  let username: String?
  
  static let parser = /^\s*([^\:]+)\:\s*(.+)/
  
  init(text: String, type: ChatMessageType, date: Date) {
    self.type = type
    self.date = date
    
    if
      type == .message,
      let match = text.firstMatch(of: ChatMessage.parser) {
      self.username = String(match.1)
      self.text = String(match.2)
    }
    else {
      self.username = nil
      self.text = text
    }
  }
}

struct UserStatus: OptionSet {
  let rawValue: Int

  static let idle = UserStatus(rawValue: 1 << 0)
  static let admin = UserStatus(rawValue: 1 << 1)
}

struct User: Identifiable {
  let id: UInt
  var name: String
  var iconID: UInt
  var status: UserStatus
  
  init(hotlineUser: HotlineUser) {
    var status: UserStatus = UserStatus()
    if hotlineUser.isIdle { status.update(with: .idle) }
    if hotlineUser.isAdmin { status.update(with: .admin) }
    
    self.id = UInt(hotlineUser.id)
    self.name = hotlineUser.name
    self.iconID = UInt(hotlineUser.iconID)
    self.status = status
  }
  
  init(id: UInt, name: String, iconID: UInt, status: UserStatus) {
    self.id = id
    self.name = name
    self.iconID = iconID
    self.status = status
  }
}

@Observable final class Hotline: HotlineClientDelegate {
  let trackerClient: HotlineTrackerClient
  let client: HotlineClient
  
  var status: HotlineClientStatus = .disconnected
  
  var server: Server? = nil
  var serverVersion: UInt16? = nil
  var username: String = "bolt"
  var iconID: UInt = 128
  
  var users: [User] = []
  var chat: [ChatMessage] = []
  var messageBoard: [String] = []
  var files: [FileInfo] = []
  var news: [NewsCategory] = []
  
  // MARK: -
  
  init(trackerClient: HotlineTrackerClient, client: HotlineClient) {
    self.trackerClient = trackerClient
    self.client = client
    self.client.delegate = self
  }
  
  // MARK: -
  
  @MainActor func getServers(address: String, port: Int = Tracker.defaultPort) async -> [Server] {
    let fetchedServers: [HotlineServer] = await self.trackerClient.fetchServers(address: address, port: port)
    
    var servers: [Server] = []
    
    for s in fetchedServers {
      if let serverName = s.name {
        servers.append(Server(name: serverName, description: s.description, address: s.address, port: Int(s.port), users: Int(s.users)))
      }
    }
    
    return servers
  }
  
  @MainActor func disconnectTracker() {
    self.trackerClient.disconnect()
  }
  
  @MainActor func login(server: Server, login: String, password: String, username: String, iconID: UInt) async -> Bool {
    self.server = server
    self.username = username
    self.iconID = iconID
    
    return await withCheckedContinuation { [weak self] continuation in
      let _ = self?.client.login(server.address, port: UInt16(server.port), login: login, password: password, username: username, iconID: UInt16(iconID)) { [weak self] err, serverVersion in
        self?.serverVersion = serverVersion
        continuation.resume(returning: (err != nil))
      }
    }
  }
  
  @MainActor func disconnect() {
    self.client.disconnect()
  }
  
  @MainActor func sendChat(_ text: String) {
    self.client.sendChat(message: text, sent: nil)
  }
  
  @MainActor func getMessageBoard() async -> [String] {
    self.messageBoard = await withCheckedContinuation { [weak self] continuation in
      self?.client.sendGetMessageBoard() { err, messages in
        continuation.resume(returning: (err != nil ? [] : messages))
      }
    }
    
    return self.messageBoard
  }
  
  @MainActor func getFileList(path: [String] = []) async -> [FileInfo] {
    return await withCheckedContinuation { [weak self] continuation in
      self?.client.sendGetFileList(path: path, sent: { success in
        if !success {
          continuation.resume(returning: [])
          return
        }
        // Failed to send?
      }, reply: { [weak self] files in
        let parentFile = self?.findFile(in: self?.files ?? [], at: path)
        
        var newFiles: [FileInfo] = []
        for f in files {
          newFiles.append(FileInfo(hotlineFile: f))
        }
        
        if let parent = parentFile {
          print("FOUND PARENT AT \(path)")
          parent.children = newFiles
        }
        else if path.isEmpty {
          print("FOUND ROOT AT \(path)")
          self?.files = newFiles
        }
        
        continuation.resume(returning: newFiles)
      })
    }
  }
  
  @MainActor func getNewsCategories() async -> [NewsCategory] {
    return await withCheckedContinuation { [weak self] continuation in
      self?.client.sendGetNewsCategories(sent: { success in
        if !success {
          continuation.resume(returning: [])
          return
        }
      }, reply: { [weak self] categories in
        var newCategories: [NewsCategory] = []
        for category in categories {
          newCategories.append(NewsCategory(hotlineNewsCategory: category))
        }
        self?.news = newCategories
        
        continuation.resume(returning: newCategories)
      })
    }
  }

  
//  @MainActor func updateUsers() async -> [User] {
//    let userList = await self.client.sendGetUserList()
//    var users = []
////    self.client.sendChat(message: text)
//    
//    return users
//  }
  
  // MARK: - Hotline Delegate
  
  func hotlineStatusChanged(status: HotlineClientStatus) {
    print("Hotline: Connection status changed to: \(status)")
    
    if status == .disconnected {
      self.serverVersion = nil
      self.users = []
      self.chat = []
      self.messageBoard = []
      self.files = []
      self.news = []
    }
    
    self.status = status
  }
  
  func hotlineGetUserInfo() -> (String, UInt16) {
    return (self.username, UInt16(self.iconID))
  }
  
  func hotlineReceivedAgreement(text: String) {
    self.chat.append(ChatMessage(text: text, type: .agreement, date: Date()))
  }
  
  func hotlineReceivedServerMessage(message: String) {
//    print("Hotline: received server message:\n\(message)")
//    self.chat.append(ChatMessage(text: message, type: .server, date: Date()))
  }
  
  func hotlineReceivedChatMessage(message: String) {
    self.chat.append(ChatMessage(text: message, type: .message, date: Date()))
  }
  
  func hotlineReceivedUserList(users: [HotlineUser]) {
    var existingUserIDs: [UInt] = []
    var userList: [User] = []
    
    print("GOT USER LIST", users)
    
    for u in users {
      if let i = self.users.firstIndex(where: { $0.id == u.id }) {
        // If a user is already in the user list we have to assume
        // they changed somehow before we received the user list
        // which means let's keep their existing info.
        existingUserIDs.append(UInt(u.id))
        userList.append(self.users[i])
      }
      else {
        userList.append(User(hotlineUser: u))
      }
    }
    
    if !existingUserIDs.isEmpty {
      self.users = self.users.filter { !existingUserIDs.contains($0.id) }
    }
    
    self.users = userList + self.users
  }
  
  func hotlineUserChanged(user: HotlineUser) {
    self.addOrUpdateHotlineUser(user)
  }
    
  func hotlineUserDisconnected(userID: UInt16) {
    if let existingUserIndex = self.users.firstIndex(where: { $0.id == UInt(userID) }) {
      let user = self.users.remove(at: existingUserIndex)
      self.chat.append(ChatMessage(text: "\(user.name) left", type: .status, date: Date()))
    }
  }
  
  func hotlineReceivedError(message: String) {
    
  }
  
  // MARK: - Utilities
  
  private func addOrUpdateHotlineUser(_ user: HotlineUser) {
    if let i = self.users.firstIndex(where: { $0.id == user.id }) {
      print("Hotline: updating user \(self.users[i].name)")
      self.users[i] = User(hotlineUser: user)
    }
    else {
      print("Hotline: added user: \(user.name)")
      self.users.append(User(hotlineUser: user))
      self.chat.append(ChatMessage(text: "\(user.name) joined", type: .status, date: Date()))
    }
  }
  
  private func findFile(in filesToSearch: [FileInfo], at path: [String]) -> FileInfo? {
    guard !path.isEmpty, !filesToSearch.isEmpty else { return nil }
    
    //    var stack: [([HotlineFile], [String])] = [(self.files!, path)]
    
    let currentName = path[0]
    
    for file in filesToSearch {
      if file.name == currentName {
        if path.count == 1 {
          return file
        }
        else if let subfiles = file.children {
          let remainingPath = Array(path[1...])
          return self.findFile(in: subfiles, at: remainingPath)
        }
      }
    }
    
    return nil
  }
}