From 6f9a00d728c2cdb370372f6841bcd77eb46ac39e Mon Sep 17 00:00:00 2001 From: Askia Linder Date: Sat, 21 Jun 2025 17:32:29 +0200 Subject: [PATCH] Handle npub correctly in draft notes Damus stores npub as both Strings and URLs in NSAttributedString.Key.link when a note is saved as a draft. Make Damus correctly handle both when we retrieve and store drafts. Changelog-Changed: Handle npub correctly in draft notes Signed-off-by: Askeew Closes: https://github.com/damus-io/damus/issues/2923 --- damus/Views/PostView.swift | 4 +++- damusTests/PostViewTests.swift | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/damus/Views/PostView.swift b/damus/Views/PostView.swift index 5d31e90a..2152bd0b 100644 --- a/damus/Views/PostView.swift +++ b/damus/Views/PostView.swift @@ -863,7 +863,9 @@ func build_post(state: DamusState, post: NSAttributedString, action: PostAction, func build_post(state: DamusState, post: NSAttributedString, action: PostAction, uploadedMedias: [UploadedMedia], pubkeys: [Pubkey]) -> NostrPost { let post = NSMutableAttributedString(attributedString: post) post.enumerateAttributes(in: NSRange(location: 0, length: post.length), options: []) { attributes, range, stop in - if let link = attributes[.link] as? String { + let linkValue = attributes[.link] + let link = (linkValue as? String) ?? (linkValue as? URL)?.absoluteString + if let link { let nextCharIndex = range.upperBound if nextCharIndex < post.length, let nextChar = post.attributedSubstring(from: NSRange(location: nextCharIndex, length: 1)).string.first, diff --git a/damusTests/PostViewTests.swift b/damusTests/PostViewTests.swift index 7b8ddc2b..72b1e9b3 100644 --- a/damusTests/PostViewTests.swift +++ b/damusTests/PostViewTests.swift @@ -176,6 +176,48 @@ final class PostViewTests: XCTestCase { XCTAssertEqual(post.tags, [["q", test_note.id.hex()]]) } + + func testBuildPostRecognizesStringsAsNpubs() throws { + // given + let expectedLink = "nostr:\(test_pubkey.npub)" + let content = NSMutableAttributedString(string: "@test", attributes: [ + NSAttributedString.Key.link: "damus:\(expectedLink)" + ]) + + // when + let post = build_post( + state: test_damus_state, + post: content, + action: .posting(.user(test_pubkey)), + uploadedMedias: [], + pubkeys: [] + ) + + // then + XCTAssertEqual(post.content, expectedLink) + } + + func testBuildPostRecognizesUrlsAsNpubs() throws { + // given + guard let npubUrl = URL(string: "damus:nostr:\(test_pubkey.npub)") else { + return XCTFail("Could not create URL") + } + let content = NSMutableAttributedString(string: "@test", attributes: [ + NSAttributedString.Key.link: npubUrl + ]) + + // when + let post = build_post( + state: test_damus_state, + post: content, + action: .posting(.user(test_pubkey)), + uploadedMedias: [], + pubkeys: [] + ) + + // then + XCTAssertEqual(post.content, "nostr:\(test_pubkey.npub)") + } } func checkMentionLinkEditorHandling(