summaryrefslogtreecommitdiff
path: root/Sora/Data/Booru/BooruManager.swift
blob: 3e94b567648ab286b672f1c00e63a6480b3935ea (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
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
// swiftlint:disable file_length

import Alamofire
import SwiftUI

@MainActor
class BooruManager: ObservableObject {  // swiftlint:disable:this type_body_length
  // MARK: - Published Properties
  @Published var posts: [BooruPost] = []
  @Published var isLoading = false
  @Published var currentPage = 1
  @Published var searchText = ""
  @Published var endOfData = false
  @Published var selectedPost: BooruPost?
  @Published var flavor: BooruProviderFlavor
  @Published var domain: String
  @Published private(set) var postIndexMap: [String: Int] = [:]
  @Published var provider: BooruProvider
  @Published var historyIndex: Int = -1
  @Published var searchHistory: [BooruSearchQuery] = []
  @Published var isNavigatingHistory = false
  @Published var error: Error?

  // MARK: - Private Properties
  private var currentTask: Task<Void, Never>?
  private let pageCache = NSCache<NSString, BooruPageCacheEntry>()  // swiftlint:disable:this legacy_objc_type
  private let cacheDuration: TimeInterval
  private let credentials: BooruProviderCredentials?
  private let userAgent: String
  private var urlCache: [String: URL] = [:]
  private var lastPostCount = 0
  private var xmlParserPool: [BooruPostXMLParser] = []
  private let parserPoolLock = NSLock()

  // MARK: - Computed Properties
  var tags: [String] {
    searchText.isEmpty
      ? []
      : searchText
        .components(separatedBy: .whitespaces)
        .filter { !$0.isEmpty }
  }
  var canGoBackInHistory: Bool { historyIndex > 0 }
  var canGoForwardInHistory: Bool { historyIndex < searchHistory.count - 1 }

  // MARK: - Initialisation
  init(
    _ provider: BooruProvider,
    credentials: BooruProviderCredentials? = nil,
    cacheDuration: TimeInterval = BooruPageCacheEntry.defaultExpiration
  ) {
    self.provider = provider
    self.flavor = BooruProviderFlavor(provider: provider)
    self.domain = provider.domain
    self.credentials = credentials
    self.cacheDuration = cacheDuration
    pageCache.countLimit = 50
    pageCache.totalCostLimit = 50 * 1_024 * 1_024

    let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0"
    let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "1"

    self.userAgent = "Sora/\(version) (Build \(buildNumber))"

    let rootQuery = BooruSearchQuery(
      provider: provider,
      tags: []
    )

    searchHistory.append(rootQuery)

    historyIndex = 0
  }

  // MARK: - Public Methods
  func fetchPosts(page: Int = 1, limit: Int = 100, tags: [String] = [], replace: Bool = false) async
  {
    guard !isLoading else { return }

    let pageValue = flavor == .gelbooru ? page - 1 : page
    guard let url = urlForPosts(page: pageValue, limit: limit, tags: tags) else { return }
    let cacheKey = "\(url.absoluteString.hashValue)_\(replace)" as NSString  // swiftlint:disable:this legacy_objc_type

    if let cachedEntry = pageCache.object(forKey: cacheKey),
      !cachedEntry.isExpired
    {
      isLoading = true

      defer { isLoading = false }

      updatePosts(cachedEntry.posts, replace: replace)

      return
    }

    isLoading = true

    defer { isLoading = false }

    let finalPosts = await fetchPostsWithRetry(url: url)

    if Task.isCancelled { return }

    let cacheEntry = BooruPageCacheEntry(
      posts: finalPosts,
      timestamp: Date(),
      expiration: cacheDuration
    )

    pageCache.setObject(cacheEntry, forKey: cacheKey, cost: finalPosts.count)

    withAnimation(nil) {
      updatePosts(finalPosts, replace: replace)
    }
  }

  private func fetchPostsWithRetry(url: URL) async -> [BooruPost] {
    let maxAttempts = 4

    for attempt in 1...maxAttempts {
      if Task.isCancelled { return [] }

      do {
        let data = try await requestURL(url)

        if Task.isCancelled { return [] }

        let flavor = self.flavor
        let provider = self.provider
        let newPosts = await withCheckedContinuation { continuation in
          DispatchQueue.global(qos: .userInitiated).async {
            let parsedPosts = Self.parsePosts(
              from: data,
              flavor: flavor,
              provider: provider
            )
            .sorted { $0.createdAt > $1.createdAt }

            continuation.resume(returning: parsedPosts)
          }
        }

        if Task.isCancelled { return [] }

        if !newPosts.isEmpty {
          return newPosts
        }

        if attempt < maxAttempts {
          try await Task.sleep(for: .seconds(0.5 * Double(attempt)))
        }
      } catch {
        if !Task.isCancelled {
          self.error = error

          debugPrint("BooruManager.fetchPosts(\(attempt)): \(error)")
        }

        break
      }
    }

    return []
  }

  func clearCachedPages() {
    pageCache.removeAllObjects()
    urlCache.removeAll()
  }

  func performSearch(settings: SettingsManager? = nil) async {
    let inputTags = tags

    guard !inputTags.isEmpty else { return }

    if searchHistory.last?.tags == inputTags { return }

    if historyIndex < searchHistory.count - 1 {
      searchHistory = Array(searchHistory[0...historyIndex])
    }

    let query = BooruSearchQuery(
      provider: settings?.preferredBooru ?? provider,
      tags: inputTags
    )

    searchHistory.append(query)

    historyIndex = searchHistory.count - 1

    settings?.appendToSearchHistory(query)

    searchText = inputTags.joined(separator: " ")

    await fetchPosts(page: 1, tags: inputTags, replace: true)
  }

  func loadNextPage() async {
    guard !isLoading else { return }

    currentPage += 1

    await fetchPosts(page: currentPage, tags: tags)

    if historyIndex >= 0 && historyIndex < searchHistory.count {
      var currentQuery = searchHistory[historyIndex]

      currentQuery.page = currentPage

      searchHistory[historyIndex] = currentQuery
    }
  }

  func goBackInHistory() {
    guard canGoBackInHistory else { return }

    isNavigatingHistory = true
    historyIndex -= 1

    let previousQuery = searchHistory[historyIndex]

    if previousQuery.provider != provider {
      provider = previousQuery.provider
      flavor = BooruProviderFlavor(provider: provider)
      domain = provider.domain
    }

    searchText = previousQuery.tags.joined(separator: " ")

    cancelCurrentTask()

    currentTask = Task {
      await fetchPosts(page: 1, tags: previousQuery.tags, replace: true)

      isNavigatingHistory = false
    }
  }

  func goForwardInHistory() {
    guard canGoForwardInHistory else { return }

    historyIndex += 1
    isNavigatingHistory = true

    let nextQuery = searchHistory[historyIndex]

    if nextQuery.provider != provider {
      provider = nextQuery.provider
      flavor = BooruProviderFlavor(provider: provider)
      domain = provider.domain
    }

    searchText = nextQuery.tags.joined(separator: " ")

    cancelCurrentTask()

    currentTask = Task {
      await fetchPosts(page: 1, tags: nextQuery.tags, replace: true)

      isNavigatingHistory = false
    }
  }

  func searchTags(name: String) async -> [BooruTag] {
    guard let url = urlForTagsSearch(name: name) else { return [] }

    do {
      let data = try await requestURL(url)

      guard !Task.isCancelled else { return [] }

      return BooruTagXMLParser(data: data).parse().sorted { $0.count > $1.count }
    } catch {
      if (error as? URLError)?.code != .cancelled {
        debugPrint("BooruManager.searchTags: \(error)")
      }

      return []
    }
  }

  // MARK: - Private Methods
  func urlForPosts(page: Int, limit: Int, tags: [String]) -> URL? {
    let tagString = tags.joined(separator: "+")
    let cacheKey = "posts_\(page)_\(limit)_\(tagString.hashValue)"

    if let cachedURL = urlCache[cacheKey] {
      return cachedURL
    }

    let url: URL?

    switch flavor {
    case .danbooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/posts.json"
      components.queryItems = [
        URLQueryItem(name: "page", value: String(page)),
        URLQueryItem(name: "tags", value: tagString),
      ]
      url = components.url

    case .moebooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/post.xml"
      components.queryItems = [
        URLQueryItem(name: "page", value: String(page)),
        URLQueryItem(name: "limit", value: String(limit)),
        URLQueryItem(name: "tags", value: tagString),
      ]
      url = components.url

    case .gelbooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/index.php"

      var queryItems = [
        URLQueryItem(name: "page", value: "dapi"),
        URLQueryItem(name: "s", value: "post"),
        URLQueryItem(name: "q", value: "index"),
        URLQueryItem(name: "pid", value: String(page)),
        URLQueryItem(name: "limit", value: String(limit)),
        URLQueryItem(name: "tags", value: tagString),
      ]

      if let validCredentials = credentials,
        !validCredentials.apiKey.isEmpty,
        validCredentials.userID != 0
      {
        queryItems.append(URLQueryItem(name: "api_key", value: validCredentials.apiKey))
        queryItems.append(URLQueryItem(name: "user_id", value: String(validCredentials.userID)))
      }

      components.queryItems = queryItems
      url = components.url
    }

    if let constructedURL = url {
      urlCache[cacheKey] = constructedURL
    }

    return url
  }

  private func urlForTags(limit: Int, order: String = "count") -> URL? {
    switch flavor {
    case .moebooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/tag.xml"
      components.queryItems = [
        URLQueryItem(name: "limit", value: String(limit)),
        URLQueryItem(name: "order", value: order),
      ]

      return components.url

    case .gelbooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/index.php"
      components.queryItems = [
        URLQueryItem(name: "page", value: "dapi"),
        URLQueryItem(name: "s", value: "tag"),
        URLQueryItem(name: "q", value: "index"),
        URLQueryItem(name: "limit", value: String(limit)),
        URLQueryItem(name: "orderby", value: order),
      ]

      return components.url

    case .danbooru:
      return nil
    }
  }

  private func urlForTagsSearch(name: String) -> URL? {
    switch flavor {
    case .moebooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/tag.xml"
      components.queryItems = [
        URLQueryItem(name: "name_pattern", value: name),
        URLQueryItem(name: "order", value: "count"),
      ]

      return components.url

    case .gelbooru:
      var components = URLComponents()

      components.scheme = "https"
      components.host = domain
      components.path = "/index.php"

      var queryItems = [
        URLQueryItem(name: "page", value: "dapi"),
        URLQueryItem(name: "s", value: "tag"),
        URLQueryItem(name: "q", value: "index"),
        URLQueryItem(name: "name_pattern", value: "%\(name)%"),
        URLQueryItem(name: "orderby", value: "count"),
      ]

      if let validCredentials = credentials,
        !validCredentials.apiKey.isEmpty,
        validCredentials.userID != 0
      {
        queryItems.append(URLQueryItem(name: "api_key", value: validCredentials.apiKey))
        queryItems.append(URLQueryItem(name: "user_id", value: String(validCredentials.userID)))
      }

      components.queryItems = queryItems

      return components.url

    case .danbooru:
      return nil
    }
  }

  nonisolated static func parsePosts(
    from data: Data,
    flavor: BooruProviderFlavor,
    provider: BooruProvider
  ) -> [BooruPost] {
    let parsedPosts =
      flavor == .danbooru
      ? DanbooruPostParser(data: data).parse()
      : BooruPostXMLParser(data: data, provider: provider).parse()
    var uniquePosts: [String: BooruPost] = [:]

    for post in parsedPosts {
      uniquePosts[post.id] = post
    }

    return Array(uniquePosts.values)
  }

  private func getXMLParser(for provider: BooruProvider) -> BooruPostXMLParser {
    parserPoolLock.lock()

    defer { parserPoolLock.unlock() }

    if let parser = xmlParserPool.popLast() {
      return parser
    }

    return BooruPostXMLParser(data: Data(), provider: provider)
  }

  private func returnXMLParser(_ parser: BooruPostXMLParser) {
    parserPoolLock.lock()

    defer { parserPoolLock.unlock() }

    if xmlParserPool.count < 3 {
      xmlParserPool.append(parser)
    }
  }

  private func updatePosts(_ newPosts: [BooruPost], replace: Bool) {
    if replace {
      posts = []
      currentPage = 1

      postIndexMap.removeAll()

      lastPostCount = 0
    }

    endOfData = newPosts.isEmpty

    guard !endOfData else { return }

    withTransaction(Transaction(animation: nil)) {
      let oldCount = self.posts.count

      self.posts += newPosts

      if newPosts.count > 10 || self.posts.count - lastPostCount > 50 {
        for (offset, post) in newPosts.enumerated() {
          self.postIndexMap[post.id] = oldCount + offset
        }

        lastPostCount = self.posts.count
      }
    }
  }

  func requestURL(_ url: URL) async throws -> Data {
    try await AF.request(url, headers: ["User-Agent": userAgent])
      .serializingData()
      .value
  }

  private func cancelCurrentTask() {
    currentTask?.cancel()

    currentTask = nil
  }

  // MARK: - Deinitialisation
  nonisolated deinit {
    currentTask?.cancel()
    urlCache.removeAll()
  }
}