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

geesawra.industries/old-fella

Old people's social media app

0
1

fix(media): add GIF display controls

Merged geesawra.industries asked to merge into main from geesawra.industries/old-fella:fix/gif-visibility-reviewed
Sources/Oldsky/BlueskyService.swift+31−4
@@ -297,6 +297,14 @@ struct MockBlueskyService: BlueskyService {
]
)
}
if ProcessInfo.processInfo.arguments.contains("-ui-testing-gif") {
let image = URL(string: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAAAAAAALAAAAAABAAEAAAIBRAAh+QQAAAAAACwAAAAAAQABAAACAUQAOw==")!
posts[0].gifURLs = [image]
posts[0].imageDescriptions[image] = "A moving square."
posts[1].imageURLs = [image]
posts[1].gifURLs = [image]
posts[0].quote = Post.Quote(postID: "post-2", author: authors[1], text: "Quoted GIF", gifURLs: [image])
}
if ProcessInfo.processInfo.arguments.contains("-ui-testing-video") {
posts[0].videoURLs = [URL(string: "https://example.invalid/video.mp4")!]
}
@@ -1155,6 +1163,7 @@ actor ATProtoBlueskyService: BlueskyService {
let mediaLinks = Self.urls(in: rawText) + Array(facetURLs)
let images = Self.uniqueURLs(attachedMedia.images + mediaLinks.filter { Post.destination(for: $0) == .image })
let videos = Self.uniqueURLs(attachedMedia.videos + mediaLinks.filter { Post.destination(for: $0) == .video })
let gifs = Self.uniqueURLs(attachedMedia.gifs + mediaLinks.filter { Post.destination(for: $0) == .gif })
let inlineGIFVideos = Self.uniqueURLs(attachedMedia.inlineGIFVideos)
let likeURI = (object["viewer"] as? [String: Any])?["like"] as? String
let repostURI = (object["viewer"] as? [String: Any])?["repost"] as? String
@@ -1162,10 +1171,10 @@ actor ATProtoBlueskyService: BlueskyService {
let root = reply?["root"] as? [String: Any]
let parent = reply?["parent"] as? [String: Any]
let quoteURI = Self.quoteURI(from: embed) ?? Self.quoteURI(from: record["embed"] as? [String: Any] ?? [:])
return Post(id: uri, cid: cid, author: Post.Author(id: did, name: author["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(author["avatar"])), text: rawText, likeCount: object["likeCount"] as? Int ?? 0, repostCount: object["repostCount"] as? Int ?? 0, isLiked: likeURI != nil, isReposted: repostURI != nil, imageURLs: images, videoURLs: videos, inlineGIFVideoURLs: inlineGIFVideos, replyRootURI: root?["uri"] as? String, replyRootCID: root?["cid"] as? String, replyParentURI: parent?["uri"] as? String, replyParentCID: parent?["cid"] as? String, likeURI: likeURI, repostURI: repostURI, links: links, facets: facets, quote: quoteURI.map { Self.quote(from: embed, postID: $0) }, replyIDs: [], replyCount: object["replyCount"] as? Int ?? 0, createdAt: Self.postDate(record["createdAt"]) ?? Self.postDate(object["indexedAt"]), imageDescriptions: Self.imageDescriptions(from: embed))
return Post(id: uri, cid: cid, author: Post.Author(id: did, name: author["displayName"] as? String ?? handle, handle: handle, avatarURL: Self.url(author["avatar"])), text: rawText, likeCount: object["likeCount"] as? Int ?? 0, repostCount: object["repostCount"] as? Int ?? 0, isLiked: likeURI != nil, isReposted: repostURI != nil, imageURLs: images, videoURLs: videos, gifURLs: gifs, inlineGIFVideoURLs: inlineGIFVideos, replyRootURI: root?["uri"] as? String, replyRootCID: root?["cid"] as? String, replyParentURI: parent?["uri"] as? String, replyParentCID: parent?["cid"] as? String, likeURI: likeURI, repostURI: repostURI, links: links, facets: facets, quote: quoteURI.map { Self.quote(from: embed, postID: $0) }, replyIDs: [], replyCount: object["replyCount"] as? Int ?? 0, createdAt: Self.postDate(record["createdAt"]) ?? Self.postDate(object["indexedAt"]), imageDescriptions: Self.imageDescriptions(from: embed))
}
private static func attachedMedia(from embed: [String: Any]) -> (images: [URL], videos: [URL], inlineGIFVideos: [URL]) {
private static func attachedMedia(from embed: [String: Any]) -> (images: [URL], videos: [URL], gifs: [URL], inlineGIFVideos: [URL]) {
let media = embed["media"] as? [String: Any] ?? embed
let images = (media["images"] as? [[String: Any]] ?? []).compactMap { image in
let url = image["fullsize"] as? String ?? image["fullSize"] as? String ?? image["thumb"] as? String
@@ -1174,7 +1183,10 @@ actor ATProtoBlueskyService: BlueskyService {
let playlist = [media["playlist"] as? String].compactMap { $0 }.compactMap(URL.init(string:))
let videos = media["presentation"] as? String == "gif" ? [] : playlist
let inlineGIFVideos = media["presentation"] as? String == "gif" ? playlist : []
return (images, videos, inlineGIFVideos)
let external = media["external"] as? [String: Any]
let externalURL = (external?["uri"] as? String).flatMap(URL.init(string:))
let gifs = [externalURL].compactMap { $0 }.filter { ["http", "https"].contains($0.scheme?.lowercased() ?? "") && Post.destination(for: $0) == .gif }
return (images, videos, gifs, inlineGIFVideos)
}
private static func imageDescriptions(from embed: [String: Any]) -> [URL: String] {
@@ -1187,6 +1199,17 @@ actor ATProtoBlueskyService: BlueskyService {
!alt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue }
descriptions[url] = alt
}
if let external = media["external"] as? [String: Any],
let rawURL = external["uri"] as? String, let url = URL(string: rawURL),
Post.destination(for: url) == .gif,
let description = external["description"] as? String,
!description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
descriptions[url] = description
}
if let rawURL = media["playlist"] as? String, let url = URL(string: rawURL),
let alt = media["alt"] as? String, !alt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
descriptions[url] = alt
}
return descriptions
}
@@ -1213,14 +1236,18 @@ actor ATProtoBlueskyService: BlueskyService {
}
let embeds = record["embeds"] as? [[String: Any]] ?? []
let media = embeds.map { attachedMedia(from: $0) }
let urls = Self.urls(in: text)
let facets = decodedFacets(from: value["facets"], text: text)
let urls = Self.urls(in: text) + facets.compactMap { facet -> URL? in
if case .link(let url) = facet.feature { return url }
return nil
}
return Post.Quote(
postID: postID,
author: Post.Author(id: did, name: author["displayName"] as? String ?? handle, handle: handle, avatarURL: url(author["avatar"])),
text: text,
facets: facets,
imageURLs: uniqueURLs(media.flatMap(\.images) + urls.filter { Post.destination(for: $0) == .image }),
gifURLs: uniqueURLs(media.flatMap(\.gifs) + urls.filter { Post.destination(for: $0) == .gif }),
inlineGIFVideoURLs: uniqueURLs(media.flatMap(\.inlineGIFVideos)),
createdAt: postDate(value["createdAt"]) ?? postDate(record["indexedAt"]),
imageDescriptions: embeds.reduce(into: [:]) { result, embed in
Sources/Oldsky/Models.swift+5−1
@@ -35,6 +35,7 @@ struct NotificationPage: Equatable {
enum MediaDestination: Equatable {
case image
case gif
case video
case ordinaryLink
}
@@ -90,6 +91,7 @@ struct Post: Identifiable, Equatable {
var text: String? = nil
var facets: [PostFacet] = []
var imageURLs: [URL] = []
var gifURLs: [URL] = []
var inlineGIFVideoURLs: [URL] = []
var createdAt: Date? = nil
var imageDescriptions: [URL: String] = [:]
@@ -105,6 +107,7 @@ struct Post: Identifiable, Equatable {
var isReposted: Bool
var imageURLs: [URL]
var videoURLs: [URL] = []
var gifURLs: [URL] = []
var inlineGIFVideoURLs: [URL] = []
var replyRootURI: String? = nil
var replyRootCID: String? = nil
@@ -122,7 +125,8 @@ struct Post: Identifiable, Equatable {
static func destination(for url: URL) -> MediaDestination {
let path = url.path.lowercased()
if [".jpg", ".jpeg", ".png", ".webp", ".gif"].contains(where: path.hasSuffix) {
if path.hasSuffix(".gif") { return .gif }
if [".jpg", ".jpeg", ".png", ".webp"].contains(where: path.hasSuffix) {
return .image
}
if [".mp4", ".m4v", ".mov", ".m3u8"].contains(where: path.hasSuffix) {
Sources/Oldsky/OldskyApp.swift+393−73
466 lines changed: not loaded until asked for.
Tests/OldskyTests/AppModelTests.swift+97−1
@@ -1,6 +1,26 @@
import XCTest
@testable import Oldsky
final class ImageTestProtocol: URLProtocol {
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
guard let url = request.url, url.path != "/wait" else { return }
let response = HTTPURLResponse(url: url, statusCode: url.path == "/error" ? 503 : 200, httpVersion: "HTTP/1.1", headerFields: nil)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
if url.path == "/gif" {
client?.urlProtocol(self, didLoad: Data("GIF89a".utf8))
client?.urlProtocol(self, didLoad: Data(repeating: 0, count: GIFDownload.byteLimit))
} else {
client?.urlProtocol(self, didLoad: Data(repeating: 0, count: 1024))
}
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
}
@MainActor
final class AppModelTests: XCTestCase {
func testNotificationGroupsKeepOrderAndSeparateReasonsAndPosts() {
@@ -393,9 +413,85 @@ final class AppModelTests: XCTestCase {
XCTAssertNotNil(model.errorMessage)
}
func testGIFDecoderRejectsOversizedDimensions() throws {
var data = try XCTUnwrap(Data(base64Encoded: "R0lGODlhAQABAIAAAAAAAP///yH5BAAAAAAALAAAAAABAAEAAAIBRAAh+QQAAAAAACwAAAAAAQABAAACAUQAOw=="))
XCTAssertTrue(RemoteImageDecoder.isGIF(data))
XCTAssertFalse(RemoteImageDecoder.isGIF(Data([0x89, 0x50, 0x4e, 0x47])))
XCTAssertNotNil(RemoteImageDecoder.decode(data))
data[6] = 0xff
data[7] = 0x7f
data[8] = 0xff
data[9] = 0x7f
XCTAssertNil(RemoteImageDecoder.decode(data))
}
func testDownloadSizeLimitAppliesOnlyToGIFs() throws {
var data = Data(repeating: 0, count: GIFDownload.byteLimit + 1)
XCTAssertNoThrow(try GIFDownload.validate(data))
data.replaceSubrange(0..<6, with: Data("GIF89a".utf8))
XCTAssertThrowsError(try GIFDownload.validate(data))
data.removeLast()
XCTAssertNoThrow(try GIFDownload.validate(data))
}
func testChunkedDownloadLimitsGIFWithoutLimitingOtherImages() throws {
var gif = ImageDownloadBuffer()
try gif.append(Data("GIF".utf8))
try gif.append(Data("89a".utf8))
try gif.append(Data(repeating: 0, count: GIFDownload.byteLimit - 6))
XCTAssertThrowsError(try gif.append(Data([0])))
XCTAssertEqual(gif.data.count, GIFDownload.byteLimit)
var image = ImageDownloadBuffer()
try image.append(Data([0x89, 0x50, 0x4e, 0x47]))
try image.append(Data(repeating: 0, count: GIFDownload.byteLimit))
XCTAssertEqual(image.data.count, GIFDownload.byteLimit + 4)
try image.append(Data(repeating: 0, count: GIFDownload.imageByteLimit - image.data.count))
XCTAssertThrowsError(try image.append(Data([0]))) { error in
XCTAssertEqual(error as? ImageDownloadError, .imageTooLarge)
}
XCTAssertEqual(image.data.count, GIFDownload.imageByteLimit)
}
func testDownloadRejectsHTTPError() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [ImageTestProtocol.self]
do {
_ = try await GIFDownload.load(URL(string: "https://example.test/error")!, configuration: configuration)
XCTFail("Expected an HTTP error")
} catch let error as ImageDownloadError {
XCTAssertEqual(error, .httpStatus(503))
}
}
func testDownloadEnforcesLimitWithoutContentLength() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [ImageTestProtocol.self]
do {
_ = try await GIFDownload.load(URL(string: "https://example.test/gif")!, configuration: configuration)
XCTFail("Expected a GIF size error")
} catch let error as ImageDownloadError {
XCTAssertEqual(error, .gifTooLarge)
}
}
func testDownloadCancellation() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [ImageTestProtocol.self]
let task = Task { try await GIFDownload.load(URL(string: "https://example.test/wait")!, configuration: configuration) }
task.cancel()
do {
_ = try await task.value
XCTFail("Expected cancellation")
} catch is CancellationError {
} catch let error as URLError {
XCTAssertEqual(error.code, .cancelled)
}
}
func testMediaDestinations() {
XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/photo.JPG")!), .image)
XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/clip.gif")!), .image)
XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/clip.gif?size=1")!), .gif)
XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/movie.mp4")!), .video)
XCTAssertEqual(Post.destination(for: URL(string: "https://example.com/article")!), .ordinaryLink)
}
Tests/OldskyTests/ATProtoServiceTests.swift+14−2
@@ -198,6 +198,12 @@ final class ATProtoServiceTests: XCTestCase {
"presentation": "gif"
]
])
let facetGIFText = "see animation"
let externalGIF = post("external-gif", embed: [
"$type": "app.bsky.embed.recordWithMedia#view",
"record": ["record": ["uri": quotedURI, "author": ["did": "did:plc:quoted", "handle": "quoted.example"], "value": ["text": facetGIFText, "facets": [["index": ["byteStart": 0, "byteEnd": facetGIFText.utf8.count], "features": [["$type": "app.bsky.richtext.facet#link", "uri": "https://example.test/facet.gif"]]]]], "embeds": [["$type": "app.bsky.embed.external#view", "external": ["uri": "https://example.test/quoted.gif?size=1", "title": "GIF", "description": "Quoted GIF"]]]]],
"media": ["$type": "app.bsky.embed.external#view", "external": ["uri": "https://static.klipy.com/example.gif?hh=498&mp4=abc", "title": "GIF", "description": "A person nods"]]
])
let textMedia = post(
"text-media",
text: "GIF https://cdn.example.test/loop.gif video https://cdn.example.test/clip.mp4 site https://example.test/article"
@@ -208,7 +214,7 @@ final class ATProtoServiceTests: XCTestCase {
embed: ["$type": "app.bsky.embed.images#view", "images": [["thumb": "https://cdn.example.test/photo-thumb.jpg", "fullsize": "https://cdn.example.test/photo.jpg", "alt": "Photo"]]]
)
let responseData = try JSONSerialization.data(withJSONObject: [
"feed": [attachedImage, attachedVideo, attachedGIFVideo, nestedImage, nestedVideo, nestedGIFVideo, textMedia, duplicateTextImage].map { ["post": $0] }
"feed": [attachedImage, attachedVideo, attachedGIFVideo, nestedImage, nestedVideo, nestedGIFVideo, externalGIF, textMedia, duplicateTextImage].map { ["post": $0] }
])
StubURLProtocol.clearRequests()
StubURLProtocol.handler = { request in
@@ -264,7 +270,13 @@ final class ATProtoServiceTests: XCTestCase {
XCTAssertEqual(posts["at://did:plc:media/app.bsky.feed.post/nested-gif-video"]?.videoURLs, [])
XCTAssertEqual(posts["at://did:plc:media/app.bsky.feed.post/nested-gif-video"]?.inlineGIFVideoURLs, [nestedGIFVideoURL])
let textPost = try XCTUnwrap(posts["at://did:plc:media/app.bsky.feed.post/text-media"])
XCTAssertEqual(textPost.imageURLs, [gifURL])
XCTAssertEqual(textPost.imageURLs, [])
XCTAssertEqual(textPost.gifURLs, [gifURL])
let externalPost = try XCTUnwrap(posts["at://did:plc:media/app.bsky.feed.post/external-gif"])
XCTAssertEqual(externalPost.gifURLs, [URL(string: "https://static.klipy.com/example.gif?hh=498&mp4=abc")!])
XCTAssertEqual(externalPost.imageDescriptions[URL(string: "https://static.klipy.com/example.gif?hh=498&mp4=abc")!], "A person nods")
XCTAssertEqual(externalPost.quote?.gifURLs, [URL(string: "https://example.test/quoted.gif?size=1")!, URL(string: "https://example.test/facet.gif")!])
XCTAssertEqual(externalPost.quote?.postID, quotedURI)
XCTAssertEqual(textPost.videoURLs, [directVideoURL])
XCTAssertEqual(textPost.inlineGIFVideoURLs, [])
let facetLinks = Set(textPost.facets.compactMap { facet -> URL? in
Tests/OldskyUITests/OldskyUITests.swift+83−1
@@ -68,6 +68,88 @@ final class OldskyUITests: XCTestCase {
XCTAssertTrue(profile.isHittable)
}
func testGIFSettingControlsPostAndQuotedGIFs() {
let app = XCUIApplication()
app.launchArguments = ["-ui-testing", "-ui-testing-gif"]
app.launch()
app.buttons["demoSignInButton"].tap()
XCTAssertTrue(app.descendants(matching: .any)["inlineGIF"].firstMatch.waitForExistence(timeout: 5))
let gif = app.buttons["A moving square."].firstMatch
XCTAssertTrue(gif.waitForExistence(timeout: 5))
app.swipeUp()
gif.tap()
XCTAssertTrue(app.buttons["imageViewerClose"].waitForExistence(timeout: 5))
app.buttons["imageDescriptionButton"].tap()
XCTAssertTrue(app.staticTexts["A moving square."].waitForExistence(timeout: 5))
app.buttons["imageViewerClose"].tap()
XCTAssertEqual(app.buttons.matching(identifier: "showGIFButton").count, 0)
let quote = app.cells.containing(.button, identifier: "postText-post-1").firstMatch
XCTAssertTrue(quote.buttons["showReplyGIFButton"].firstMatch.waitForExistence(timeout: 5))
let replyContext = app.descendants(matching: .any)["replyPostContext-post-1"].firstMatch
for _ in 0..<5 {
if replyContext.buttons["showReplyGIFButton"].exists { break }
app.swipeUp()
}
XCTAssertTrue(replyContext.buttons["showReplyGIFButton"].firstMatch.waitForExistence(timeout: 5))
app.tabBars.buttons["Settings"].tap()
let setting = app.switches["showGIFsInline"]
XCTAssertTrue(setting.waitForExistence(timeout: 5))
setting.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()
XCTAssertEqual(String(describing: setting.value ?? ""), "0")
app.tabBars.buttons["Following"].tap()
let buttons = app.buttons.matching(identifier: "showGIFButton")
XCTAssertTrue(app.buttons["showReplyGIFButton"].firstMatch.waitForExistence(timeout: 5))
XCTAssertTrue(buttons.firstMatch.waitForExistence(timeout: 5))
buttons.firstMatch.tap()
XCTAssertTrue(app.buttons["A moving square."].firstMatch.waitForExistence(timeout: 5))
XCTAssertFalse(quote.buttons["showGIFButton"].exists)
}
func testQuotedGIFNeedsOnlyOneRevealWhenSettingIsOff() {
let app = XCUIApplication()
app.launchArguments = ["-ui-testing", "-ui-testing-gif", "-ui-testing-signed-in"]
app.launch()
app.tabBars.buttons["Settings"].tap()
let setting = app.switches["showGIFsInline"]
XCTAssertTrue(setting.waitForExistence(timeout: 5))
setting.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()
XCTAssertEqual(String(describing: setting.value ?? ""), "0")
app.tabBars.buttons["Following"].tap()
let post = app.cells.containing(.button, identifier: "postText-post-1").firstMatch
let reveal = post.buttons["showReplyGIFButton"].firstMatch
XCTAssertTrue(reveal.waitForExistence(timeout: 5))
reveal.tap()
XCTAssertTrue(post.buttons["GIF"].firstMatch.waitForExistence(timeout: 5))
XCTAssertFalse(post.buttons["showReplyGIFButton"].exists)
XCTAssertTrue(post.buttons["showGIFButton"].exists)
}
func testDirectReplyGIFFollowsSetting() {
let app = XCUIApplication()
app.launchArguments = ["-ui-testing", "-ui-testing-gif", "-ui-testing-signed-in"]
app.launch()
let reply = app.cells.containing(.button, identifier: "postText-post-2").firstMatch
for _ in 0..<5 {
if reply.exists { break }
app.swipeUp()
}
XCTAssertTrue(reply.waitForExistence(timeout: 5))
XCTAssertTrue(reply.descendants(matching: .any)["inlineGIF"].firstMatch.waitForExistence(timeout: 5))
XCTAssertFalse(reply.buttons["showGIFButton"].exists)
app.tabBars.buttons["Settings"].tap()
let setting = app.switches["showGIFsInline"]
XCTAssertTrue(setting.waitForExistence(timeout: 5))
setting.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()
XCTAssertEqual(String(describing: setting.value ?? ""), "0")
app.tabBars.buttons["Following"].tap()
for _ in 0..<5 {
if reply.buttons["showGIFButton"].exists { break }
app.swipeUp()
}
XCTAssertTrue(reply.buttons["showGIFButton"].firstMatch.waitForExistence(timeout: 5))
}
func testVideoViewerHasOneCloseButton() {
let app = XCUIApplication()
app.launchArguments = ["-ui-testing", "-ui-testing-video"]
@@ -646,7 +728,7 @@ final class OldskyUITests: XCTestCase {
let grid = app.cells.containing(.button, identifier: "postText-post-1").firstMatch.descendants(matching: .any)["postImageGrid"]
XCTAssertTrue(grid.waitForExistence(timeout: 5))
let gridImage = grid.images["Attached image"]
let gridImage = grid.buttons["Attached image"]
XCTAssertTrue(gridImage.waitForExistence(timeout: 5))
let tile = gridImage
XCTAssertTrue(tile.waitForExistence(timeout: 5))