summaryrefslogtreecommitdiff
path: root/Sora/Data/Booru/Provider/BooruProviderCredentials.swift
blob: 67334059292dcfedd6239bfd78e4f1bf8e3eef9a (plain) (blame)
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
import Foundation

struct BooruProviderCredentials: Codable, Identifiable, Equatable {
  let id: UUID
  let provider: BooruProvider
  var apiKey: String
  var userID: Int
  var login: String

  init(
    provider: BooruProvider,
    apiKey: String,
    userID: Int,
    login: String = "",
    id: UUID = UUID()
  ) {
    self.id = id
    self.provider = provider
    self.apiKey = apiKey
    self.userID = userID
    self.login = login
  }

  // swiftlint:disable explicit_enum_raw_value
  private enum CodingKeys: String, CodingKey {
    case id
    case provider
    case apiKey
    case userID
    case login
  }
  // swiftlint:enable explicit_enum_raw_value

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
    provider = try container.decode(BooruProvider.self, forKey: .provider)
    apiKey = try container.decodeIfPresent(String.self, forKey: .apiKey) ?? ""
    userID = try container.decodeIfPresent(Int.self, forKey: .userID) ?? 0
    login = try container.decodeIfPresent(String.self, forKey: .login) ?? ""
  }

  static func from(
    // swiftlint:disable:next large_tuple
    _ rawCredentials: [(provider: BooruProvider, apiKey: String, userID: Int, login: String)],
    existingCredentials: [Self]
  ) -> [Self] {
    rawCredentials.map { credentials in
      if let existingKey = existingCredentials.first(
        where: { $0.provider == credentials.provider }
      ) {
        return Self(
          provider: credentials.provider,
          apiKey: credentials.apiKey,
          userID: credentials.userID,
          login: credentials.login,
          id: existingKey.id
        )
      }

      return Self(
        provider: credentials.provider,
        apiKey: credentials.apiKey,
        userID: credentials.userID,
        login: credentials.login
      )
    }
  }
}