import Foundation import Testing @testable import HUDKit // Push as an app file declares it, as Grain's does: the device's bindings // stamped into its register and unregister calls, a notification's fields // mapped to a route's path, and that path opened as the route's call. @Suite struct Pushing { private static let grain = "did:web:grain.social#grain_appview" private static let device: JSON = [ "serviceDid": "did:web:grain.social", "token": ["$token": true], "platform": ["$platform": true], "appId": ["$appId": true], ] /// Grain's app file, its push and the routes that push opens. private static let app: JSON = [ "routes": [ ["path": "/notifications", "call": ["name": "query", "args": ["method": "social.grain.notification.listNotifications"]]], [ "path": "/location/{h3}?name={name}", "tab": "Explore", "call": ["name": "query", "args": ["method": "social.grain.feed.getFeed", "params": ["location": "{h3}", "name": "{name}"]]], ], [ "path": "/search?q={q}&tab=people", "tab": "Explore", "call": ["name": "query", "args": ["method": "social.grain.actor.searchActors", "params": ["q": "{q}"]]], ], [ "path": "/profile/{actor}/gallery/{rkey}", "call": ["name": "query", "args": ["method": "social.grain.gallery.getGallery", "params": ["gallery": "at://{actor}/social.grain.gallery/{rkey}"]]], ], [ "path": "/profile/{actor}/story/{rkey}", "pager": true, "under": "/profile/{actor}", "call": ["name": "query", "args": ["method": "social.grain.story.getArchive", "params": ["actor": "{actor:did}"], "at": "at://{actor:did}/social.grain.story/{rkey}"]], ], ["path": "/profile/{actor}", "call": ["name": "describe_app", "args": ["domain": "grain.social", "actor": "{actor}"]]], ], "push": [ "register": ["method": "social.grain.notification.registerPush", "service": .string(grain), "input": device], "unregister": ["method": "social.grain.notification.unregisterPush", "service": .string(grain), "input": device], "open": [ ["when": ["uri": "at://{actor}/social.grain.gallery/{rkey}"], "path": "/profile/{actor}/gallery/{rkey}"], ["when": ["uri": "at://{actor}/social.grain.story/{rkey}"], "path": "/profile/{actor}/story/{rkey}"], ["when": ["did": "{actor}"], "path": "/profile/{actor}"], ], ], ] private static let plan = PushPlan(app["push"])! @Test func theDevicesBindingsAreStamped() { let device = PushDevice(apns: Data([0xDE, 0xAD, 0x01]), appId: "social.grain.grain") #expect(device == PushDevice(token: "dead01", appId: "social.grain.grain", platform: "ios")) let input: JSON = [ "serviceDid": "did:web:grain.social", "token": "dead01", "platform": "ios", "appId": "social.grain.grain", ] #expect(Self.plan.registering(device) == Call("call_procedure", ["method": "social.grain.notification.registerPush", "service": .string(Self.grain), "input": input])) #expect(Self.plan.unregistering(device).args["method"] == "social.grain.notification.unregisterPush") #expect(Self.plan.unregistering(device).args["input"] == input) // Nested, in arrays, and only a binding alone and true. let template: JSON = ["d": [["$token": true]], "x": ["$token": false], "y": ["$token": true, "z": 1], "w": ["$other": true]] #expect(PushPlan.stamped(template, device) == ["d": ["dead01"], "x": ["$token": false], "y": ["$token": true, "z": 1], "w": ["$other": true]]) } @Test func anAppWithoutPushHasNoPlan() { #expect(PushPlan(nil) == nil) #expect(PushPlan(["register": ["method": "a.b.c", "service": "did:web:x#y"]]) == nil) #expect(PushPlan(["register": ["method": "a.b.c", "service": "did:web:x#y"], "unregister": ["method": "a.b.d", "service": "did:web:x#y"]])?.open == []) } @Test func aNotificationOpensTheRouteItsFieldsName() { let did = "did:plc:abc123" // grain-serve's payloads: a gallery's favorite or comment, a story's, a follow. #expect(Self.plan.path(for: ["type": "gallery-favorite", "uri": "at://\(did)/social.grain.gallery/3kx"]) == "/profile/\(did)/gallery/3kx") #expect(Self.plan.path(for: ["type": "story-comment", "uri": "at://\(did)/social.grain.story/3ky"]) == "/profile/\(did)/story/3ky") #expect(Self.plan.path(for: ["type": "follow", "did": did]) == "/profile/\(did)") // A comment's favorite names the comment, which no route opens; nor does a payload without fields. #expect(Self.plan.path(for: ["type": "comment-favorite", "uri": "at://\(did)/social.grain.comment/3kz"]) == nil) #expect(Self.plan.path(for: [:]) == nil) // A field's value in a segment is encoded. #expect(Self.plan.path(for: ["did": "a b"]) == "/profile/a%20b") #expect(PushPlan.fields(["type": "follow", "did": did, "aps": ["badge": 2], 5: "x"]) == ["type": "follow", "did": did]) } @Test func aPathOpensAsItsRoutesCall() throws { let routes = Route.all(in: Self.app) #expect(routes.count == 6) let did = "did:plc:abc123" let gallery = try #require(Route.screen("/profile/\(did)/gallery/3kx", in: routes)) #expect(gallery.call == Call("query", ["method": "social.grain.gallery.getGallery", "params": ["gallery": .string("at://\(did)/social.grain.gallery/3kx")]])) #expect(gallery.tab == nil) let story = try #require(Route.screen("/profile/\(did)/story/3ky", in: routes)) #expect(story.call.args["at"] == .string("at://\(did)/social.grain.story/3ky")) #expect(story.call.args["params"] == ["actor": .string(did)]) #expect(Route.screen("/profile/\(did)/", in: routes)?.call == Call("describe_app", ["domain": "grain.social", "actor": .string(did)])) #expect(Route.screen("/notifications", in: routes)?.call.args["method"] == "social.grain.notification.listNotifications") // A query string's token may be absent, and its key is left out; a literal one must be there. let place = try #require(Route.screen("/location/8a2a?name=Central+Park", in: routes)) #expect(place.tab == "Explore") #expect(place.call.args["params"] == ["location": "8a2a", "name": "Central Park"]) #expect(Route.screen("/location/8a2a", in: routes)?.call.args["params"] == ["location": "8a2a"]) #expect(Route.screen("/search?q=cats&tab=people", in: routes)?.call.args["method"] == "social.grain.actor.searchActors") #expect(Route.screen("/search?q=cats", in: routes) == nil) // Encoded segments are decoded; a path no route has opens nothing. #expect(Route.screen("/profile/a%20b", in: routes)?.call.args["actor"] == "a b") #expect(Route.screen("/profile//gallery/3kx", in: routes) == nil) #expect(Route.screen("/nowhere", in: routes) == nil) #expect(Route(["path": "/x"]) == nil) } /// A story's route opens in the stories pager, over the screen under /// it: a path of it says so, `under` filled from the path; a call of it, /// as a view opens it, is known as one, keys besides its route's allowed. @Test func aStorysRouteOpensInThePager() throws { let routes = Route.all(in: Self.app) let did = "did:plc:abc123" let story = try #require(Route.screen("/profile/alice.test/story/3ky", in: routes)) #expect(story.pager) #expect(story.under == "/profile/alice.test") #expect(Route.screen("/profile/alice.test", in: routes)?.call == Call("describe_app", ["domain": "grain.social", "actor": "alice.test"])) let gallery = try #require(Route.screen("/profile/\(did)/gallery/3kx", in: routes)) #expect(!gallery.pager && gallery.under == nil) // A profile's Stories pane cover: its service and a limit besides. let archive = Call("query", [ "method": "social.grain.story.getArchive", "service": "did:web:grain.social#grain_appview", "params": ["actor": .string(did), "limit": 50], "at": .string("at://\(did)/social.grain.story/3ky"), ]) #expect(Route.pager(archive, in: routes)) #expect(Route.pager(story.call, in: routes)) // The archive with no story named, another account's story, a gallery, another tool: none. #expect(!Route.pager(Call("query", ["method": "social.grain.story.getArchive", "params": ["actor": .string(did)]]), in: routes)) #expect(!Route.pager(Call("query", ["method": "social.grain.story.getArchive", "params": ["actor": .string(did)], "at": "at://did:plc:other/social.grain.story/3ky"]), in: routes)) #expect(!Route.pager(gallery.call, in: routes)) #expect(!Route.pager(Call("call_tool", archive.args), in: routes)) // A query string's token alone may be absent; `pager` is true or nothing. let search = [Route(path: "/s?q={q}", call: Call("find", ["q": "{q}"]), pager: true)] #expect(Route.pager(Call("find", [:]), in: search)) #expect(Route(["path": "/x", "call": ["name": "n"], "pager": "yes"])?.pager == false) #expect(Route(["path": "/x", "call": ["name": "n"]])?.under == nil) } /// A path naming an account by handle, opened from outside: its call's /// `{actor:did}` tokens resolved to the DID first, so the archive opens /// at the story its `at` names; its `under` keeps the handle, and a DID /// or a token with no `:did` is asked of no one. @Test func aStorysPathResolvesItsAccount() async throws { let routes = Route.all(in: Self.app) var asked: [String] = [] let resolve = { (actor: String) async -> String in asked.append(actor) return "did:plc:abc123" } let story = try #require(await Route.screen("/profile/alice.test/story/3ky", in: routes, resolve: resolve)) #expect(story.call.args["at"] == "at://did:plc:abc123/social.grain.story/3ky") #expect(story.call.args["params"] == ["actor": "did:plc:abc123"]) #expect(story.under == "/profile/alice.test") #expect(asked == ["alice.test"]) _ = await Route.screen("/profile/did:plc:abc123/story/3ky", in: routes, resolve: resolve) _ = await Route.screen("/profile/alice.test", in: routes, resolve: resolve) #expect(asked == ["alice.test"]) #expect(await Route.screen("/nowhere", in: routes, resolve: resolve) == nil) } /// An app file's own pages are routes before its routes, each its /// path's `describe_app` of it; a page's text links mail as well as pages. @Test func anAppsPagesAreRoutes() throws { guard case .object(var app) = Self.app else { throw CancellationError() } app["domain"] = "grain.social" app["pages"] = [["path": "/support/terms", "title": "Terms", "markdown": "pages/terms.md"], ["title": "No path"]] let routes = Route.all(in: .object(app)) #expect(routes.count == 7) let terms = try #require(Route.screen("/support/terms", in: routes)) #expect(terms.call == Call("describe_app", ["domain": "grain.social", "page": "/support/terms"])) #expect(terms.tab == nil) #expect(Route.screen("/notifications", in: routes)?.call.args["method"] == "social.grain.notification.listNotifications") let text = Resolved.text([["text": "mail", "link": "mailto:support@grain.social"], ["text": "x", "link": "mailto:x"], ["text": "js", "link": "javascript:x"]]) #expect(text.runs.compactMap(\.link) == [URL(string: "mailto:support@grain.social")!]) } @Test func patternsBindTokens() { var bound: [String: String] = [:] let whole = Pattern.matchText("{a}", "x/y", &bound) #expect(whole && bound == ["a": "x/y"]) let elsewhere = Pattern.matchText("at://{a}/c/{r}", "at://x/d/r", &bound) #expect(!elsewhere) // A token bound already must match the same. bound = ["a": "x"] let another = Pattern.matchText("at://{a}/c/{r}", "at://y/c/r", &bound) #expect(!another) let same = Pattern.matchText("at://{a}/c/{r}", "at://x/c/r", &bound) #expect(same && bound["r"] == "r") let literal = Pattern.matchText("literal", "literal", &bound) #expect(literal) #expect(Pattern.sole("{a:did}") == "a") #expect(Pattern.sole("x{a}") == nil) var root: [String: String] = [:] let empty = Pattern.matchPath("/", "", &root) let slash = Pattern.matchPath("/", "/", &root) #expect(empty && slash) #expect(Pattern.fillText("/p/{a}/{b}", ["a": "1"]) == "/p/1/") } } /// What a test hands `Push`: a store of its own, and the paths it opened. @MainActor @Suite struct PushTapping { private func make() -> Push { let defaults = UserDefaults(suiteName: "hud.push.tests.\(UUID().uuidString)")! let plan = PushPlan(["register": ["method": "a.b.c", "service": "did:web:x#y"], "unregister": ["method": "a.b.d", "service": "did:web:x#y"], "open": [["when": ["did": "{actor}"], "path": "/profile/{actor}"]]])! return Push(plan: plan, appId: "social.grain.grain", defaults: defaults) } @Test func aTapBeforeTheAppCanOpenWaitsForIt() async { let push = make() push.tapped(["did": "did:plc:a"]) push.tapped(["type": "nothing"]) var opened: [String] = [] push.open = { opened.append($0) } #expect(opened == ["/profile/did:plc:a"]) push.tapped(["did": "did:plc:b"]) #expect(opened == ["/profile/did:plc:a", "/profile/did:plc:b"]) } @Test func theTokenIsKeptWithNoOneSignedIn() async { let push = make() #expect(push.token == nil) await push.registered(Data([0xAB, 0x12])) #expect(push.token == "ab12") // No one signed in: nothing to unregister as. await push.signingOut() #expect(push.token == "ab12") } }