// // SafariWebExtensionHandler.swift // Shared (Extension) // // Created by Emanuel Avalos on 23/04/25. // import SafariServices import Foundation class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { let item = context.inputItems[0] as! NSExtensionItem let message = item.userInfo?[SFExtensionMessageKey] if let url = message as? String { shortenURL(urlString: url) { shortUrl in let response = NSExtensionItem() response.userInfo = [ SFExtensionMessageKey: shortUrl ] context.completeRequest(returningItems: [response], completionHandler: nil) } } } private func shortenURL(urlString: String, completion: @escaping (String) -> Void) { guard let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let apiUrl = URL(string: "https://short.waifus.cc/yourls-api.php?signature=215c678cd4&action=shorturl&url=\(encodedUrl)&format=json") else { NSLog("Invalid URL: %@", urlString) completion("Error: Invalid URL") return } let task = URLSession.shared.dataTask(with: apiUrl) { data, response, error in if let error = error { NSLog("Network error: %@", error.localizedDescription) completion("Error: Network request failed") return } guard let data = data else { NSLog("No data received") completion("Error: No data received") return } do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let shortUrl = json["shorturl"] as? String { completion(shortUrl) } else { NSLog("Invalid JSON response") completion("Error: Invalid server response") } } catch { NSLog("JSON parsing error: %@", error.localizedDescription) completion("Error: Could not parse response") } } task.resume() } }