summaryrefslogtreecommitdiff
path: root/Sora/Views/Post/Details/PostDetailsImageView.swift
blob: 1e0da7207e38613ac0667fe59e494e54c87c0a09 (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
import NetworkImage
import SwiftUI
import UserNotifications

struct PostDetailsImageView<Placeholder: View>: View {
  @EnvironmentObject var settings: SettingsManager
  @EnvironmentObject var manager: BooruManager
  var url: URL?
  @Binding var loadingState: BooruPostLoadingState
  var finalLoadingState: BooruPostLoadingState
  let placeholder: () -> Placeholder
  let post: BooruPost?

  #if os(iOS)
    var keyWindow: UIWindow? {
      guard
        let window = UIApplication.shared.connectedScenes
          .compactMap({ $0 as? UIWindowScene })
          .flatMap(\.windows)
          .first(where: \.isKeyWindow)
      else {
        return nil
      }

      return window
    }
  #endif

  var body: some View {
    let content = NetworkImage(url: url) { image in
      InteractiveImageView(
        image: image,
        contextMenu: Group {
          #if os(iOS)
            if settings.enableShareShortcut {
              Button {
                guard let shareURL = url else { return }

                keyWindow?.rootViewController?.present(
                  UIActivityViewController(
                    activityItems: [shareURL], applicationActivities: nil
                  ), animated: true
                )
              } label: {
                Label("Share", systemImage: "square.and.arrow.up")
              }
              .disabled(url == nil)
            }
          #endif

          #if os(iOS)
            Button {
              guard let imageURL = url else { return }

              Task(priority: .userInitiated) {
                guard let imageData = await ImageCacheManager.shared.loadImageData(for: imageURL),
                  let uiImage = UIImage(data: imageData)
                else { return }

                await MainActor.run {
                  UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
                }
              }
            } label: {
              Label("Save to Photos", systemImage: "square.and.arrow.down")
            }
          #endif

          #if os(macOS)
            Button {
              saveImageToPicturesFolder()
            } label: {
              Label("Save to Pictures", systemImage: "square.and.arrow.down")
            }
            .keyboardShortcut("s", modifiers: [.command])
          #endif

          Button {
            #if os(iOS)
              Task(priority: .userInitiated) {
                guard let imageURL = url else { return }
                guard let imageData = await ImageCacheManager.shared.loadImageData(for: imageURL),
                  let uiImage = UIImage(data: imageData)
                else { return }

                await MainActor.run {
                  UIPasteboard.general.image = uiImage
                }
              }
            #else
              if let url {
                NSPasteboard.general.clearContents()
                NSPasteboard.general.writeObjects([NSImage(byReferencing: url)])
              }
            #endif
          } label: {
            Label("Copy", systemImage: "doc.on.doc")
          }
          .keyboardShortcut("c", modifiers: [.command])

          Button {
            guard let postURL = postURL(for: post?.id) else { return }

            openURL(postURL)
          } label: {
            Label("Open Post in Safari", systemImage: "safari")
          }
          .disabled(postURL(for: post?.id) == nil)

          if let source = post?.source,
            let sourceURL = URL(string: source.trimmingCharacters(in: .whitespacesAndNewlines))
          {
            Button {
              openURL(sourceURL)
            } label: {
              Label("Open Source Link in Safari", systemImage: "safari")
            }
          }
        }
      )
      .onAppear {
        if loadingState != .loaded { loadingState = finalLoadingState }
      }
    } placeholder: {
      placeholder()
        .onAppear { loadingState = .loadingPreview }
    }

    #if os(macOS)
      return content.overlay(
        Group {
          Button(action: saveImageToPicturesFolder) {
            EmptyView()
          }
          .keyboardShortcut("s", modifiers: [.command])

          Button(action: { movePostCursor(by: 1) }) { EmptyView() }
            .keyboardShortcut(.rightArrow, modifiers: [])

          Button(action: { movePostCursor(by: -1) }) { EmptyView() }
            .keyboardShortcut(.leftArrow, modifiers: [])
        }
        .frame(width: 0, height: 0)
        .opacity(0)
      )
    #else
      return content
    #endif
  }

  func movePostCursor(by direction: Int) {
    guard let selectedPost = manager.selectedPost,
      let index = manager.postIndexMap[selectedPost.id],
      (0..<manager.posts.count).contains(index + direction)
    else { return }

    manager.selectedPost = manager.posts[index + direction]
  }

  init(
    url: URL?,
    loadingStage: Binding<BooruPostLoadingState>,
    finalLoadingState: BooruPostLoadingState = .loadingFile,
    post: BooruPost? = nil,
    @ViewBuilder placeholder: @escaping () -> Placeholder = {
      GeometryReader { _ in
        //        ProgressView()
        //          .frame(width: geometry.size.width, height: geometry.size.height)
        //          .position(x: geometry.size.width / 2, y: geometry.size.height / 2)
        //          .padding()
      }
    }
  ) {
    self.url = url
    _loadingState = loadingStage
    self.finalLoadingState = finalLoadingState
    self.placeholder = placeholder
    self.post = post
  }

  private func postURL(for id: String?) -> URL? {
    guard let id, !id.isEmpty else { return nil }

    var components = URLComponents()

    components.scheme = "https"
    components.host = manager.domain

    switch manager.flavor {
    case .moebooru:
      components.path = "/post/show/\(id)"

    case .gelbooru:
      components.path = "/index.php"
      components.queryItems = [
        URLQueryItem(name: "page", value: "post"),
        URLQueryItem(name: "s", value: "view"),
        URLQueryItem(name: "id", value: id),
      ]

    case .danbooru:
      components.path = "/posts/\(id)"
    }

    return components.url
  }

  #if os(macOS)
    @preconcurrency
    private func saveImageToPicturesFolder() {
      guard let url = self.url else { return }

      let provider = manager.provider
      let detailViewQuality = settings.detailViewQuality
      let saveTagsToFile = settings.saveTagsToFile
      let post = self.post

      URLSession.shared.dataTask(with: url) { data, _, _ in
        guard let data, let post else { return }

        let picturesURL = FileManager.default.homeDirectoryForCurrentUser
          .appendingPathComponent("Pictures/Sora/\(provider.rawValue)")

        do {
          try FileManager.default.createDirectory(
            at: picturesURL,
            withIntermediateDirectories: true
          )
          try data.write(
            to:
              picturesURL
              .appendingPathComponent(
                "\(post.id)_\(detailViewQuality.rawValue.lowercased()).\(url.pathExtension)"
              )
          )

          if saveTagsToFile {
            try post.tags.joined(separator: "\n").write(
              to: picturesURL.appendingPathComponent(
                "\(post.id).txt"
              ),
              atomically: true,
              encoding: .utf8
            )
          }

          #if os(macOS)
            Task {
              await sendLocalNotification(
                title: "Sora",
                body: "Image \(saveTagsToFile ? "and tags" : "") saved (\(post.id))"
              )
            }
          #endif
        } catch {
          print("PostDetailsImageView.saveImageToPicturesFolder: \(error)")
        }
      }
      .resume()
    }
  #endif

  private func openURL(_ url: URL) {
    #if os(macOS)
      NSWorkspace.shared.open(url)
    #else
      UIApplication.shared.open(url)
    #endif
  }

  private func sendLocalNotification(title: String, body: String) async {
    let notificationCenter = UNUserNotificationCenter.current()

    do {
      try await notificationCenter.requestAuthorization(options: [.alert, .sound, .badge])
    } catch {
      debugPrint(error)
    }

    let content = UNMutableNotificationContent()

    content.title = title
    content.body = body
    content.sound = .default

    do {
      try await notificationCenter.add(
        UNNotificationRequest(
          identifier: UUID().uuidString,
          content: content,
          trigger: nil
        )
      )
    } catch {
      debugPrint(error)
    }
  }
}