Repository Public
1// SP Drive iOS2// File: KitTests/ShareTests.swift3// Description: The share extension's logic without the extension: what each kind of shared item becomes (file, PDF, link file, text4// file), with real NSItemProviders; and the inbox in the group container, including the case where the extension is5// stopped after it finished (or half finished) an upload — nothing is lost and nothing is sent twice.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11import UniformTypeIdentifiers12@testable import SPDriveKit1314@Suite struct ShareIntakeTests {15 func dir() -> URL { FileManager.default.temporaryDirectory.appendingPathComponent("intake-\(UUID().uuidString.prefix(8))", isDirectory: true) }1617 @Test func eachKindOfSharedItemHasAPlan() {18 #expect(ShareIntake.plan(types: ["public.url"]) == .webLink) // Safari, a web page19 #expect(ShareIntake.plan(types: ["public.url", "com.adobe.pdf"]) == .file(type: "com.adobe.pdf")) // Safari on a PDF: the PDF itself20 #expect(ShareIntake.plan(types: ["public.jpeg", "public.file-url"]) == .file(type: "public.jpeg")) // Files21 #expect(ShareIntake.plan(types: ["public.heic"]) == .file(type: "public.heic")) // Photos22 #expect(ShareIntake.plan(types: ["com.apple.quicktime-movie"]) == .file(type: "com.apple.quicktime-movie"))23 #expect(ShareIntake.plan(types: ["public.plain-text", "public.file-url"]) == .file(type: "public.plain-text")) // a .txt from Files stays a file24 #expect(ShareIntake.plan(types: ["public.plain-text"]) == .text(type: "public.plain-text")) // selected text25 #expect(ShareIntake.plan(types: ["public.plain-text", "public.url"]) == .webLink) // a link shared with its title26 #expect(ShareIntake.plan(types: ["org.openxmlformats.wordprocessingml.document"]) == .file(type: "org.openxmlformats.wordprocessingml.document")) // Mail attachment27 #expect(ShareIntake.plan(types: ["public.file-url"]) == .unsupported || ShareIntake.plan(types: ["public.file-url"]) == .file(type: "public.file-url"))28 #expect(ShareIntake.plan(types: []) == .unsupported)29 #expect(ShareIntake.name(from: "Un titre / avec : des\nlignes", fallback: "x", ext: "webloc") == "Un titre _ avec _ des.webloc")30 #expect(ShareIntake.name(from: " ", fallback: "exemple.org", ext: "webloc") == "exemple.org.webloc")31 #expect(ShareIntake.name(from: String(repeating: "a", count: 300), fallback: "x", ext: "txt").count <= 84)32 }3334 @Test func webPageBecomesALinkFile() async throws {35 let provider = NSItemProvider(object: URL(string: "https://www.example.org/article?id=7")! as NSURL)36 let c = try #require(await ShareIntake.collect(provider, title: "Un article intéressant", into: dir()))37 #expect(c.kind == .webLink && c.name == "Un article intéressant.webloc")38 let raw = try PropertyListSerialization.propertyList(from: Data(contentsOf: c.url), format: nil)39 let plist = try #require(raw as? [String: String])40 #expect(plist["URL"] == "https://www.example.org/article?id=7")41 // without a title the host names the file; anything that is not http(s) is refused42 #expect(await ShareIntake.collect(NSItemProvider(object: URL(string: "https://exemple.org/x")! as NSURL), into: dir())?.name == "exemple.org.webloc")43 #expect(await ShareIntake.collect(NSItemProvider(object: URL(string: "javascript:alert(1)")! as NSURL), into: dir()) == nil)44 }4546 @Test func pdfTextAndFilesAreCollected() async throws {47 // a page shared with a PDF representation: the PDF is taken, not the link48 let both = NSItemProvider(object: URL(string: "https://www.example.org/doc.pdf")! as NSURL)49 let pdfBytes = Data("%PDF-1.4 test".utf8)50 both.registerDataRepresentation(forTypeIdentifier: UTType.pdf.identifier, visibility: .all) { done in done(pdfBytes, nil); return nil }51 both.suggestedName = "Rapport annuel"52 let pdf = try #require(await ShareIntake.collect(both, into: dir()))53 #expect(pdf.kind == .pdf && pdf.name == "Rapport annuel.pdf")54 #expect(try Data(contentsOf: pdf.url) == pdfBytes)5556 let text = NSItemProvider(object: "Une note prise au vol\nSeconde ligne" as NSString)57 let t = try #require(await ShareIntake.collect(text, into: dir()))58 #expect(t.kind == .text && t.name == "Une note prise au vol.txt")59 #expect(try String(contentsOf: t.url, encoding: .utf8) == "Une note prise au vol\nSeconde ligne")6061 // a file lent by another app (Files, Mail): copied under its own name, several items side by side62 let src = dir()63 try FileManager.default.createDirectory(at: src, withIntermediateDirectories: true)64 let out = dir()65 for (i, name) in ["photo.jpg", "pièce jointe.docx"].enumerated() {66 let f = src.appendingPathComponent(name)67 try randomData(2_000 + i).write(to: f)68 let lent = try #require(NSItemProvider(contentsOf: f))69 let c = try #require(await ShareIntake.collect(lent, into: out.appendingPathComponent("\(i)")))70 #expect(c.kind == .file && c.name == name, "\(c.kind) \(c.name) types=\(lent.registeredTypeIdentifiers)")71 #expect(try Data(contentsOf: c.url) == Data(contentsOf: f))72 }73 #expect(await ShareIntake.collect(NSItemProvider(), into: dir()) == nil)74 }75}7677@Suite(.enabled(if: TestEnv.available, "disposable backend not running: Scripts/test-server.sh up"), .serialized)78struct ShareInboxTests {79 @Test func parkedFilesAreSentOnceEvenWhenTheExtensionWasStoppedMidway() async throws {80 let a = try await Device(), b = try await Device(host: "127.0.0.1")81 let ws = try await a.workspace("share")82 let inbox = ShareInbox(directory: a.root.appendingPathComponent("Inbox", isDirectory: true))83 let payload = ["envoyé.bin": randomData(30_000), "à-moitié.bin": randomData(9_000_000), "jamais-parti.webloc": ShareIntake.webloc(for: URL(string: "https://example.org")!)]84 var entries: [String: ShareInbox.Entry] = [:]85 for (name, data) in payload { entries[name] = try inbox.park(try a.tempFile(name, data), displayName: name, folderID: ws.id) }86 #expect(inbox.entries().count == 3)8788 // the extension sent the first file completely, then was stopped before it could say so89 let done = try #require(entries["envoyé.bin"])90 _ = try await DirectTransfer.upload(file: inbox.url(of: done), remote: a.api, store: nil, resumeKey: nil, scratch: a.root.appendingPathComponent("scratch")) { size in91 let up = try await a.api.createUpload(parentID: ws.id, name: "envoyé.bin", size: size, onConflict: .rename, fileID: nil, baseVersionID: nil)92 inbox.note(uploadID: up.id, for: done)93 return up94 }95 // … and had sent only the first block of the second one96 let half = try #require(entries["à-moitié.bin"])97 let session = try await a.api.createUpload(parentID: ws.id, name: "à-moitié.bin", size: 9_000_000, onConflict: .rename, fileID: nil, baseVersionID: nil)98 inbox.note(uploadID: session.id, for: half)99 let chunk = a.root.appendingPathComponent("chunk")100 let sha = try IntegrityVerifier.slice(inbox.url(of: half), offset: 0, length: 8 * 1024 * 1024, to: chunk)101 _ = try await a.api.sendChunk(uploadID: session.id, offset: 0, sha256: sha, fileURL: chunk)102103 // the app opens: it drains the inbox into its own queue104 await a.engine.sync()105 let engine = a.engine106 await inbox.drain(remote: a.api) { url, entry in _ = try await engine.importFile(at: url, named: entry.displayName, into: entry.folderID ?? "", move: false) }107 #expect(inbox.entries().isEmpty)108 await a.settle(timeout: 90)109110 await b.engine.sync()111 let names = b.store.children(of: ws.id).map(\.name).sorted()112 #expect(names == ["envoyé.bin", "jamais-parti.webloc", "à-moitié.bin"].sorted(), "each file exactly once, no « (2) »: \(names)")113 for (name, data) in payload { #expect(b.child(name, of: ws.id)?.sha256 == IntegrityVerifier.sha256(data)) }114 // the half-finished session of the extension was closed, not left behind115 await #expect(throws: RemoteError.self) { let s = try await a.api.uploadStatus(id: session.id); if s.status != "active" { throw RemoteError.uploadClosed } }116117 // offline at the time of the drain: the entry whose fate is unknown waits, nothing is duplicated118 let later = try inbox.park(try a.tempFile("plus-tard.txt", Data("plus tard".utf8)), displayName: "plus-tard.txt", folderID: ws.id)119 inbox.note(uploadID: "00000000-0000-4000-8000-000000000000", for: later)120 a.setOffline(true)121 defer { NetworkGate.set("localhost", offline: false) }122 await inbox.drain(remote: a.api) { url, entry in _ = try await engine.importFile(at: url, named: entry.displayName, into: entry.folderID ?? "", move: false) }123 #expect(inbox.entries().count == 1)124 a.setOffline(false)125 await inbox.drain(remote: a.api) { url, entry in _ = try await engine.importFile(at: url, named: entry.displayName, into: entry.folderID ?? "", move: false) }126 await a.settle()127 #expect(inbox.entries().isEmpty && a.child("plus-tard.txt", of: ws.id) != nil)128 }129}130