aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Models/Hotline.swift
blob: 6aafdfea106d08bdb78169eee8ee6476d5e23dbf (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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
import SwiftUI

@Observable final class Hotline: HotlineClientDelegate {
  let trackerClient: HotlineTrackerClient
  let client: HotlineClient
  
  static let defaultIconSet: [Int: String] = [
    414: "๐Ÿ™‚",
    2000: "๐Ÿ“Ÿ",
    2001: "๐Ÿ’€",
    2002: "๐Ÿชฉ",
    2003: "๐Ÿ’ฅ",
    2004: "๐Ÿž",
    2014: "๐ŸŽ",
    2006: "๐Ÿ’ ",
    2007: "๐Ÿฆ ",
    2008: "๐Ÿช€",
    2009: "๐Ÿ›Ÿ",
    2010: "๐Ÿ‰",
    2011: "๐Ÿ",
    2012: "๐Ÿšฆ",
    145: "๐Ÿš”",
    2015: "๐Ÿ‘ป",
    2016: "๐Ÿ’ป",
    2017: "โ˜€๏ธ",
    2018: "โžก๏ธ",
    417: "๐Ÿงโ€โ™‚๏ธ",
    140: "๐ŸŽจ",
    141: "๐Ÿ‘ฝ",
    142: "๐Ÿš€",
    143: "๐Ÿ•ท๏ธ",
    138: "๐Ÿ˜บ",
    146: "๐ŸŒ…",
    149: "๐Ÿฎ",
    150: "๐Ÿฆ–",
    151: "๐Ÿงป",
    154: "๐Ÿ–",
    182: "โœ‹",
    207: "โš ๏ธ",
    2061: "โ˜•๏ธ",
    2063: "๐ŸŒฎ",
    2064: "๐Ÿ•",
    2065: "๐Ÿ”",
    2066: "๐ŸŒญ",
    2067: "๐Ÿญ",
    2013: "๐Ÿง",
    2037: "โš ๏ธ",
    2055: "โšก๏ธ",
    2400: "๐Ÿ‡จ๐Ÿ‡ฆ",
    2036: "โ˜ฃ๏ธ",
    4134: "๐Ÿฆˆ",
    4247: "๐Ÿ—",
    135: "โ˜ฏ๏ธ",
    137: "๐Ÿ",
    144: "๐Ÿš€",
    165: "๐ŸŽถ",
    166: "โค๏ธ",
    2549: "๐Ÿ‡ฎ๐Ÿ‡ฑ",
    2553: "๐Ÿ‡บ๐Ÿ‡ธ",
    2555: "๐Ÿ‡จ๐Ÿ‡ฆ",
    2552: "๐Ÿ‡ฎ๐Ÿ‡ณ",
    2556: "๐Ÿ‡ฆ๐Ÿ‡บ",
    2565: "๐Ÿ‡ฌ๐Ÿ‡ง",
    2567: "๐Ÿ‡ฏ๐Ÿ‡ต",
    2566: "๐Ÿ‡ซ๐Ÿ‡ท",
    2564: "๐Ÿ‡ฉ๐Ÿ‡ช",
    2563: "๐Ÿ‡ฎ๐Ÿ‡น",
    2550: "๐Ÿ‡ญ๐Ÿ‡บ",
    2551: "๐Ÿ‡ต๐Ÿ‡ฑ",
    2560: "๐Ÿ‡ช๐Ÿ‡ธ",
    2561: "๐Ÿ‡ธ๐Ÿ‡ช",
  ]
  
//  @AppStorage("username") private var username: String = "guest"
//  @AppStorage("refuse private messages") private var refusePrivateMessages = false
//  @AppStorage("refuse private chat") private var refusePrivateChat = false
//  @AppStorage("enable automatic response") private var enableAutomaticResponse = false
//  @AppStorage("automatic response") private var automaticResponse = ""
  
  var status: HotlineClientStatus = .disconnected
  
  var server: Server?  {
    didSet {
      self.updateServerTitle()
    }
  }
  var serverVersion: UInt16?  {
    didSet {
      self.updateServerTitle()
    }
  }
  var serverName: String? {
    didSet {
      self.updateServerTitle()
    }
  }
  var serverTitle: String = "Server"
  var username: String = "guest"
  var iconID: Int = 414
  var access: HotlineUserAccessOptions?
  var agreed: Bool = false
  
  var users: [User] = []
  var chat: [ChatMessage] = []
  var messageBoard: [String] = []
  var messageBoardLoaded: Bool = false
  var files: [FileInfo] = []
  var filesLoaded: Bool = false
  var news: [NewsInfo] = []
  var newsLoaded: Bool = false
  
  var downloads: [HotlineFileClient] = []
  
  @ObservationIgnored var bannerClient: HotlineFileClient?
  #if os(macOS)
  var bannerImage: NSImage? = nil
  #elseif os(iOS)
  var bannerImage: UIImage? = nil
  #endif
  
  
  // MARK: -
  
  init(trackerClient: HotlineTrackerClient, client: HotlineClient) {
    self.trackerClient = trackerClient
    self.client = client
    self.client.delegate = self
  }
  
  // MARK: -
  
  @MainActor func getServerList(tracker: String, port: Int = Tracker.defaultPort) async -> [Server] {
    let fetchedServers: [HotlineServer] = await self.trackerClient.fetchServers(address: tracker, 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: Int, callback: ((Bool) -> Void)? = nil) {
    self.server = server
    self.serverName = server.name
    self.username = username
    self.iconID = iconID
    
    self.client.login(server.address, port: UInt16(server.port), login: login, password: password, username: username, iconID: UInt16(iconID)) { [weak self] err, serverName, serverVersion in
      self?.serverVersion = serverVersion
      if serverName != nil {
        self?.serverName = serverName
      }
      
      callback?(err == nil)
    }
  }
  
  @MainActor func sendUserInfo(username: String, iconID: Int, options: HotlineUserOptions = [], autoresponse: String? = nil, callback: ((Bool) -> Void)? = nil) {
    self.username = username
    self.iconID = iconID
    
    self.client.sendSetClientUserInfo(username: username, iconID: UInt16(iconID), options: options, autoresponse: autoresponse) { success in
      callback?(success)
    }
  }
  
  @MainActor func getUserList(callback: ((Bool) -> Void)? = nil) {
    self.client.sendGetUserList() { success in
      callback?(success)
    }
  }
  
  @MainActor func disconnect() {
    self.client.disconnect()
    self.bannerClient?.disconnect()
  }
  
  @MainActor func sendAgree() {
    self.client.sendAgree(username: self.username, iconID: UInt16(self.iconID), options: .none)
  }
  
  @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))
      }
    }
    
    self.messageBoardLoaded = true
    
    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
        }
      }, 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))
        }
        
        DispatchQueue.main.async {
          if let parent = parentFile {
            parent.children = newFiles
          }
          else if path.isEmpty {
            self?.filesLoaded = true
            self?.files = newFiles
          }
          
          continuation.resume(returning: newFiles)
        }
      })
    }
  }
  
  @MainActor func getNewsArticle(id articleID: UInt, at path: [String], flavor: String) async -> String? {
    return await withCheckedContinuation { [weak self] continuation in
      self?.client.sendGetNewsArticle(id: UInt32(articleID), path: path, flavor: flavor, sent: { success in
        if !success {
          continuation.resume(returning: nil)
          return
        }
        
        print("GET NEWS CATS FROM \(path)")
      }, reply: { articleText in
//          let parentNews = self?.findNews(in: self?.news ?? [], at: path)
        
//        var newCategories: [NewsInfo] = []
//        for category in categories {
//          newCategories.append(NewsInfo(hotlineNewsCategory: category))
//        }
//        
//        if let parent = existingNewsItem {
//          parent.children = newCategories
//        }
//        else if path.isEmpty {
//          self?.news = newCategories
//        }
        
        continuation.resume(returning: articleText)
      })
    }
    
  }
  
  @MainActor func getNewsList(at path: [String] = []) async -> [NewsInfo] {
    return await withCheckedContinuation { [weak self] continuation in
      var requestCategories = true
      
      let existingNewsItem = self?.findNews(in: self?.news ?? [], at: path)
      
      if existingNewsItem != nil {
        if existingNewsItem!.type != .bundle {
          requestCategories = false
        }
      }
      
      if requestCategories {
        self?.client.sendGetNewsCategories(path: path, sent: { success in
          if !success {
            continuation.resume(returning: [])
            return
          }
          
          print("GET NEWS CATS FROM \(path)")
        }, reply: { [weak self] categories in
//          let parentNews = self?.findNews(in: self?.news ?? [], at: path)
          
          var newCategories: [NewsInfo] = []
          for category in categories {
            newCategories.append(NewsInfo(hotlineNewsCategory: category))
          }
          
          DispatchQueue.main.async {
            if let parent = existingNewsItem {
              parent.children = newCategories
            }
            else if path.isEmpty {
              self?.newsLoaded = true
              self?.news = newCategories
            }
            
            continuation.resume(returning: newCategories)
          }
        })
      }
      else {
        self?.client.sendGetNewsArticles(path: path, sent: { success in
          if !success {
            DispatchQueue.main.async {
              continuation.resume(returning: [])
            }
            return
          }
          
          print("GET NEWS ARTICLES FROM \(path)")
        }, reply: { [weak self] articles in
//          let parentNews = self?.findNews(in: self?.news ?? [], at: path)
          print("GENERATING NEWS")
          
          var newArticles: [NewsInfo] = []
          for article in articles {
            newArticles.append(NewsInfo(hotlineNewsArticle: article))
          }
          
          DispatchQueue.main.async {
            if let parent = existingNewsItem {
              print("UNDER PARENT:", parent.name)
              parent.children = newArticles
              
              print(parent.children)
            }
            else if path.isEmpty {
              self?.news = newArticles
            }
            
            continuation.resume(returning: newArticles)
          }
        })
      }
    }
  }
  
  @MainActor func getNewsCategories(at path: [String] = []) async -> [NewsInfo] {
    return await withCheckedContinuation { [weak self] continuation in
      self?.client.sendGetNewsCategories(path: path, sent: { success in
        if !success {
          DispatchQueue.main.async {
            continuation.resume(returning: [])
          }
          return
        }
        
        print("GET NEWS CATS FROM \(path)")
      }, reply: { [weak self] categories in
        let parentNews = self?.findNews(in: self?.news ?? [], at: path)
        
        var newCategories: [NewsInfo] = []
        for category in categories {
          newCategories.append(NewsInfo(hotlineNewsCategory: category))
        }
        
        DispatchQueue.main.async {
          if let parent = parentNews {
            parent.children = newCategories
          }
          else if path.isEmpty {
            self?.news = newCategories
          }
          
          continuation.resume(returning: newCategories)
        }
      })
    }
  }
  
  @MainActor func getArticles(at path: [String]) async -> [NewsInfo] {
    return await withCheckedContinuation { [weak self] continuation in
      self?.client.sendGetNewsArticles(path: path, sent: { success in
        if !success {
          DispatchQueue.main.async {
            continuation.resume(returning: [])
          }
          return
        }
      }, reply: { articles in
        DispatchQueue.main.async {
          continuation.resume(returning: [])
        }
      })
    }
  }
  
  func downloadFile(path: [String], callback: ((Bool) -> Void)?) {
    
  }
  
  @MainActor func downloadBanner(force: Bool = false, callback: ((Bool) -> Void)?) {
    if let b = self.bannerClient {
      b.disconnect()
      self.bannerClient = nil
    }
    
    if force {
      self.bannerImage = nil
    }
    
    if self.bannerImage != nil {
      callback?(true)
      return
    }
    
    self.client.sendDownloadBanner(sent: { success in
      if !success {
        print("FAIL BANNER")
        callback?(false)
        return
      }
    }, reply: { [weak self] downloadReferenceNumber, downloadTransferSize in
      if
        let self = self,
        let address = self.server?.address,
        let port = self.server?.port,
        let referenceNumber = downloadReferenceNumber,
        let transferSize = downloadTransferSize {
        self.bannerClient = HotlineFileClient(address: address, port: UInt16(port), reference: referenceNumber, size: UInt32(transferSize), type: .banner)
        self.bannerClient?.downloadToMemory({ [weak self] data in
          if let b = self?.bannerClient {
            b.disconnect()
            self?.bannerClient = nil
          }
          
          if data != nil {
            #if os(macOS)
            self?.bannerImage = NSImage(data: data!)
            #elseif os(iOS)
            self?.bannerImage = UIImage(data: data!)
            #endif
          }
          
          callback?(data != nil)
        })
      }
    })
  }
  
  // MARK: - Hotline Delegate
  
  func hotlineStatusChanged(status: HotlineClientStatus) {
    print("Hotline: Connection status changed to: \(status)")
    
    if status == .disconnected {
      self.serverVersion = nil
      self.serverName = nil
      self.access = nil
      
      self.users = []
      self.chat = []
      self.messageBoard = []
      self.messageBoardLoaded = false
      self.files = []
      self.filesLoaded = false
      self.news = []
      self.newsLoaded = false
      
      self.bannerImage = nil
      
      if let b = self.bannerClient {
        b.disconnect()
        self.bannerClient = nil
      }
    }
    
    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 hotlineReceivedUserAccess(options: HotlineUserAccessOptions) {
    print("Hotline: got access options")
    print(options, options.contains(.canSendChat), options.contains(.canBroadcast))
    
    self.access = options
  }
  
  func hotlineReceivedError(message: String) {
    
  }
  
  // MARK: - Utilities
  
  func updateServerTitle() {
    self.serverTitle = self.serverName ?? self.server?.name ?? server?.address ?? "Server"
  }
  
  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 }
    
    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
  }
  
  private func findNews(in newsToSearch: [NewsInfo], at path: [String]) -> NewsInfo? {
    guard !path.isEmpty, !newsToSearch.isEmpty else { return nil }
    
    let currentName = path[0]
    
    for news in newsToSearch {
      if news.name == currentName {
        if path.count == 1 {
          return news
        }
        else if !news.children.isEmpty {
          let remainingPath = Array(path[1...])
          return self.findNews(in: news.children, at: remainingPath)
        }
      }
    }
    
    return nil
  }
}