Remade project structure

This commit is contained in:
Joshua Higgins
2025-06-04 13:57:32 -04:00
parent b27b223a5e
commit 718436764d
57 changed files with 925 additions and 894 deletions

View File

@@ -0,0 +1,60 @@
import Foundation
import UIKit
class DownloadService {
static let shared = DownloadService()
private let cache = NSCache<NSString, NSData>()
private var activeTasks: [URL: URLSessionDataTask] = [:]
private init() {
cache.totalCostLimit = 50 * 1024 * 1024 // 50 MB cache limit
}
func downloadGIF(from urlString: String, completion: @escaping (Data?, Error?) -> Void) {
guard let url = URL(string: urlString) else {
completion(nil, NSError(domain: "DownloadService", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
return
}
// Check if the GIF is already cached
let cacheKey = url.absoluteString as NSString
if let cachedData = cache.object(forKey: cacheKey) {
completion(cachedData as Data, nil)
return
}
// Cancel any existing tasks for this URL
activeTasks[url]?.cancel()
// Create a new download task
let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
defer {
self?.activeTasks.removeValue(forKey: url)
}
guard let self = self, error == nil, let data = data else {
DispatchQueue.main.async {
completion(nil, error ?? NSError(domain: "DownloadService", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to download GIF"]))
}
return
}
// Cache the downloaded data
self.cache.setObject(data as NSData, forKey: cacheKey, cost: data.count)
DispatchQueue.main.async {
completion(data, nil)
}
}
// Store and start the task
activeTasks[url] = task
task.resume()
}
func cancelAllTasks() {
activeTasks.values.forEach { $0.cancel() }
activeTasks.removeAll()
}
}

View File

@@ -0,0 +1,177 @@
import Foundation
import UIKit
class GIFFileManager {
static let shared = GIFFileManager()
private init() {
createGIFsDirectoryIfNeeded()
}
// MARK: - File Storage
private var documentsDirectory: URL {
// First try to get the App Group container
if let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.gifcollector") {
return containerURL
}
// Fall back to the app's documents directory if App Group is not available
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
private var gifsDirectory: URL {
return documentsDirectory.appendingPathComponent("SavedGIFs", isDirectory: true)
}
private func createGIFsDirectoryIfNeeded() {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: gifsDirectory.path) {
do {
try fileManager.createDirectory(at: gifsDirectory, withIntermediateDirectories: true)
} catch {
print("Error creating GIFs directory: \(error)")
}
}
}
func storeGIF(data: Data, fromURL urlString: String) -> String? {
// Check if this is a shared GIF from the share extension
if let sharedGIFPath = checkForSharedGIF(withURL: urlString), FileManager.default.fileExists(atPath: sharedGIFPath) {
return sharedGIFPath
}
// Create a unique filename based on the URL hash and timestamp
let urlHash = urlString.hashValue
let timestamp = Int(Date().timeIntervalSince1970)
let filename = "gif_\(urlHash)_\(timestamp).gif"
let fileURL = gifsDirectory.appendingPathComponent(filename)
do {
try data.write(to: fileURL)
return fileURL.path
} catch {
print("Error saving GIF to disk: \(error)")
return nil
}
}
func loadGIFData(from localPath: String) -> Data? {
let url = URL(fileURLWithPath: localPath)
do {
let data = try Data(contentsOf: url)
return data
} catch {
print("Error loading GIF from disk: \(error)")
return nil
}
}
func deleteGIF(at localPath: String) -> Bool {
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: localPath)
return true
} catch {
print("Error deleting GIF from disk: \(error)")
return false
}
}
func fileExists(at localPath: String) -> Bool {
return FileManager.default.fileExists(atPath: localPath)
}
func getAllGIFsSize() -> Int64 {
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(at: gifsDirectory, includingPropertiesForKeys: [.fileSizeKey])
var totalSize: Int64 = 0
while let fileURL = enumerator?.nextObject() as? URL {
do {
let attributes = try fileURL.resourceValues(forKeys: [.fileSizeKey])
if let fileSize = attributes.fileSize {
totalSize += Int64(fileSize)
}
} catch {
print("Error calculating file size: \(error)")
}
}
return totalSize
}
// Clean up old GIFs if storage exceeds 100 MB
func performStorageCleanupIfNeeded() {
let maxStorageSize: Int64 = 100 * 1024 * 1024 // 100 MB
if getAllGIFsSize() > maxStorageSize {
cleanupOldGIFs()
}
}
private func cleanupOldGIFs() {
let fileManager = FileManager.default
do {
// Get all files and their creation dates
let fileURLs = try fileManager.contentsOfDirectory(at: gifsDirectory, includingPropertiesForKeys: [.creationDateKey])
// Sort by creation date
let sortedFiles = try fileURLs.sorted {
let date1 = try $0.resourceValues(forKeys: [.creationDateKey]).creationDate ?? Date.distantPast
let date2 = try $1.resourceValues(forKeys: [.creationDateKey]).creationDate ?? Date.distantPast
return date1 < date2
}
// Delete the oldest 30% of files
let filesToDelete = Int(Double(sortedFiles.count) * 0.3)
for i in 0..<min(filesToDelete, sortedFiles.count) {
try fileManager.removeItem(at: sortedFiles[i])
}
} catch {
print("Error cleaning up old GIFs: \(error)")
}
}
// Check if we already have this GIF in the shared container
private func checkForSharedGIF(withURL urlString: String) -> String? {
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.gifcollector") else {
return nil
}
let sharedGIFsFolder = containerURL.appendingPathComponent("GIFs", isDirectory: true)
guard FileManager.default.fileExists(atPath: sharedGIFsFolder.path) else {
return nil
}
do {
let fileURLs = try FileManager.default.contentsOfDirectory(at: sharedGIFsFolder, includingPropertiesForKeys: nil)
// Find any shared GIF that matches our URL (usually won't find any, but helps avoid duplicates)
let userDefaults = UserDefaults(suiteName: "group.gifcollector")
if let pendingGIFs = userDefaults?.array(forKey: "pendingGIFs") as? [[String: Any]] {
for gifInfo in pendingGIFs {
if let originURL = gifInfo["originalURL"] as? String,
let path = gifInfo["localFilePath"] as? String,
originURL == urlString {
return path
}
}
}
return nil
} catch {
print("Error checking for shared GIFs: \(error)")
return nil
}
}
}

View File

@@ -0,0 +1,135 @@
import Foundation
class GIFStorageService {
static let shared = GIFStorageService()
private let userDefaults = UserDefaults(suiteName: "group.gifcollector")
private let savedGIFsKey = "savedGIFs"
private let pendingGIFsKey = "pendingGIFs"
private init() {
// Make sure the shared UserDefaults exists
if userDefaults == nil {
print("Error: Could not create UserDefaults with app group")
}
// Process any pending GIFs from the Share Extension
checkForSharedGIFs()
}
func saveGIF(data: Data, fromURL urlString: String, completion: @escaping (GIF?) -> Void) {
// First store the GIF data to disk
guard let localPath = GIFFileManager.shared.storeGIF(data: data, fromURL: urlString) else {
completion(nil)
return
}
// Create and save the GIF model
let gif = GIF(localFilePath: localPath, originalURL: urlString)
var savedGIFs = fetchGIFs()
// Don't save duplicates of the same URL
if !savedGIFs.contains(where: { $0.originalURL == urlString }) {
savedGIFs.append(gif)
saveToUserDefaults(gifs: savedGIFs)
}
// Perform cleanup if needed
GIFFileManager.shared.performStorageCleanupIfNeeded()
completion(gif)
}
func fetchGIFs() -> [GIF] {
guard let data = userDefaults?.data(forKey: savedGIFsKey),
let gifs = try? JSONDecoder().decode([GIF].self, from: data) else {
return []
}
// Filter out any GIFs whose files no longer exist
let validGIFs = gifs.filter { GIFFileManager.shared.fileExists(at: $0.localFilePath) }
// If we filtered any out, save the updated list
if validGIFs.count != gifs.count {
saveToUserDefaults(gifs: validGIFs)
}
return validGIFs.sorted(by: { $0.createdAt > $1.createdAt })
}
func deleteGIF(with id: UUID) {
var savedGIFs = fetchGIFs()
// Find the GIF to delete
if let gifToDelete = savedGIFs.first(where: { $0.id == id }) {
// Delete the file from storage
GIFFileManager.shared.deleteGIF(at: gifToDelete.localFilePath)
// Remove from the list
savedGIFs.removeAll(where: { $0.id == id })
saveToUserDefaults(gifs: savedGIFs)
}
}
func clearAllGIFs() {
// Delete all GIF files
fetchGIFs().forEach { gif in
GIFFileManager.shared.deleteGIF(at: gif.localFilePath)
}
// Clear the list
saveToUserDefaults(gifs: [])
}
private func saveToUserDefaults(gifs: [GIF]) {
guard let data = try? JSONEncoder().encode(gifs) else { return }
userDefaults?.set(data, forKey: savedGIFsKey)
}
func getGIFData(for gif: GIF) -> Data? {
return GIFFileManager.shared.loadGIFData(from: gif.localFilePath)
}
// MARK: - Share Extension Integration
func checkForSharedGIFs() {
guard let pendingGIFsData = userDefaults?.array(forKey: pendingGIFsKey) as? [[String: Any]] else {
return
}
guard !pendingGIFsData.isEmpty else {
return
}
var savedGIFs = fetchGIFs()
var newGIFsAdded = false
for gifInfo in pendingGIFsData {
if let localFilePath = gifInfo["localFilePath"] as? String,
let originalURL = gifInfo["originalURL"] as? String,
let createdAt = gifInfo["createdAt"] as? TimeInterval {
// Create a GIF object
let gif = GIF(
localFilePath: localFilePath,
originalURL: originalURL
)
// Don't add duplicates
if !savedGIFs.contains(where: { $0.localFilePath == localFilePath }) {
savedGIFs.append(gif)
newGIFsAdded = true
}
}
}
// Save updated GIFs list and clear pending ones
if newGIFsAdded {
saveToUserDefaults(gifs: savedGIFs)
}
// Clear pending GIFs
userDefaults?.removeObject(forKey: pendingGIFsKey)
}
}