// // 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) { guard let item = context.inputItems.first as? NSExtensionItem, let message = item.userInfo?[SFExtensionMessageKey] as? [String: String], let urlString = message["url"], let signature = message["signature"] else { let response = NSExtensionItem() response.userInfo = [SFExtensionMessageKey: "Error: Invalid request"] context.completeRequest(returningItems: [response], completionHandler: nil) return } shortenURL(urlString: urlString, signature: signature) { shortUrl in let response = NSExtensionItem() response.userInfo = [SFExtensionMessageKey: shortUrl] context.completeRequest(returningItems: [response], completionHandler: nil) } } private func shortenURL(urlString: String, signature: String, completion: @escaping (String) -> Void) { guard let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let encodedSignature = signature.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let apiUrl = URL(string: "https://short.waifus.cc/yourls-api.php?signature=\(encodedSignature)&action=shorturl&url=\(encodedUrl)&format=json") else { NSLog("Invalid URL: %@", urlString) completion("Error: Invalid URL") return } let task = URLSession.shared.dataTask(with: apiUrl) { data, _, 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() } }