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

struct PostDetailsImageView<Placeholder: View>: View {
  @EnvironmentObject var settings: Settings
  @EnvironmentObject var manager: BooruManager
  var url: URL?
  @Binding var loadingState: BooruPostLoadingState
  var finalLoadingState: BooruPostLoadingState
  let placeholder: () -> Placeholder
  let post: BooruPost?
  @State private var currentScale: CGFloat = 1.0
  @State private var finalScale: CGFloat = 1.0
  @State private var currentOffset: CGSize = .zero
  @State private var finalOffset: CGSize = .zero

  #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,
      transaction: Transaction(animation: .default)
    ) { image in
      InteractiveImageView(
        image: image,
        contextMenu: Group {
          #if os(iOS)
            Button {
              guard let url else { return }

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

                UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
              }
              .resume()
            } label: {
              Label("Save Image", systemImage: "square.and.arrow.down")
            }
          #endif

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

          #if os(iOS)
            if settings.enableShareShortcut {
              Button {
                keyWindow?.rootViewController?.present(
                  UIActivityViewController(
                    activityItems: [url ?? URL(string: "")!], applicationActivities: nil
                  ), animated: true
                )
              } label: {
                Label("Share Image", systemImage: "square.and.arrow.up")
              }
            }
          #endif

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

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

    #if os(macOS)
      return content.overlay(
        Button(action: saveImageToPicturesFolder) {
          EmptyView()
        }
        .keyboardShortcut("s", modifiers: [.command])
        .frame(width: 0, height: 0)
        .opacity(0)
      )
    #else
      return content
    #endif
  }

  init(
    url: URL?,
    loadingStage: Binding<BooruPostLoadingState>,
    finalLoadingState: BooruPostLoadingState = .loadingFile,
    post: BooruPost? = nil,
    @ViewBuilder placeholder: @escaping () -> Placeholder = {
      GeometryReader { geometry 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 {
    switch manager.flavor {
    case .moebooru:
      return URL(string: "https://\(manager.domain)/post/show/\(id)")!

    case .gelbooru:
      return URL(string: "https://\(manager.domain)/index.php?page=post&s=view&id=\(id)")!
    }
  }

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

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

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

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

          if settings.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 \(settings.saveTagsToFile ? "and tags" : "") saved (\(post.id))"
              )
            }
          #endif
        } catch {
          print("PostDetailsImageView.saveImageToPicturesFolder: \(error)")
        }
      }
      .resume()
    }
  #endif

  private func openURL(_ url: URL) {
    #if os(iOS)
      UIApplication.shared.open(url)
    #else
      NSWorkspace.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)
    }
  }
}