~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
252 lines · 13.0 KB Raw History
import Foundation
import XCTest

@testable import OldFella

extension ATProtoServiceTests {
    func testVideoUploadUsesServiceTokenAndPublishesProcessedBlob() async throws {
        let suite = "VideoUpload.\(UUID().uuidString)"
        let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)
        let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "")
        let token = "header.\(payload).signature"
        StubURLProtocol.clearRequests()
        StubURLProtocol.handler = { request in
            try self.videoUploadResponse(request, token: token)
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
            defaults.removePersistentDomain(forName: suite)
        }
        let service = ATProtoBlueskyService(defaults: defaults, session: session)
        _ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil)
        do {
            _ = try await service.publish(
                text: "Mixed", replyTo: nil, quotePost: nil, images: [ImageAttachment(data: Data([1]))],
                video: VideoAttachment(data: Data([1])))
            XCTFail("Expected mixed media to fail")
        } catch {
            XCTAssertTrue(error is ActionNotSentError)
        }
        XCTAssertFalse(
            StubURLProtocol.recordedRequests.contains { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
        _ = try await service.publish(
            text: "Video", replyTo: nil, quotePost: nil, images: [], video: VideoAttachment(data: Data([1, 2, 3, 4])))
        let request = try XCTUnwrap(
            StubURLProtocol.recordedRequests.first { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" })
        let body = try XCTUnwrap(StubURLProtocol.recordedBody(for: try XCTUnwrap(request.url)))
        let object = try XCTUnwrap(JSONSerialization.jsonObject(with: body) as? [String: Any])
        let record = try XCTUnwrap(object["record"] as? [String: Any])
        let embed = try XCTUnwrap(record["embed"] as? [String: Any])
        XCTAssertEqual(embed["$type"] as? String, "app.bsky.embed.video")
        XCTAssertNil(embed["alt"])
        let blob = try XCTUnwrap(embed["video"] as? [String: Any])
        XCTAssertEqual(blob["mimeType"] as? String, "video/mp4")
        let videoFile = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).mp4")
        try Data([5, 6, 7, 8]).write(to: videoFile)
        defer { try? FileManager.default.removeItem(at: videoFile) }
        _ = try await service.publish(
            text: "File video", replyTo: nil, quotePost: nil, images: [], video: VideoAttachment(fileURL: videoFile))
        XCTAssertEqual(
            StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/app.bsky.video.uploadVideo" }.count, 2)
        try await service.signOut()
    }

    func testFiveImagesUseGalleryEmbed() throws {
        let image: [String: Any] = [
            "image": ["mimeType": "image/jpeg"], "alt": "Example", "aspectRatio": ["width": 4, "height": 3]
        ]
        let legacy = ATProtoBlueskyService.imageEmbed(Array(repeating: image, count: 4))
        XCTAssertEqual(legacy["$type"] as? String, "app.bsky.embed.images")
        let gallery = ATProtoBlueskyService.imageEmbed(Array(repeating: image, count: 10))
        XCTAssertEqual(gallery["$type"] as? String, "app.bsky.embed.gallery")
        let items = try XCTUnwrap(gallery["items"] as? [[String: Any]])
        XCTAssertEqual(items.count, 10)
        XCTAssertTrue(items.allSatisfy { $0["$type"] as? String == "app.bsky.embed.gallery#image" })
    }
    func testSavedCustomFeedsAndMissingFeedResponse() async throws {
        let suite = "CustomFeeds.\(UUID().uuidString)"
        let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [StubURLProtocol.self]
        let session = URLSession(configuration: configuration)
        let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)
        let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "")
        let token = "header.\(payload).signature"
        let uri = "at://did:plc:reader/app.bsky.feed.generator/nature"
        var legacy = false
        var status = 200
        StubURLProtocol.handler = { request in
            try self.customFeedResponse(request, token: token, uri: uri, legacy: legacy, status: status)
        }
        defer {
            StubURLProtocol.handler = nil
            session.invalidateAndCancel()
            defaults.removePersistentDomain(forName: suite)
        }
        let service = ATProtoBlueskyService(defaults: defaults, session: session)
        _ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil)
        let expected = [CustomFeed(id: uri, name: "Nature", avatarURL: URL(string: "https://example.test/avatar.png"))]
        let feeds = try await service.loadSubscribedFeeds()
        XCTAssertEqual(feeds, expected)
        legacy = true
        let legacyFeeds = try await service.loadSubscribedFeeds()
        XCTAssertEqual(legacyFeeds, expected)
        let page = try await service.loadCustomFeed(uri: uri, cursor: "next")
        XCTAssertEqual(page.cursor, "last")
        _ = try await service.loadFollowingFeed(cursor: nil)
        status = 404
        do {
            _ = try await service.loadCustomFeed(uri: uri, cursor: "next")
            XCTFail("Expected a missing feed")
        } catch { XCTAssertTrue(error is CustomFeedError, "Unexpected error: \(String(reflecting: error))") }
        status = 503
        do {
            _ = try await service.loadCustomFeed(uri: uri, cursor: "next")
            XCTFail("Expected a server error")
        } catch { XCTAssertFalse(error is CustomFeedError) }
    }

    private func videoUploadResponse(_ request: URLRequest, token: String) throws -> (Int, Data) {
        switch request.url?.path {
        case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
        case "/did:plc:reader":
            return (
                200,
                Data(
                    ("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\","
                        + "\"type\":\"AtprotoPersonalDataServer\","
                        + "\"serviceEndpoint\":\"https://reader.example.test\"}]}")
                        .utf8)
            )
        case "/xrpc/com.atproto.server.createSession":
            return (
                200,
                Data(
                    ("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\","
                        + "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}")
                        .utf8)
            )
        case "/xrpc/app.bsky.actor.getProfile":
            return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8))
        case "/xrpc/com.atproto.server.getServiceAuth":
            let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
            XCTAssertEqual(query?.first { $0.name == "aud" }?.value, "did:web:reader.example.test")
            XCTAssertEqual(query?.first { $0.name == "lxm" }?.value, "com.atproto.repo.uploadBlob")
            return (200, Data("{\"token\":\"video-service-token\"}".utf8))
        case "/xrpc/app.bsky.video.uploadVideo":
            XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer video-service-token")
            XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "video/mp4")
            return (200, Data("{\"jobId\":\"job-1\",\"state\":\"JOB_STATE_ENCODING\"}".utf8))
        case "/xrpc/app.bsky.video.getJobStatus":
            return (
                200,
                Data(
                    ("{\"jobStatus\":{\"jobId\":\"job-1\",\"state\":\"JOB_STATE_COMPLETED\","
                        + "\"blob\":{\"$type\":\"blob\",\"ref\":{\"$link\":\"bafk-video\"},"
                        + "\"mimeType\":\"video/mp4\",\"size\":4}}}")
                        .utf8)
            )
        case "/xrpc/com.atproto.repo.createRecord":
            return (200, Data("{\"uri\":\"at://did:plc:reader/app.bsky.feed.post/new\",\"cid\":\"cid\"}".utf8))
        default:
            XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")")
            return (404, Data())
        }
    }

    private func customFeedResponse(_ request: URLRequest, token: String, uri: String, legacy: Bool, status: Int) throws
        -> (Int, Data) {
        if let response = try customFeedResponseIdentity(
            request, token: token, uri: uri, legacy: legacy, status: status) {
            return response
        }
        return try customFeedResponseAction(request, token: token, uri: uri, legacy: legacy, status: status)
    }

    private func customFeedResponseIdentity(
        _ request: URLRequest, token: String, uri: String, legacy: Bool, status: Int
    ) throws -> (Int, Data)? {
        switch request.url?.path {
        case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
        case "/did:plc:reader":
            return (
                200,
                Data(
                    ("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\","
                        + "\"type\":\"AtprotoPersonalDataServer\","
                        + "\"serviceEndpoint\":\"https://reader.example.test\"}]}")
                        .utf8)
            )
        case "/xrpc/com.atproto.server.createSession":
            return (
                200,
                Data(
                    ("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\","
                        + "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}")
                        .utf8)
            )
        case "/xrpc/app.bsky.actor.getProfile":
            return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8))
        default: return nil
        }
    }

    private func customFeedResponseAction(_ request: URLRequest, token: String, uri: String, legacy: Bool, status: Int)
        throws -> (Int, Data) {
        switch request.url?.path {
        case "/xrpc/app.bsky.actor.getPreferences":
            let pref: [String: Any] =
                legacy
                ? ["$type": "app.bsky.actor.defs#savedFeedsPref", "saved": [uri, uri], "pinned": [uri]]
                : [
                    "$type": "app.bsky.actor.defs#savedFeedsPrefV2",
                    "items": [
                        ["id": "one", "type": "feed", "value": uri, "pinned": false],
                        [
                            "id": "two", "type": "feed",
                            "value": "at://did:plc:reader/app.bsky.feed.generator/deleted", "pinned": true
                        ],
                        [
                            "id": "three", "type": "list",
                            "value": "at://did:plc:reader/app.bsky.graph.list/friends", "pinned": true
                        ]
                    ]
                ]
            return (200, try JSONSerialization.data(withJSONObject: ["preferences": [pref]]))
        case "/xrpc/app.bsky.feed.getFeedGenerators":
            return (
                200,
                try JSONSerialization.data(withJSONObject: [
                    "feeds": [
                        [
                            "uri": uri, "cid": "cid", "did": "did:web:feed.example", "displayName": "Nature",
                            "avatar": "https://example.test/avatar.png",
                            "creator": ["did": "did:plc:reader", "handle": "reader.example"],
                            "indexedAt": "2024-05-06T12:34:56Z"
                        ]
                    ]
                ])
            )
        case "/xrpc/app.bsky.feed.getFeed":
            let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
            XCTAssertEqual(query?.first { $0.name == "feed" }?.value, uri)
            XCTAssertEqual(query?.first { $0.name == "cursor" }?.value, "next")
            XCTAssertEqual(query?.first { $0.name == "limit" }?.value, "70")
            return status == 200
                ? (200, Data("{\"feed\":[],\"cursor\":\"last\"}".utf8))
                : (status, Data("{\"error\":\"NotFound\",\"message\":\"Feed not found\"}".utf8))
        case "/xrpc/app.bsky.feed.getTimeline":
            let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
            XCTAssertEqual(query?.first { $0.name == "limit" }?.value, "70")
            return (200, Data("{\"feed\":[]}".utf8))
        default:
            XCTFail("Unexpected request: \(request.url?.absoluteString ?? "nil")")
            return (404, Data("{}".utf8))
        }
    }
}