2024-12-03 13:19:50 +01:00

132 lines
3.3 KiB
Swift

import Foundation
import SwiftUI
import Combine
final class Content: ObservableObject {
@Published
var websiteData: WebsiteData
@Published
var posts: [Post]
@Published
var pages: [Page]
@Published
var tags: [Tag]
@Published
var images: [ImageResource]
@Published
var videos: [String]
@Published
var files: [FileResource]
@AppStorage("contentPath")
private var storedContentPath: String = ""
@Published
var contentPath: String = "" {
didSet {
storedContentPath = contentPath
}
}
let storage: Storage
private var cancellables = Set<AnyCancellable>()
init(websiteData: WebsiteData,
posts: [Post],
pages: [Page],
tags: [Tag],
images: [ImageResource],
files: [FileResource],
videos: [String],
storedContentPath: String) {
self.websiteData = websiteData
self.posts = posts
self.pages = pages
self.tags = tags
self.images = images
self.files = files
self.videos = videos
self.storedContentPath = storedContentPath
self.contentPath = storedContentPath
self.storage = Storage(baseFolder: URL(filePath: storedContentPath))
do {
try storage.createFolderStructure()
} catch {
print(error)
return
}
observeContentPath()
}
init() {
self.storage = Storage(baseFolder: URL(filePath: ""))
self.websiteData = .mock
self.posts = []
self.pages = []
self.tags = []
self.images = []
self.files = []
self.videos = []
contentPath = storedContentPath
do {
try storage.createFolderStructure()
} catch {
print(error)
return
}
try? storage.update(baseFolder: URL(filePath: contentPath), moveContent: false)
observeContentPath()
}
private func observeContentPath() {
$contentPath.sink { newValue in
let url = URL(filePath: newValue)
try? self.storage.update(baseFolder: url, moveContent: true)
}
.store(in: &cancellables)
}
// MARK: Folder access
static func accessFolderFromBookmark(key: String, operation: (URL) -> Void) {
guard let bookmarkData = UserDefaults.standard.data(forKey: key) else {
print("No bookmark data to access folder")
return
}
var isStale = false
let folderURL: URL
do {
// Resolve the bookmark to get the folder URL
folderURL = try URL(resolvingBookmarkData: bookmarkData, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
} catch {
print("Failed to resolve bookmark: \(error)")
return
}
if isStale {
print("Bookmark is stale, consider saving a new bookmark.")
}
// Start accessing the security-scoped resource
if folderURL.startAccessingSecurityScopedResource() {
print("Accessing folder: \(folderURL.path)")
operation(folderURL)
folderURL.stopAccessingSecurityScopedResource()
} else {
print("Failed to access folder: \(folderURL.path)")
}
}
}