Compare commits

..

2 Commits

Author SHA1 Message Date
tyiu 8e852ed742 Remove language filtering from Universe feed because language detection can be inaccurate
Changelog-Removed: Removed language filtering from Universe feed because language detection can be inaccurate

Signed-off-by: Terry Yiu <git@tyiu.xyz>
2025-01-19 13:21:31 -05:00
tyiu 7b4fc79030 Translate notes even if they are in a preferred language but not the current language as that is what users expect
Changelog-Fixed: Translate notes even if they are in a preferred language but not the current language as that is what users expect

Signed-off-by: Terry Yiu <git@tyiu.xyz>
2025-01-19 13:07:51 -05:00
119 changed files with 1433 additions and 7230 deletions
-52
View File
@@ -1,52 +0,0 @@
---
name: App release process
about: Begin preparing for a new app release
title: 'Release: '
labels: release-tasks
assignees: ''
---
A new version release. Please attempt to follow the release process steps below in the order they are shown.
## TestFlight release candidates
### Release candidate 1
**Version:** _[Enter full build information for the release candidate, including major and minor version number, build number, and commit hash]_
1. [ ] Merge in all needed changes to `master`
2. [ ] Check CI, make sure it is passing
3. [ ] Prepare preliminary changelog as a draft PR: _[Enter PR link to changelog here]_
4. [ ] Make a _release_ build and submit to the internal TestFlight group via our new Release candidate workflow in Xcode Cloud.
5. [ ] Prepare short screencast style video with main changes for the announcement
6. [ ] Publish release build to these TestFlight groups:
- [ ] Alpha testers group
- [ ] Translators group
- [ ] Purple group
7. [ ] Publish announcement on Nostr
_[Duplicate this release candidate section if there is more than one release candidate]_
## App Store release
1. [ ] Release candidate checks:
- [ ] Release candidate has been on Purple TestFlight for at least one week
- [ ] No blocker issues came from feedback from Purple users (double-check)
- [ ] Check with stakeholders
- [ ] Check with developers & product for any release showstoppers (e.g., critical newfound bugs)
2. [ ] Thorough check on release notes
3. [ ] Submit to App Store review (with manual publishing setting enabled)
4. [ ] Get App Store approval from Apple
5. [ ] Prepare announcement
7. [ ] Publish on the App Store and make announcement
8. [ ] Publish changelog and tag commit hash corresponding to the release
9. [ ] Perform a version bump on the repository, in preparation for the next release
## Notes/others
_Enter any relevant notes here_
-1
View File
@@ -6,7 +6,6 @@ _[Please provide a summary of the changes in this PR.]_
- [ ] I have read (or I am familiar with) the [Contribution Guidelines](../docs/CONTRIBUTING.md)
- [ ] I have tested the changes in this PR
- [ ] I have opened or referred to an existing github issue related to this change.
- [ ] My PR is either small, or I have split it into smaller logical commits that are easier to review
- [ ] I have added the signoff line to all my commits. See [Signing off your work](../docs/CONTRIBUTING.md#sign-your-work---the-developers-certificate-of-origin)
- [ ] I have added appropriate changelog entries for the changes in this PR. See [Adding changelog entries](../docs/CONTRIBUTING.md#add-changelog-changed-changelog-fixed-etc)
-5
View File
@@ -1,5 +0,0 @@
### Acknowledgements and licenses
1. This product contains code derived from [Nostr SDK iOS](https://github.com/nostr-sdk/nostr-sdk-ios). [License](https://github.com/nostr-sdk/nostr-sdk-ios/blob/40df800c6749d7ce0b6fd7328e76cbc0dc71c87b/LICENSE)
2. This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/). [License](https://github.com/krzyzanowskim/CryptoSwift/blob/e74bbbfbef939224b242ae7c342a90e60b88b5ce/LICENSE)
-112
View File
@@ -1,115 +1,3 @@
## [1.13.1] - 2025-03-21
### Fixed
- Fixed an issue where threads would not load properly (Daniel DAquino)
[1.13.1]: https://github.com/damus-io/damus/releases/tag/v1.13.1
## [1.13] - 2025-03-14
### Added
- Added local persistence of note drafts (Daniel DAquino)
- Added user-friendly error view for errors around the app that would not fit in other places (Daniel DAquino)
- Coinos connection button in Wallet view (ericholguin)
- Added Alby Go to mobile wallets selection menu (Tomek ⚡ K)
- Minor accessibility improvements around picture editing and onboarding (Daniel DAquino)
- Profile image cropping tools (Daniel DAquino)
- Added Conversations tab to profiles (Terry Yiu)
- Added profile pictures to push notifications (William Casarin)
### Changed
- Don't show reposts for the same note more than once in your home feed (William Casarin)
- Improved profile image bandwidth optimization (Daniel DAquino)
- Improved reliability of picture selector (Daniel DAquino)
- Changed spaces to newlines in new posts to provide cleaner separation between text, uploaded media, and quoted notes (Terry Yiu)
### Fixed
- Fixed issue where some push notifications would not open in the app and leave users confused (Daniel DAquino)
- Fixed issue where app would need a restart for new NWC wallets to work (Daniel DAquino)
- Fixed overly sensitive horizontal swipe on thread chat view (Daniel DAquino)
- Trim whitespaces from Lightning addresses (Terry Yiu)
- Fixed translation export script by upgrading nostr-sdk-swift dependency to support Mac Catalyst (Terry Yiu)
- Fixed issue where users continue to receive push notifications after logout (Daniel DAquino)
- Fixed an issue where events on a thread view would occasionally disappear (Daniel DAquino)
- Improved robustness of the URL handler (Daniel DAquino)
- Translate notes even if they are in a preferred language but not the current language as that is what users expect (Terry Yiu)
- Cancel ongoing uploading operations after the user cancels the post (Swift Coder)
- Fixed link and photo sharing support on macOS (Swift Coder)
- Fix bug where profile view was showing more than just the notes and replies on the notes / notes & replies tabs (Terry Yiu)
- Fixed reposts banner to be localizable (Terry Yiu)
### Removed
- Removed language filtering from Universe feed because language detection can be inaccurate (Terry Yiu)
- Removed mystery tabs meant to fix tab switching bug that no longer exists (Terry Yiu)
[1.13](https://github.com/damus-io/damus/releases/tag/v1.13): https://github.com/damus-io/damus/releases/tag/v1.13
## [1.12.3] - 2025-02-06
### Added
- Purple members who have been active for more than a year now get a special badge (Daniel DAquino)
### Changed
- Improved clarity of the mute button to indicate it can be used for blocking a user (Daniel DAquino)
- Made the microphone access request message more clear to users (Daniel DAquino)
[v1.12.3]: https://github.com/damus-io/damus/releases/tag/v1.12.3
## [1.12](https://github.com/damus-io/damus/releases/tag/v1.12) - 2024-12-20
### Added
- Render Gif and video files while composing posts (Swift Coder)
- Add profile info text in stretchable banner with follow button (Swift Coder)
- Paste Gif image similar to jpeg and png files (Swift Coder)
### Changed
- Improved UX around the label for searching words (Daniel DAquino)
- Improved accessibility support on some elements (Daniel DAquino)
### Fixed
- Fixed issue where the "next" button would appear hidden and hard to click on the create account view (Daniel DAquino)
- Fix non scrollable wallet screen (Swift Coder)
- Fixed suggested users category titles to be localizable (Terry Yiu)
- Fixed GradientFollowButton to have consistent width and autoscale text limited to 1 line (Terry Yiu)
- Fixed right-to-left localization issues (Terry Yiu)
- Fixed AddMuteItemView to trim leading and trailing whitespaces from mute text and disallow adding text with only whitespaces (Terry Yiu)
- Fixed SideMenuView text to autoscale and limit to 1 line (Terry Yiu)
- Fixed an issue where a profile would need to be input twice in the search to be found (Daniel DAquino)
- Fixed non-breaking spaces in localized strings (Terry Yiu)
- Fixed localization issue on Add mute item button (Terry Yiu)
- Replace non-breaking spaces with regular spaces as Apple's NSLocalizedString macro does not seem to work with it (Terry Yiu)
- Fixed localization issues in RelayConfigView (Terry Yiu)
- Fix duplicate uploads (Swift Coder)
- Remove duplicate pubkey from Follow Suggestion list (Swift Coder)
- Fix Page control indicator (Swift Coder)
- Fix damus sharing issues (Swift Coder)
- Fixed issue where banner edit button is unclickable (Daniel DAquino)
- Handle empty notification pages by displaying suitable text (Swift Coder)
[v1.12](https://github.com/damus-io/damus/releases/tag/v1.12): [https://github.com/damus-io/damus/releases/tag/v1.12]
## [v1.11(10)](https://github.com/damus-io/damus/releases/tag/v1.11-10) - 2024-11-18
### Added
@@ -2,8 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.usernotifications.communication</key>
<true/>
<key>com.apple.developer.kernel.extended-virtual-addressing</key>
<true/>
<key>com.apple.security.app-sandbox</key>
@@ -5,32 +5,15 @@
// Created by Daniel DAquino on 2023-11-10.
//
import Kingfisher
import ImageIO
import UserNotifications
import Foundation
import UniformTypeIdentifiers
import Intents
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
private func configureKingfisherCache() {
guard let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.DAMUS_APP_GROUP_IDENTIFIER) else {
return
}
let cachePath = groupURL.appendingPathComponent(Constants.IMAGE_CACHE_DIRNAME)
if let cache = try? ImageCache(name: "sharedCache", cacheDirectoryURL: cachePath) {
KingfisherManager.shared.cache = cache
}
}
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
configureKingfisherCache()
self.contentHandler = contentHandler
guard let nostr_event_json = request.content.userInfo["nostr_event"] as? String,
@@ -57,16 +40,9 @@ class NotificationService: UNNotificationServiceExtension {
return
}
let sender_profile = {
let txn = state.ndb.lookup_profile(nostr_event.pubkey)
let profile = txn?.unsafeUnownedValue?.profile
let picture = ((profile?.picture.map { URL(string: $0) }) ?? URL(string: robohash(nostr_event.pubkey)))!
return ProfileBuf(picture: picture,
name: profile?.name,
display_name: profile?.display_name,
nip05: profile?.nip05)
}()
let sender_pubkey = nostr_event.pubkey
let txn = state.ndb.lookup_profile(nostr_event.pubkey)
let profile = txn?.unsafeUnownedValue?.profile
let name = Profile.displayName(profile: profile, pubkey: nostr_event.pubkey).displayName
// Don't show notification details that match mute list.
// TODO: Remove this code block once we get notification suppression entitlement from Apple. It will be covered by the `guard should_display_notification` block
@@ -80,7 +56,7 @@ class NotificationService: UNNotificationServiceExtension {
contentHandler(content)
return
}
guard should_display_notification(state: state, event: nostr_event, mode: .push) else {
Log.debug("should_display_notification failed", for: .push_notifications)
// We should not display notification for this event. Suppress notification.
@@ -89,7 +65,7 @@ class NotificationService: UNNotificationServiceExtension {
contentHandler(request.content)
return
}
guard let notification_object = generate_local_notification_object(from: nostr_event, state: state) else {
Log.debug("generate_local_notification_object failed", for: .push_notifications)
// We could not process this notification. Probably an unsupported nostr event kind. Suppress.
@@ -98,58 +74,15 @@ class NotificationService: UNNotificationServiceExtension {
contentHandler(request.content)
return
}
Task {
let sender_dn = DisplayName(name: sender_profile.name, display_name: sender_profile.display_name, pubkey: sender_pubkey)
guard let (improvedContent, _) = await NotificationFormatter.shared.format_message(displayName: sender_dn.displayName, notify: notification_object, state: state) else {
guard let (improvedContent, _) = await NotificationFormatter.shared.format_message(displayName: name, notify: notification_object, state: state) else {
Log.debug("NotificationFormatter.format_message failed", for: .push_notifications)
return
}
do {
var options: [AnyHashable: Any] = [:]
if let imageSource = CGImageSourceCreateWithURL(sender_profile.picture as CFURL, nil),
let uti = CGImageSourceGetType(imageSource) {
options[UNNotificationAttachmentOptionsTypeHintKey] = uti
}
let attachment = try UNNotificationAttachment(identifier: sender_profile.picture.absoluteString, url: sender_profile.picture, options: options)
improvedContent.attachments = [attachment]
} catch {
Log.error("failed to get notification attachment: %s", for: .push_notifications, error.localizedDescription)
}
let kind = nostr_event.known_kind
// these aren't supported yet
if !(kind == .text || kind == .dm) {
contentHandler(improvedContent)
return
}
// rich communication notifications for kind1, dms, etc
let message_intent = await message_intent_from_note(ndb: state.ndb,
sender_profile: sender_profile,
content: improvedContent.body,
note: nostr_event,
our_pubkey: state.keypair.pubkey)
improvedContent.threadIdentifier = nostr_event.thread_id().hex()
improvedContent.categoryIdentifier = "COMMUNICATION"
let interaction = INInteraction(intent: message_intent, response: nil)
interaction.direction = .incoming
do {
try await interaction.donate()
let updated = try improvedContent.updating(from: message_intent)
contentHandler(updated)
} catch {
Log.error("failed to donate interaction: %s", for: .push_notifications, error.localizedDescription)
contentHandler(improvedContent)
}
contentHandler(improvedContent)
}
}
@@ -162,162 +95,3 @@ class NotificationService: UNNotificationServiceExtension {
}
}
struct ProfileBuf {
let picture: URL
let name: String?
let display_name: String?
let nip05: String?
}
func message_intent_from_note(ndb: Ndb, sender_profile: ProfileBuf, content: String, note: NdbNote, our_pubkey: Pubkey) async -> INSendMessageIntent {
let sender_pk = note.pubkey
let sender = await profile_to_inperson(name: sender_profile.name,
display_name: sender_profile.display_name,
picture: sender_profile.picture.absoluteString,
nip05: sender_profile.nip05,
pubkey: sender_pk,
our_pubkey: our_pubkey)
let conversationIdentifier = note.thread_id().hex()
var recipients: [INPerson] = []
var pks: [Pubkey] = []
let meta = INSendMessageIntentDonationMetadata()
// gather recipients
if let recipient_note_id = note.direct_replies() {
let replying_to = ndb.lookup_note(recipient_note_id)
if let replying_to_pk = replying_to?.unsafeUnownedValue?.pubkey {
meta.isReplyToCurrentUser = replying_to_pk == our_pubkey
if replying_to_pk != sender_pk {
// we push the actual person being replied to first
pks.append(replying_to_pk)
}
}
}
let pubkeys = Array(note.referenced_pubkeys)
meta.recipientCount = pubkeys.count
if pubkeys.contains(sender_pk) {
meta.recipientCount -= 1
}
for pk in pubkeys.prefix(3) {
if pk == sender_pk || pks.contains(pk) {
continue
}
if !meta.isReplyToCurrentUser && pk == our_pubkey {
meta.mentionsCurrentUser = true
}
pks.append(pk)
}
for pk in pks {
let recipient = await pubkey_to_inperson(ndb: ndb, pubkey: pk, our_pubkey: our_pubkey)
recipients.append(recipient)
}
// we enable default formatting this way
var groupName = INSpeakableString(spokenPhrase: "")
// otherwise we just say its a DM
if note.known_kind == .dm {
groupName = INSpeakableString(spokenPhrase: "DM")
}
let intent = INSendMessageIntent(recipients: recipients,
outgoingMessageType: .outgoingMessageText,
content: content,
speakableGroupName: groupName,
conversationIdentifier: conversationIdentifier,
serviceName: "kind\(note.kind)",
sender: sender,
attachments: nil)
intent.donationMetadata = meta
// this is needed for recipients > 0
if let img = sender.image {
intent.setImage(img, forParameterNamed: \.speakableGroupName)
}
return intent
}
func pubkey_to_inperson(ndb: Ndb, pubkey: Pubkey, our_pubkey: Pubkey) async -> INPerson {
let profile_txn = ndb.lookup_profile(pubkey)
let profile = profile_txn?.unsafeUnownedValue?.profile
let name = profile?.name
let display_name = profile?.display_name
let nip05 = profile?.nip05
let picture = profile?.picture
return await profile_to_inperson(name: name,
display_name: display_name,
picture: picture,
nip05: nip05,
pubkey: pubkey,
our_pubkey: our_pubkey)
}
func fetch_pfp(picture: URL) async throws -> RetrieveImageResult {
try await withCheckedThrowingContinuation { continuation in
KingfisherManager.shared.retrieveImage(with: Kingfisher.ImageResource(downloadURL: picture)) { result in
switch result {
case .success(let img):
continuation.resume(returning: img)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
func profile_to_inperson(name: String?, display_name: String?, picture: String?, nip05: String?, pubkey: Pubkey, our_pubkey: Pubkey) async -> INPerson {
let npub = pubkey.npub
let handle = INPersonHandle(value: npub, type: .unknown)
var aliases: [INPersonHandle] = []
if let nip05 {
aliases.append(INPersonHandle(value: nip05, type: .emailAddress))
}
let nostrName = DisplayName(name: name, display_name: display_name, pubkey: pubkey)
let nameComponents = nostrName.nameComponents()
let displayName = nostrName.displayName
let contactIdentifier = npub
let customIdentifier = npub
let suggestionType = INPersonSuggestionType.socialProfile
var image: INImage? = nil
if let picture,
let url = URL(string: picture),
let img = try? await fetch_pfp(picture: url),
let imgdata = img.data()
{
image = INImage(imageData: imgdata)
} else {
Log.error("Failed to fetch pfp (%s) for %s", for: .push_notifications, picture ?? "nil", displayName)
}
let person = INPerson(personHandle: handle,
nameComponents: nameComponents,
displayName: displayName,
image: image,
contactIdentifier: contactIdentifier,
customIdentifier: customIdentifier,
isMe: pubkey == our_pubkey,
suggestionType: suggestionType
)
return person
}
func robohash(_ pk: Pubkey) -> String {
return "https://robohash.org/" + pk.hex()
}
+3 -32
View File
@@ -1,32 +1,3 @@
// swift-tools-version: 6.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "damus",
platforms: [
.iOS(.v16),
.macOS(.v12)
],
products: [
.library(
name: "damus",
targets: ["damus"]),
],
dependencies: [
.package(url: "https://github.com/jb55/secp256k1.swift.git", branch: "main")
],
targets: [
.target(
name: "damus",
dependencies: [
.product(name: "secp256k1", package: "secp256k1.swift")
],
path: "damus"),
.testTarget(
name: "damusTests",
dependencies: ["damus"],
path: "damusTests"),
]
)
dependencies: [
.Package(url: "https://github.com/jb55/secp256k1.swift.git", branch: "main")
]
+1 -1
View File
@@ -8,7 +8,7 @@ A twitter-like [nostr][nostr] client for iPhone, iPad and MacOS.
[nostr]: https://github.com/fiatjaf/nostr
## How is Damus better than X/Twitter?
## How is Damus better than twitter?
There are no toxic algorithms.\
You can send or receive zaps (satoshis) without asking for permission.\
[There is no central database](https://fiatjaf.com/nostr.html). Therefore, Damus is censorship resistant.\
-1
View File
@@ -1 +0,0 @@
Fix q tags
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,5 @@
{
"originHash" : "06318d35ee2e6bd681b95591e67da33a9461b48a3c652e58bd9d1a6f0d82bdac",
"originHash" : "0d806129a33991730dd1aa3d38c47a745f9e9e6ff44999f4a7f28b695f024832",
"pins" : [
{
"identity" : "codescanner",
@@ -9,21 +9,13 @@
"revision" : "9fa582f4b36c69c2a55bff5fb3377eb170ae273c"
}
},
{
"identity" : "cryptoswift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/krzyzanowskim/CryptoSwift.git",
"state" : {
"revision" : "e74bbbfbef939224b242ae7c342a90e60b88b5ce"
}
},
{
"identity" : "emojikit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/tyiu/EmojiKit",
"state" : {
"revision" : "47a4b1402de26be0299dcb4d667c1faaf21a7874",
"version" : "0.2.0"
"revision" : "05805f72d63a6d6a2d7dc7fe14abd37c1317b11a",
"version" : "0.1.2"
}
},
{
@@ -31,8 +23,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/tyiu/EmojiPicker.git",
"state" : {
"revision" : "3f48903721eae223238ff0af17c22d6373d33813",
"version" : "0.2.0"
"revision" : "0c28b4a1a6b8840cf2580bda59517f6d0a733dc8",
"version" : "0.1.1"
}
},
{
+2 -2
View File
@@ -232,7 +232,7 @@ func send_zap(damus_state: DamusState, target: ZapTarget, lnurl: String, is_cust
flusher = .once({ pe in
// send donation zap when the pending zap is flushed, this allows user to cancel and not send a donation
Task { @MainActor in
await WalletConnect.send_donation_zap(pool: damus_state.pool, postbox: damus_state.postbox, nwc: nwc_state.url, percent: damus_state.settings.donation_percent, base_msats: amount_msat)
await send_donation_zap(pool: damus_state.pool, postbox: damus_state.postbox, nwc: nwc_state.url, percent: damus_state.settings.donation_percent, base_msats: amount_msat)
}
})
}
@@ -240,7 +240,7 @@ func send_zap(damus_state: DamusState, target: ZapTarget, lnurl: String, is_cust
// we don't have a delay on one-tap nozaps (since this will be from customize zap view)
let delay = damus_state.settings.nozaps ? nil : 5.0
let nwc_req = WalletConnect.pay(url: nwc_state.url, pool: damus_state.pool, post: damus_state.postbox, invoice: inv, delay: delay, on_flush: flusher)
let nwc_req = nwc_pay(url: nwc_state.url, pool: damus_state.pool, post: damus_state.postbox, invoice: inv, delay: delay, on_flush: flusher)
guard let nwc_req, case .nwc(let pzap_state) = pending_zap_state else {
print("nwc: failed to send nwc request for zapreq \(reqid.reqid)")
+5 -51
View File
@@ -10,68 +10,22 @@ import SwiftUI
struct Reposted: View {
let damus: DamusState
let pubkey: Pubkey
let target: NostrEvent
@State var reposts: Int
init(damus: DamusState, pubkey: Pubkey, target: NostrEvent) {
self.damus = damus
self.pubkey = pubkey
self.target = target
self.reposts = damus.boosts.counts[target.id] ?? 1
}
var body: some View {
HStack(alignment: .center) {
Image("repost")
.foregroundColor(Color.gray)
// Show profile picture of the reposter only if the reposter is not the author of the reposted note.
if pubkey != target.pubkey {
ProfilePicView(pubkey: pubkey, size: eventview_pfp_size(.small), highlight: .none, profiles: damus.profiles, disable_animation: damus.settings.disable_animation)
.onTapGesture {
show_profile_action_sheet_if_enabled(damus_state: damus, pubkey: pubkey)
}
.onLongPressGesture(minimumDuration: 0.1) {
UIImpactFeedbackGenerator(style: .medium).impactOccurred()
damus.nav.push(route: Route.ProfileByKey(pubkey: pubkey))
}
}
NavigationLink(value: Route.Reposts(reposts: .reposts(state: damus, target: target.id))) {
Text(people_reposted_text(profiles: damus.profiles, pubkey: pubkey, reposts: reposts))
.font(.subheadline)
.foregroundColor(.gray)
}
ProfileName(pubkey: pubkey, damus: damus, show_nip5_domain: false)
.foregroundColor(Color.gray)
Text("Reposted", comment: "Text indicating that the note was reposted (i.e. re-shared).")
.foregroundColor(Color.gray)
}
.onReceive(handle_notify(.update_stats), perform: { note_id in
guard note_id == target.id else { return }
let repost_count = damus.boosts.counts[target.id]
if let repost_count, reposts != repost_count {
reposts = repost_count
}
})
}
}
func people_reposted_text(profiles: Profiles, pubkey: Pubkey, reposts: Int, locale: Locale = Locale.current) -> String {
guard reposts > 0 else {
return ""
}
let bundle = bundleForLocale(locale: locale)
let other_reposts = reposts - 1
let display_name = event_author_name(profiles: profiles, pubkey: pubkey)
if other_reposts == 0 {
return String(format: NSLocalizedString("%@ reposted", bundle: bundle, comment: "Text indicating that the note was reposted (i.e. re-shared)."), locale: locale, display_name)
} else {
return String(format: localizedStringFormat(key: "people_reposted_count", locale: locale), locale: locale, other_reposts, display_name)
}
}
struct Reposted_Previews: PreviewProvider {
static var previews: some View {
let test_state = test_damus_state
Reposted(damus: test_state, pubkey: test_state.pubkey, target: test_note)
Reposted(damus: test_state, pubkey: test_state.pubkey)
}
}
+1 -1
View File
@@ -63,7 +63,7 @@ struct SelectableText: View {
})) {
if let event, case .show_highlight_post_view(let highlighted_text) = self.selectedTextActionState {
PostView(
action: .highlighting(.init(selected_text: highlighted_text, source: .event(event.id))),
action: .highlighting(.init(selected_text: highlighted_text, source: .event(event))),
damus_state: damus_state
)
.presentationDragIndicator(.visible)
+8 -163
View File
@@ -12,14 +12,6 @@ struct SupporterBadge: View {
let purple_account: DamusPurple.Account?
let style: Style
let text_color: Color
var badge_variant: BadgeVariant {
if purple_account?.attributes.contains(.memberForMoreThanOneYear) == true {
return .oneYearSpecial
}
else {
return .normal
}
}
init(percent: Int?, purple_account: DamusPurple.Account? = nil, style: Style, text_color: Color = .secondary) {
self.percent = percent
@@ -34,18 +26,13 @@ struct SupporterBadge: View {
HStack {
if let purple_account, purple_account.active == true {
HStack(spacing: 1) {
switch self.badge_variant {
case .normal:
StarShape()
.frame(width:size, height:size)
.foregroundStyle(GoldGradient)
case .oneYearSpecial:
DoubleStar(size: size)
}
if self.style == .full,
let ordinal = self.purple_account?.ordinal() {
Text(ordinal)
Image("star.fill")
.resizable()
.frame(width:size, height:size)
.foregroundStyle(GoldGradient)
if self.style == .full {
let date = format_date(date: purple_account.created_at, time_style: .none)
Text(date)
.foregroundStyle(text_color)
.font(.caption)
}
@@ -69,102 +56,8 @@ struct SupporterBadge: View {
case full // Shows the entire badge with a purple subscriber number if present
case compact // Does not show purple subscriber number. Only shows the star (if applicable)
}
enum BadgeVariant {
/// A normal badge that people are used to
case normal
/// A special badge for users who have been members for more than a year
case oneYearSpecial
}
}
struct StarShape: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius: CGFloat = min(rect.width, rect.height) / 2
let points = 5
let adjustment: CGFloat = .pi / 2
for i in 0..<points * 2 {
let angle = (CGFloat(i) * .pi / CGFloat(points)) - adjustment
let pointRadius = i % 2 == 0 ? radius : radius * 0.4
let point = CGPoint(x: center.x + pointRadius * cos(angle), y: center.y + pointRadius * sin(angle))
if i == 0 {
path.move(to: point)
} else {
path.addLine(to: point)
}
}
path.closeSubpath()
return path
}
}
struct DoubleStar: View {
let size: CGFloat
var starOffset: CGFloat = 5
var body: some View {
if #available(iOS 17.0, *) {
DoubleStarShape(starOffset: starOffset)
.frame(width: size, height: size)
.foregroundStyle(GoldGradient)
.padding(.trailing, starOffset)
} else {
Fallback(size: size, starOffset: starOffset)
}
}
@available(iOS 17.0, *)
struct DoubleStarShape: Shape {
var strokeSize: CGFloat = 3
var starOffset: CGFloat
func path(in rect: CGRect) -> Path {
let normalSizedStarPath = StarShape().path(in: rect)
let largerStarPath = StarShape().path(in: rect.insetBy(dx: -strokeSize, dy: -strokeSize))
let finalPath = normalSizedStarPath
.subtracting(
largerStarPath.offsetBy(dx: starOffset, dy: 0)
)
.union(
normalSizedStarPath.offsetBy(dx: starOffset, dy: 0)
)
return finalPath
}
}
/// A fallback view for those who cannot run iOS 17
struct Fallback: View {
var size: CGFloat
var starOffset: CGFloat
var body: some View {
HStack {
StarShape()
.frame(width: size, height: size)
.foregroundStyle(GoldGradient)
StarShape()
.fill(GoldGradient)
.overlay(
StarShape()
.stroke(Color.damusAdaptableWhite, lineWidth: 1)
)
.frame(width: size + 1, height: size + 1)
.padding(.leading, -size - starOffset)
}
.padding(.trailing, -3)
}
}
}
func support_level_color(_ percent: Int) -> Color {
if percent == 0 {
return .gray
@@ -193,7 +86,7 @@ struct SupporterBadge_Previews: PreviewProvider {
HStack(alignment: .center) {
SupporterBadge(
percent: nil,
purple_account: DamusPurple.Account(pubkey: test_pubkey, created_at: .now, expiry: .now.addingTimeInterval(10000), subscriber_number: subscriber_number, active: true, attributes: []),
purple_account: DamusPurple.Account(pubkey: test_pubkey, created_at: .now, expiry: .now.addingTimeInterval(10000), subscriber_number: subscriber_number, active: true),
style: .full
)
.frame(width: 100)
@@ -225,52 +118,4 @@ struct SupporterBadge_Previews: PreviewProvider {
}
}
#Preview("1 yr badge") {
VStack {
HStack(alignment: .center) {
SupporterBadge(
percent: nil,
purple_account: DamusPurple.Account(pubkey: test_pubkey, created_at: .now, expiry: .now.addingTimeInterval(10000), subscriber_number: 3, active: true, attributes: []),
style: .full
)
.frame(width: 100)
}
HStack(alignment: .center) {
SupporterBadge(
percent: nil,
purple_account: DamusPurple.Account(pubkey: test_pubkey, created_at: .now, expiry: .now.addingTimeInterval(10000), subscriber_number: 3, active: true, attributes: [.memberForMoreThanOneYear]),
style: .full
)
.frame(width: 100)
}
Text(verbatim: "Double star (just shape itself, with alt background color, to show it adapts to background well)")
.multilineTextAlignment(.center)
if #available(iOS 17.0, *) {
HStack(alignment: .center) {
DoubleStar.DoubleStarShape(starOffset: 5)
.frame(width: 17, height: 17)
.padding(.trailing, -8)
}
.background(Color.blue)
}
Text(verbatim: "Double star (fallback for iOS 16 and below)")
HStack(alignment: .center) {
DoubleStar.Fallback(size: 17, starOffset: 5)
}
Text(verbatim: "Double star (fallback for iOS 16 and below, with alt color limitation shown)")
.multilineTextAlignment(.center)
HStack(alignment: .center) {
DoubleStar.Fallback(size: 17, starOffset: 5)
}
.background(Color.blue)
}
}
+123 -150
View File
@@ -31,8 +31,7 @@ enum Sheets: Identifiable {
case onboardingSuggestions
case purple(DamusPurpleURL)
case purple_onboarding
case error(ErrorView.UserPresentableError)
static func zap(target: ZapTarget, lnurl: String) -> Sheets {
return .zap(ZapSheet(target: target, lnurl: lnurl))
}
@@ -54,7 +53,6 @@ enum Sheets: Identifiable {
case .onboardingSuggestions: return "onboarding-suggestions"
case .purple(let purple_url): return "purple" + purple_url.url_string()
case .purple_onboarding: return "purple_onboarding"
case .error(_): return "error"
}
}
}
@@ -222,6 +220,12 @@ struct ContentView: View {
navigationCoordinator.push(route: Route.Script(script: model))
}
func open_profile(pubkey: Pubkey) {
let profile_model = ProfileModel(pubkey: pubkey, damus: damus_state!)
let followers = FollowersModel(damus_state: damus_state!, target: pubkey)
navigationCoordinator.push(route: Route.Profile(profile: profile_model, followers: followers))
}
func open_search(filt: NostrFilter) {
let search = SearchModel(state: damus_state!, search: filt)
navigationCoordinator.push(route: Route.Search(search: search))
@@ -306,9 +310,6 @@ struct ContentView: View {
hasSeenOnboardingSuggestions = true
}
self.appDelegate?.state = damus_state
Task { // We probably don't need this to be a detached task. According to https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Defining-and-Calling-Asynchronous-Functions, awaits are only suspension points that do not block the thread.
await self.listenAndHandleLocalNotifications()
}
}
.sheet(item: $active_sheet) { item in
switch item {
@@ -338,14 +339,36 @@ struct ContentView: View {
DamusPurpleURLSheetView(damus_state: damus_state!, purple_url: purple_url)
case .purple_onboarding:
DamusPurpleNewUserOnboardingView(damus_state: damus_state)
case .error(let error):
ErrorView(damus_state: damus_state!, error: error)
}
}
.onOpenURL { url in
Task {
let open_action = await DamusURLHandler.handle_opening_url_and_compute_view_action(damus_state: self.damus_state, url: url)
self.execute_open_action(open_action)
on_open_url(state: damus_state!, url: url) { res in
guard let res else {
return
}
switch res {
case .filter(let filt): self.open_search(filt: filt)
case .profile(let pk): self.open_profile(pubkey: pk)
case .event(let ev): self.open_event(ev: ev)
case .wallet_connect(let nwc): self.open_wallet(nwc: nwc)
case .script(let data): self.open_script(data)
case .purple(let purple_url):
if case let .welcome(checkout_id) = purple_url.variant {
// If this is a welcome link, do the following before showing the onboarding screen:
// 1. Check if this is legitimate and good to go.
// 2. Mark as complete if this is good to go.
Task {
let is_good_to_go = try? await damus_state.purple.check_and_mark_ln_checkout_is_good_to_go(checkout_id: checkout_id)
if is_good_to_go == true {
self.active_sheet = .purple(purple_url)
}
}
}
else {
self.active_sheet = .purple(purple_url)
}
}
}
}
.onReceive(handle_notify(.compose)) { action in
@@ -367,10 +390,6 @@ struct ContentView: View {
self.confirm_mute = true
}
.onReceive(handle_notify(.attached_wallet)) { nwc in
// Ensure to add NWC relay to the pool and connect it.
try? damus_state.pool.add_relay(.nwc(url: nwc.relay))
damus_state.pool.connect(to: [nwc.relay])
// update the lightning address on our profile when we attach a
// wallet with an associated
guard let ds = self.damus_state,
@@ -512,6 +531,27 @@ struct ContentView: View {
@unknown default:
break
}
}
.onReceive(handle_notify(.local_notification)) { local in
guard let damus_state else { return }
switch local.mention {
case .pubkey(let pubkey):
open_profile(pubkey: pubkey)
case .note(let noteId):
openEvent(noteId: noteId, notificationType: local.type)
case .nevent(let nevent):
openEvent(noteId: nevent.noteid, notificationType: local.type)
case .nprofile(let nprofile):
open_profile(pubkey: nprofile.author)
case .nrelay(_):
break
case .naddr(let naddr):
break
}
}
.onReceive(handle_notify(.onlyzaps_mode)) { hide in
home.filter_events()
@@ -568,7 +608,7 @@ struct ContentView: View {
}, message: {
Text("No mute list found, create a new one? This will overwrite any previous mute lists.", comment: "Alert message prompt that asks if the user wants to create a new mute list, overwriting previous mute lists.")
})
.alert(NSLocalizedString("Mute/Block User", comment: "Title of alert for muting/blocking a user."), isPresented: $confirm_mute, actions: {
.alert(NSLocalizedString("Mute User", comment: "Title of alert for muting a user."), isPresented: $confirm_mute, actions: {
Button(NSLocalizedString("Cancel", comment: "Alert button to cancel out of alert for muting a user."), role: .cancel) {
confirm_mute = false
}
@@ -621,28 +661,6 @@ struct ContentView: View {
self.selected_timeline = timeline
}
/// Listens to requests to open a push/local user notification
///
/// This function never returns, it just keeps streaming
func listenAndHandleLocalNotifications() async {
for await notification in await QueueableNotify<LossyLocalNotification>.shared.stream {
self.handleNotification(notification: notification)
}
}
func handleNotification(notification: LossyLocalNotification) {
Log.info("ContentView is handling a notification", for: .push_notifications)
guard let damus_state else {
// This should never happen because `listenAndHandleLocalNotifications` is called after damus state is initialized in `onAppear`
assertionFailure("DamusState not loaded when ContentView (new handler) was handling a notification")
Log.error("DamusState not loaded when ContentView (new handler) was handling a notification", for: .push_notifications)
return
}
let local = notification
let openAction = local.toViewOpenAction()
self.execute_open_action(openAction)
}
func connect() {
// nostrdb
var mndb = Ndb()
@@ -748,38 +766,22 @@ struct ContentView: View {
damus_state.postbox.send(ev)
}
}
/// An open action within the app
/// This is used to model, store, and communicate a desired view action to be taken as a result of opening an object,
/// for example a URL
///
/// ## Implementation notes
///
/// - The reason this was created was to separate URL parsing logic, the underlying actions that mutate the state of the app, and the action to be taken on the view layer as a result. This makes it easier to test, to read the URL handling code, and to add new functionality in between the two (e.g. a confirmation screen before proceeding with a given open action)
enum ViewOpenAction {
/// Open a page route
case route(Route)
/// Open a sheet
case sheet(Sheets)
/// Do nothing.
///
/// ## Implementation notes
/// - This is used here instead of Optional values to make semantics explicit and force better programming intent, instead of accidentally doing nothing because of Swift's syntax sugar.
case no_action
}
/// Executes an action to open something in the app view
///
/// - Parameter open_action: The action to perform
func execute_open_action(_ open_action: ViewOpenAction) {
switch open_action {
case .route(let route):
navigationCoordinator.push(route: route)
case .sheet(let sheet):
self.active_sheet = sheet
case .no_action:
private func openEvent(noteId: NoteId, notificationType: LocalNotificationType) {
guard let target = damus_state.events.lookup(noteId) else {
return
}
switch notificationType {
case .dm:
selected_timeline = .dms
damus_state.dms.set_active_dm(target.pubkey)
navigationCoordinator.push(route: Route.DMChat(dms: damus_state.dms.active_model))
case .like, .zap, .mention, .repost, .reply, .tagged:
open_event(ev: target)
case .profile_zap:
break
}
}
}
@@ -932,38 +934,10 @@ enum FoundEvent {
case event(NostrEvent)
}
/// Finds an event from NostrDB if it exists, or from the network
///
/// This is the callback version. There is also an asyc/await version of this function.
///
/// - Parameters:
/// - state: Damus state
/// - query_: The query, including the event being looked for, and the relays to use when looking
/// - callback: The function to call with results
func find_event(state: DamusState, query query_: FindEvent, callback: @escaping (FoundEvent?) -> ()) {
return find_event_with_subid(state: state, query: query_, subid: UUID().description, callback: callback)
}
/// Finds an event from NostrDB if it exists, or from the network
///
/// This is a the async/await version of `find_event`. Use this when using callbacks is impossible or cumbersome.
///
/// - Parameters:
/// - state: Damus state
/// - query_: The query, including the event being looked for, and the relays to use when looking
/// - callback: The function to call with results
func find_event(state: DamusState, query query_: FindEvent) async -> FoundEvent? {
await withCheckedContinuation { continuation in
find_event(state: state, query: query_) { event in
var already_resumed = false
if !already_resumed { // Ensure we do not resume twice, as it causes a crash
continuation.resume(returning: event)
already_resumed = true
}
}
}
}
func find_event_with_subid(state: DamusState, query query_: FindEvent, subid: String, callback: @escaping (FoundEvent?) -> ()) {
var filter: NostrFilter? = nil
@@ -1034,15 +1008,6 @@ func find_event_with_subid(state: DamusState, query query_: FindEvent, subid: St
}
}
/// Finds a replaceable event based on an `naddr` address.
///
/// This is the callback version of the function. There is another function that makes use of async/await
///
/// - Parameters:
/// - damus_state: The Damus state
/// - naddr: the `naddr` address
/// - callback: A function to handle the found event
func naddrLookup(damus_state: DamusState, naddr: NAddr, callback: @escaping (NostrEvent?) -> ()) {
var nostrKinds: [NostrKind]? = NostrKind(rawValue: naddr.kind).map { [$0] }
@@ -1071,26 +1036,6 @@ func naddrLookup(damus_state: DamusState, naddr: NAddr, callback: @escaping (Nos
}
}
/// Finds a replaceable event based on an `naddr` address.
///
/// This is the async/await version of the function. Another version of this function which makes use of callback functions also exists .
///
/// - Parameters:
/// - damus_state: The Damus state
/// - naddr: the `naddr` address
/// - callback: A function to handle the found event
func naddrLookup(damus_state: DamusState, naddr: NAddr) async -> NostrEvent? {
await withCheckedContinuation { continuation in
var already_resumed = false
naddrLookup(damus_state: damus_state, naddr: naddr) { event in
if !already_resumed { // Ensure we do not resume twice, as it causes a crash
continuation.resume(returning: event)
already_resumed = true
}
}
}
}
func timeline_name(_ timeline: Timeline?) -> String {
guard let timeline else {
return ""
@@ -1201,32 +1146,60 @@ func handle_post_notification(keypair: FullKeypair, postbox: PostBox, events: Ev
}
}
extension LossyLocalNotification {
/// Computes a view open action from a mention reference.
/// Use this when opening a user-presentable interface to a specific mention reference.
func toViewOpenAction() -> ContentView.ViewOpenAction {
switch self.mention {
case .pubkey(let pubkey):
return .route(.ProfileByKey(pubkey: pubkey))
case .note(let noteId):
return .route(.LoadableNostrEvent(note_reference: .note_id(noteId)))
case .nevent(let nEvent):
// TODO: Improve this by implementing a route that handles nevents with their relay hints.
return .route(.LoadableNostrEvent(note_reference: .note_id(nEvent.noteid)))
case .nprofile(let nProfile):
// TODO: Improve this by implementing a profile route that handles nprofiles with their relay hints.
return .route(.ProfileByKey(pubkey: nProfile.author))
case .nrelay(let string):
// We do not need to implement `nrelay` support, it has been deprecated.
// See https://github.com/nostr-protocol/nips/blob/6e7a618e7f873bb91e743caacc3b09edab7796a0/BREAKING.md?plain=1#L21
return .sheet(.error(ErrorView.UserPresentableError(
user_visible_description: NSLocalizedString("You opened an invalid link. The link you tried to open refers to \"nrelay\", which has been deprecated and is not supported.", comment: "User-visible error description for a user who tries to open a deprecated \"nrelay\" link."),
tip: NSLocalizedString("Please contact the person who provided the link, and ask for another link.", comment: "User-visible tip on what to do if a link contains a deprecated \"nrelay\" reference."),
technical_info: "`MentionRef.toViewOpenAction` detected deprecated `nrelay` contents"
)))
case .naddr(let nAddr):
return .route(.LoadableNostrEvent(note_reference: .naddr(nAddr)))
enum OpenResult {
case profile(Pubkey)
case filter(NostrFilter)
case event(NostrEvent)
case wallet_connect(WalletConnectURL)
case script([UInt8])
case purple(DamusPurpleURL)
}
func on_open_url(state: DamusState, url: URL, result: @escaping (OpenResult?) -> Void) {
if let purple_url = DamusPurpleURL(url: url) {
result(.purple(purple_url))
return
}
if let nwc = WalletConnectURL(str: url.absoluteString) {
result(.wallet_connect(nwc))
return
}
guard let link = decode_nostr_uri(url.absoluteString) else {
result(nil)
return
}
switch link {
case .ref(let ref):
switch ref {
case .pubkey(let pk):
result(.profile(pk))
case .event(let noteid):
find_event(state: state, query: .event(evid: noteid)) { res in
guard let res, case .event(let ev) = res else { return }
result(.event(ev))
}
case .hashtag(let ht):
result(.filter(.filter_hashtag([ht.hashtag])))
case .param, .quote, .reference:
// doesn't really make sense here
break
case .naddr(let naddr):
naddrLookup(damus_state: state, naddr: naddr) { res in
guard let res = res else { return }
result(.event(res))
}
}
case .filter(let filt):
result(.filter(filt))
break
// TODO: handle filter searches?
case .script(let script):
result(.script(script))
break
}
}
+1 -5
View File
@@ -2,10 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSUserActivityTypes</key>
<array>
<string>INSendMessageIntent</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
@@ -77,6 +73,6 @@
<key>NSAppleMusicUsageDescription</key>
<string>Damus needs access to your media library for playback statuses</string>
<key>NSMicrophoneUsageDescription</key>
<string>Damus needs access to your microphone to allow you to create video recordings that you can choose to post publicly on the network</string>
<string>Damus needs access to your microphone for creating video recording posts</string>
</dict>
</plist>
+1 -4
View File
@@ -10,9 +10,8 @@ import Foundation
/// Simple filter to determine whether to show posts or all posts and replies.
enum FilterState : Int {
case posts = 0
case posts_and_replies = 1
case conversations = 2
case posts = 0
func filter(ev: NostrEvent) -> Bool {
switch self {
@@ -20,8 +19,6 @@ enum FilterState : Int {
return ev.known_kind == .boost || ev.known_kind == .highlight || !ev.is_reply()
case .posts_and_replies:
return true
case .conversations:
return true
}
}
}
-3
View File
@@ -175,9 +175,6 @@ class DamusState: HeadlessDamusState {
func close() {
print("txn: damus close")
Task {
try await self.push_notification_client.revoke_token()
}
wallet.disconnect()
pool.close()
ndb.close()
+4 -241
View File
@@ -6,45 +6,14 @@
//
import Foundation
import SwiftUICore
import UIKit
/// Represents artifacts in a post draft, which is rendered by `PostView`
///
/// ## Implementation notes
///
/// - This is NOT `Codable` because we store these persistently as NIP-37 drafts in NostrDB, instead of directly encoding the object.
/// - `NSMutableAttributedString` is the bottleneck for making this `Codable`, and replacing that with another type requires a very large refactor.
/// - Encoding/decoding logic is lossy, and is not fully round-trippable. This class does a best effort attempt at encoding and recovering as much information as possible, but the information is dispersed into many different places, types, and functions around the code, making round-trip guarantees very difficult without severely refactoring `PostView`, `TextViewWrapper`, and other associated classes, unfortunately. These are the known limitations at the moment:
/// - Image metadata is lost on decoding
/// - The `filtered_pubkeys` filter effectively gets applied upon encoding, causing them to change upon decoding
///
class DraftArtifacts: Equatable {
/// The text content of the note draft
///
/// ## Implementation notes
///
/// - This serves as the backing model for `PostView` and `TextViewWrapper`. It might be cleaner to use a specialized data model for this in the future and render to attributed string in real time, but that will require a big refactor. See https://github.com/damus-io/damus/issues/1862#issuecomment-2585756932
var content: NSMutableAttributedString
/// A list of media items that have been attached to the note draft.
var media: [UploadedMedia]
/// The references for this note, which will be translated into tags once the event is published.
var references: [RefId]
/// Pubkeys that should be filtered out from the references
///
/// For example, when replying to an event, the user can select which pubkey mentions they want to keep, and which ones to remove.
var filtered_pubkeys: Set<Pubkey> = []
/// A unique ID for this draft that allows us to address these if we need to.
///
/// This will be the unique identifier in the NIP-37 note
let id: String
init(content: NSMutableAttributedString = NSMutableAttributedString(string: ""), media: [UploadedMedia] = [], references: [RefId], id: String) {
init(content: NSMutableAttributedString = NSMutableAttributedString(string: ""), media: [UploadedMedia] = []) {
self.content = content
self.media = media
self.references = references
self.id = id
}
static func == (lhs: DraftArtifacts, rhs: DraftArtifacts) -> Bool {
@@ -53,217 +22,11 @@ class DraftArtifacts: Equatable {
lhs.content.string == rhs.content.string // Comparing the text content is not perfect but acceptable in this case because attributes for our post editor are determined purely from text content
)
}
// MARK: Encoding and decoding functions to and from NIP-37 nostr events
/// Converts the draft artifacts into a NIP-37 draft event that can be saved into NostrDB or any Nostr relay
///
/// - Parameters:
/// - action: The post action for this draft, which provides necessary context for the draft (e.g. Is it meant to highlight something? Reply to something?)
/// - damus_state: The damus state, needed for encrypting, fetching Nostr data depedencies, and forming the NIP-37 draft
/// - references: references in the post?
/// - Returns: The NIP-37 draft packaged in a way that can be easily wrapped/unwrapped.
func to_nip37_draft(action: PostAction, damus_state: DamusState) throws -> NIP37Draft? {
guard let keypair = damus_state.keypair.to_full() else { return nil }
let post = build_post(state: damus_state, action: action, draft: self)
guard let note = post.to_event(keypair: keypair) else { return nil }
return try NIP37Draft(unwrapped_note: note, draft_id: self.id, keypair: keypair)
}
/// Instantiates a draft object from a NIP-37 draft
/// - Parameters:
/// - nip37_draft: The NIP-37 draft object
/// - damus_state: Damus state of the user who wants to load this draft object. Needed for pulling profiles from Ndb, and decrypting contents.
/// - Returns: A draft artifacts object, or `nil` if such cannot be loaded.
static func from(nip37_draft: NIP37Draft, damus_state: DamusState) -> DraftArtifacts? {
return Self.from(
event: nip37_draft.unwrapped_note,
draft_id: nip37_draft.id ?? UUID().uuidString, // Generate random UUID as the draft ID if none is specified. It is always better to have an ID that we can use for addressing later.
damus_state: damus_state
)
}
/// Load a draft artifacts object from a plain, unwrapped NostrEvent
///
/// This function will parse the contents of a Nostr Event and turn it into an editable draft that we can use.
///
/// - Parameters:
/// - event: The Nostr event to use as a template
/// - draft_id: The unique ID of this draft, used for keeping draft identities stable. UUIDs are recommended but not required.
/// - damus_state: The user's Damus state, used for fetching profiles in NostrDB
/// - Returns: The draft that can be loaded into `PostView`.
static func from(event: NostrEvent, draft_id: String, damus_state: DamusState) -> DraftArtifacts {
let parsed_blocks = parse_note_content(content: .init(note: event, keypair: damus_state.keypair))
return Self.from(parsed_blocks: parsed_blocks, references: Array(event.references), draft_id: draft_id, damus_state: damus_state)
}
/// Load a draft artifacts object from parsed Nostr event blocks
///
/// - Parameters:
/// - parsed_blocks: The blocks parsed from a Nostr event
/// - references: The references in the Nostr event
/// - draft_id: The unique ID of the draft as per NIP-37
/// - damus_state: Damus state, used for fetching profile info in NostrDB
/// - Returns: The draft that can be loaded into `PostView`.
static func from(parsed_blocks: Blocks, references: [RefId], draft_id: String, damus_state: DamusState) -> DraftArtifacts {
let rich_text_content: NSMutableAttributedString = .init(string: "")
var media: [UploadedMedia] = []
for block in parsed_blocks.blocks {
switch block {
case .mention(let mention):
if case .pubkey(let pubkey) = mention.ref {
// A profile reference, format things properly.
let profile = damus_state.ndb.lookup_profile(pubkey)?.unsafeUnownedValue?.profile
let profile_name = DisplayName(profile: profile, pubkey: pubkey).username
guard let url_address = URL(string: block.asString) else {
rich_text_content.append(.init(string: block.asString))
continue
}
let attributed_string = NSMutableAttributedString(
string: "@\(profile_name)",
attributes: [
.link: url_address,
.foregroundColor: UIColor(Color.accentColor)
]
)
rich_text_content.append(attributed_string)
}
else if case .note(_) = mention.ref {
// These note references occur when we quote a note, and since that is tracked via `PostAction` in `PostView`, ignore it here to avoid attaching the same event twice in a note
continue
}
else {
// Other references
rich_text_content.append(.init(string: block.asString))
}
case .url(let url):
if isSupportedImage(url: url) {
// Image, add that to our media attachments
// TODO: Add metadata decoding support
media.append(UploadedMedia(localURL: url, uploadedURL: url, metadata: .none))
continue
}
else {
// Normal URL, plain text
rich_text_content.append(.init(string: block.asString))
}
case .invoice(_), .relay(_), .hashtag(_), .text(_):
// Everything else is currently plain text.
rich_text_content.append(.init(string: block.asString))
}
}
return DraftArtifacts(content: rich_text_content, media: media, references: references, id: draft_id)
}
}
/// Holds and keeps track of the note post drafts throughout the app.
class Drafts: ObservableObject {
@Published var post: DraftArtifacts? = nil
@Published var replies: [NoteId: DraftArtifacts] = [:]
@Published var quotes: [NoteId: DraftArtifacts] = [:]
/// The drafts we have for highlights
///
/// ## Implementation notes
/// - Although in practice we also load drafts based on the highlight source for better UX (making it easier to find a draft), we need the keys to be of type `HighlightContentDraft` because we need the selected text information to be able to construct the NIP-37 draft, as well as to load that into post view.
@Published var highlights: [HighlightContentDraft: DraftArtifacts] = [:]
/// Loads drafts from storage (NostrDB + UserDefaults)
func load(from damus_state: DamusState) {
guard let note_ids = damus_state.settings.draft_event_ids?.compactMap({ NoteId(hex: $0) }) else { return }
for note_id in note_ids {
let txn = damus_state.ndb.lookup_note(note_id)
guard let note = txn?.unsafeUnownedValue else { continue }
// Implementation note: This currently fails silently, because:
// 1. Errors are unlikely and not expected
// 2. It is not mission critical to recover from this error
// 3. The changes that add a error view sheet with useful info is not yet merged in as of writing.
try? self.load(wrapped_draft_note: note, with: damus_state)
}
}
/// Loads a specific NIP-37 note into this class
func load(wrapped_draft_note: NdbNote, with damus_state: DamusState) throws {
// Extract draft info from the NIP-37 note
guard let full_keypair = damus_state.keypair.to_full() else { return }
guard let nip37_draft = try NIP37Draft(wrapped_note: wrapped_draft_note, keypair: full_keypair) else { return }
guard let known_kind = nip37_draft.unwrapped_note.known_kind else { return }
guard let draft_artifacts = DraftArtifacts.from(
nip37_draft: nip37_draft,
damus_state: damus_state
) else { return }
// Find out where to place these drafts
let blocks = parse_note_content(content: .note(nip37_draft.unwrapped_note))
switch known_kind {
case .text:
if let replied_to_note_id = nip37_draft.unwrapped_note.direct_replies() {
self.replies[replied_to_note_id] = draft_artifacts
}
else {
for block in blocks.blocks {
if case .mention(let mention) = block {
if case .note(let note_id) = mention.ref {
self.quotes[note_id] = draft_artifacts
return
}
}
}
self.post = draft_artifacts
}
case .highlight:
guard let highlight = HighlightContentDraft(from: nip37_draft.unwrapped_note) else { return }
self.highlights[highlight] = draft_artifacts
default:
return
}
}
/// Saves the drafts tracked by this class persistently using NostrDB + UserDefaults
func save(damus_state: DamusState) {
var draft_events: [NdbNote] = []
post_artifact_block: if let post_artifacts = self.post {
let nip37_draft = try? post_artifacts.to_nip37_draft(action: .posting(.user(damus_state.pubkey)), damus_state: damus_state)
guard let wrapped_note = nip37_draft?.wrapped_note else { break post_artifact_block }
draft_events.append(wrapped_note)
}
for (replied_to_note_id, reply_artifacts) in self.replies {
guard let replied_to_note = damus_state.ndb.lookup_note(replied_to_note_id)?.unsafeUnownedValue?.to_owned() else { continue }
let nip37_draft = try? reply_artifacts.to_nip37_draft(action: .replying_to(replied_to_note), damus_state: damus_state)
guard let wrapped_note = nip37_draft?.wrapped_note else { continue }
draft_events.append(wrapped_note)
}
for (quoted_note_id, quote_note_artifacts) in self.quotes {
guard let quoted_note = damus_state.ndb.lookup_note(quoted_note_id)?.unsafeUnownedValue?.to_owned() else { continue }
let nip37_draft = try? quote_note_artifacts.to_nip37_draft(action: .quoting(quoted_note), damus_state: damus_state)
guard let wrapped_note = nip37_draft?.wrapped_note else { continue }
draft_events.append(wrapped_note)
}
for (highlight, highlight_note_artifacts) in self.highlights {
let nip37_draft = try? highlight_note_artifacts.to_nip37_draft(action: .highlighting(highlight), damus_state: damus_state)
guard let wrapped_note = nip37_draft?.wrapped_note else { continue }
draft_events.append(wrapped_note)
}
for draft_event in draft_events {
// Implementation note: We do not support draft synchronization with relays yet.
// TODO: Once it is time to implement draft syncing with relays, please consider the following:
// - Privacy: Sending drafts to the network leaks metadata about app activity, and may break user expectations
// - Down-sync conflict resolution: Consider how to solve conflicts for different draft versions holding the same ID (e.g. edited in Damus, then another client, then Damus again)
damus_state.pool.send_raw_to_local_ndb(.typical(.event(draft_event)))
}
damus_state.settings.draft_event_ids = draft_events.map({ $0.id.hex() })
}
}
// MARK: - Convenience extensions
fileprivate extension Array {
mutating func appendIfNotNil(_ element: Element?) {
if let element = element {
self.append(element)
}
}
@Published var replies: [NostrEvent: DraftArtifacts] = [:]
@Published var quotes: [NostrEvent: DraftArtifacts] = [:]
@Published var highlights: [HighlightSource: DraftArtifacts] = [:]
}
+5 -31
View File
@@ -188,29 +188,17 @@ extension HighlightEvent {
struct HighlightContentDraft: Hashable {
let selected_text: String
let source: HighlightSource
init(selected_text: String, source: HighlightSource) {
self.selected_text = selected_text
self.source = source
}
init?(from note: NdbNote) {
guard let source = HighlightSource.from(tags: note.tags.strings()) else { return nil }
self.source = source
self.selected_text = note.content
}
}
enum HighlightSource: Hashable {
static let TAG_SOURCE_ELEMENT = "source"
case event(NoteId)
case event(NostrEvent)
case external_url(URL)
func tags() -> [[String]] {
switch self {
case .event(let event_id):
return [ ["e", "\(event_id)", HighlightSource.TAG_SOURCE_ELEMENT] ]
case .event(let event):
return [ ["e", "\(event.id)", HighlightSource.TAG_SOURCE_ELEMENT] ]
case .external_url(let url):
return [ ["r", "\(url)", HighlightSource.TAG_SOURCE_ELEMENT] ]
}
@@ -218,26 +206,12 @@ enum HighlightSource: Hashable {
func ref() -> RefId {
switch self {
case .event(let event_id):
return .event(event_id)
case .event(let event):
return .event(event.id)
case .external_url(let url):
return .reference(url.absoluteString)
}
}
static func from(tags: [[String]]) -> HighlightSource? {
for tag in tags {
if tag.count == 3 && tag[0] == "e" && tag[2] == HighlightSource.TAG_SOURCE_ELEMENT {
guard let event_id = NoteId(hex: tag[1]) else { continue }
return .event(event_id)
}
if tag.count == 3 && tag[0] == "r" && tag[2] == HighlightSource.TAG_SOURCE_ELEMENT {
guard let url = URL(string: tag[1]) else { continue }
return .external_url(url)
}
}
return nil
}
}
struct ShareContent {
+6 -40
View File
@@ -79,7 +79,6 @@ class HomeModel: ContactsDelegate {
var notifications = NotificationsModel()
var notification_status = NotificationStatusModel()
var events: EventHolder = EventHolder()
var already_reposted: Set<NoteId> = Set()
var zap_button: ZapButtonModel = ZapButtonModel()
init() {
@@ -123,7 +122,6 @@ class HomeModel: ContactsDelegate {
/// This is called whenever DamusState gets set. This function is used to load or setup anything we need from the new DamusState
func load_our_stuff_from_damus_state() {
self.load_latest_contact_event_from_damus_state()
self.load_drafts_from_damus_state()
}
/// This loads the latest contact event we have on file from NostrDB. This should be called as soon as we get the new DamusState
@@ -136,10 +134,6 @@ class HomeModel: ContactsDelegate {
process_contact_event(state: damus_state, ev: latest_contact_event)
}
func load_drafts_from_damus_state() {
damus_state.drafts.load(from: damus_state)
}
// MARK: - ContactsDelegate functions
func latest_contact_event_changed(new_event: NostrEvent) {
@@ -221,10 +215,6 @@ class HomeModel: ContactsDelegate {
break
case .status:
handle_status_event(ev)
case .draft:
// TODO: Implement draft syncing with relays. We intentionally do not support that as of writing. See `DraftsModel.swift` for other details
// try? damus_state.drafts.load(wrapped_draft_note: ev, with: damus_state)
break
}
}
@@ -260,7 +250,7 @@ class HomeModel: ContactsDelegate {
// TODO: Adapt KeychainStorage to StringCodable and instead of parsing to WalletConnectURL every time
guard let nwc_str = damus_state.settings.nostr_wallet_connect,
let nwc = WalletConnectURL(str: nwc_str),
let resp = await WalletConnect.FullWalletResponse(from: ev, nwc: nwc) else {
let resp = await FullWalletResponse(from: ev, nwc: nwc) else {
return
}
@@ -274,24 +264,12 @@ class HomeModel: ContactsDelegate {
guard resp.response.error == nil else {
print("nwc error: \(resp.response)")
WalletConnect.handle_error(zapcache: self.damus_state.zaps, evcache: self.damus_state.events, resp: resp)
nwc_error(zapcache: self.damus_state.zaps, evcache: self.damus_state.events, resp: resp)
return
}
if resp.response.result_type == .list_transactions {
Log.info("Received NWC transaction list from %s", for: .nwc, relay.absoluteString)
damus_state.wallet.handle_nwc_response(response: resp)
return
}
if resp.response.result_type == .get_balance {
Log.info("Received NWC balance information from %s", for: .nwc, relay.absoluteString)
damus_state.wallet.handle_nwc_response(response: resp)
return
}
print("nwc success: \(resp.response.result.debugDescription) [\(relay)]")
WalletConnect.handle_zap_success(state: self.damus_state, resp: resp)
nwc_success(state: self.damus_state, resp: resp)
}
}
@@ -388,8 +366,6 @@ class HomeModel: ContactsDelegate {
boost_ev_id = inner_ev.id
Task {
// NOTE (jb55): remove this after nostrdb update, since nostrdb
// processess reposts when note is ingested
guard validate_event(ev: inner_ev) == .ok else {
return
}
@@ -409,7 +385,7 @@ class HomeModel: ContactsDelegate {
switch self.damus_state.boosts.add_event(ev, target: e) {
case .already_counted:
break
case .success(_):
case .success(let n):
notify(.update_stats(note_id: e))
}
}
@@ -418,7 +394,7 @@ class HomeModel: ContactsDelegate {
switch damus_state.quote_reposts.add_event(ev, target: target) {
case .already_counted:
break
case .success(_):
case .success(let n):
notify(.update_stats(note_id: target))
}
}
@@ -465,7 +441,7 @@ class HomeModel: ContactsDelegate {
let nwc = WalletConnectURL(str: nwc_str),
nwc.relay == relay_id
{
WalletConnect.subscribe(url: nwc, pool: pool)
subscribe_to_nwc(url: nwc, pool: pool)
}
case .error(let merr):
let desc = String(describing: merr)
@@ -747,16 +723,6 @@ class HomeModel: ContactsDelegate {
handle_quote_repost_event(ev, target: quoted_event.note_id)
}
// don't add duplicate reposts to home
if ev.known_kind == .boost, let target = ev.get_inner_event()?.id {
if already_reposted.contains(target) {
Log.info("Skipping duplicate repost for event %s", for: .timeline, target.hex())
return
} else {
already_reposted.insert(target)
}
}
if sub_id == home_subid {
insert_home_event(ev)
} else if sub_id == notifications_subid {
+1 -1
View File
@@ -2,7 +2,7 @@
// LongformEvent.swift
// damus
//
// Created by Daniel D'Aquino on 2023-11-24.
// Created by Daniel Nogueira on 2023-11-24.
//
import Foundation
-4
View File
@@ -122,10 +122,6 @@ enum MentionRef: TagKeys, TagConvertible, Equatable, Hashable {
}
}
protocol URLEncodable {
func url() -> URL?
}
struct Mention<T: Equatable>: Equatable {
let index: Int?
let ref: T
+18 -65
View File
@@ -22,10 +22,8 @@ class ProfileModel: ObservableObject, Equatable {
var seen_event: Set<NoteId> = Set()
var sub_id = UUID().description
var prof_subid = UUID().description
var conversations_subid = UUID().description
var findRelay_subid = UUID().description
var conversation_events: Set<NoteId> = Set()
init(pubkey: Pubkey, damus: DamusState) {
self.pubkey = pubkey
self.damus = damus
@@ -61,9 +59,6 @@ class ProfileModel: ObservableObject, Equatable {
print("unsubscribing from profile \(pubkey) with sub_id \(sub_id)")
damus.pool.unsubscribe(sub_id: sub_id)
damus.pool.unsubscribe(sub_id: prof_subid)
if pubkey != damus.pubkey {
damus.pool.unsubscribe(sub_id: conversations_subid)
}
}
func subscribe() {
@@ -74,29 +69,13 @@ class ProfileModel: ObservableObject, Equatable {
text_filter.authors = [pubkey]
text_filter.limit = 500
print("subscribing to textlike events from profile \(pubkey) with sub_id \(sub_id)")
print("subscribing to profile \(pubkey) with sub_id \(sub_id)")
//print_filters(relay_id: "profile", filters: [[text_filter], [profile_filter]])
damus.pool.subscribe(sub_id: sub_id, filters: [text_filter], handler: handle_event)
damus.pool.subscribe(sub_id: prof_subid, filters: [profile_filter], handler: handle_event)
subscribe_to_conversations()
}
private func subscribe_to_conversations() {
// Only subscribe to conversation events if the profile is not us.
guard pubkey != damus.pubkey else {
return
}
let conversation_kinds: [NostrKind] = [.text, .longform, .highlight]
let limit: UInt32 = 500
let conversations_filter_them = NostrFilter(kinds: conversation_kinds, pubkeys: [damus.pubkey], limit: limit, authors: [pubkey])
let conversations_filter_us = NostrFilter(kinds: conversation_kinds, pubkeys: [pubkey], limit: limit, authors: [damus.pubkey])
print("subscribing to conversation events from and to profile \(pubkey) with sub_id \(conversations_subid)")
damus.pool.subscribe(sub_id: conversations_subid, filters: [conversations_filter_them, conversations_filter_us], handler: handle_event)
}
func handle_profile_contact_event(_ ev: NostrEvent) {
process_contact_event(state: damus, ev: ev)
@@ -111,8 +90,15 @@ class ProfileModel: ObservableObject, Equatable {
self.following = count_pubkeys(ev.tags)
self.relays = decode_json_relays(ev.content)
}
func add_event(_ ev: NostrEvent) {
guard ev.should_show_event else {
return
}
private func add_event(_ ev: NostrEvent) {
if seen_event.contains(ev.id) {
return
}
if ev.is_textlike || ev.known_kind == .boost {
if self.events.insert(ev) {
self.objectWillChange.send()
@@ -123,57 +109,24 @@ class ProfileModel: ObservableObject, Equatable {
seen_event.insert(ev.id)
}
// Ensure the event public key matches the public key(s) we are querying.
// This is done to protect against a relay not properly filtering events by the pubkey
// See https://github.com/damus-io/damus/issues/1846 for more information
private func relay_filtered_correctly(_ ev: NostrEvent, subid: String?) -> Bool {
if subid == self.conversations_subid {
switch ev.pubkey {
case self.pubkey:
return ev.referenced_pubkeys.contains(damus.pubkey)
case damus.pubkey:
return ev.referenced_pubkeys.contains(self.pubkey)
default:
return false
}
}
return self.pubkey == ev.pubkey
}
private func handle_event(relay_id: RelayURL, ev: NostrConnectionEvent) {
switch ev {
case .ws_event:
return
case .nostr_event(let resp):
guard resp.subid == self.sub_id || resp.subid == self.prof_subid || resp.subid == self.conversations_subid else {
guard resp.subid == self.sub_id || resp.subid == self.prof_subid else {
return
}
switch resp {
case .ok:
break
case .event(_, let ev):
guard ev.should_show_event else {
break
}
// Ensure the event public key matches this profiles public key
// This is done to protect against a relay not properly filtering events by the pubkey
// See https://github.com/damus-io/damus/issues/1846 for more information
guard self.pubkey == ev.pubkey else { break }
if !seen_event.contains(ev.id) {
guard relay_filtered_correctly(ev, subid: resp.subid) else {
break
}
add_event(ev)
if resp.subid == self.conversations_subid {
conversation_events.insert(ev.id)
}
} else if resp.subid == self.conversations_subid && !conversation_events.contains(ev.id) {
guard relay_filtered_correctly(ev, subid: resp.subid) else {
break
}
conversation_events.insert(ev.id)
}
add_event(ev)
case .notice:
break
//notify(.notice, notice)
+1 -50
View File
@@ -363,42 +363,6 @@ class DamusPurple: StoreObserverDelegate {
return freshly_completed_checkouts
}
/// Handles a Purple URL
/// - Parameter purple_url: The Purple URL being opened
/// - Returns: A view to be shown in the UI
@MainActor
func handle(purple_url: DamusPurpleURL) async -> ContentView.ViewOpenAction {
if case let .welcome(checkout_id) = purple_url.variant {
// If this is a welcome link, do the following before showing the onboarding screen:
// 1. Check if this is legitimate and good to go.
// 2. Mark as complete if this is good to go.
let is_good_to_go = try? await check_and_mark_ln_checkout_is_good_to_go(checkout_id: checkout_id)
switch is_good_to_go {
case .some(let is_good_to_go):
if is_good_to_go {
return .sheet(.purple(purple_url)) // ALL GOOD, SHOW WELCOME SHEET
}
else {
return .sheet(.error(.init(
user_visible_description: NSLocalizedString("You clicked on a Purple welcome link, but it does not look like the checkout is completed yet. This is likely a bug.", comment: "Error label upon continuing in the app from a Damus Purple purchase"),
tip: NSLocalizedString("Please double-check the checkout web page, or go to the Side Menu → \"Purple\" to check your account status. If you have already paid, but still don't see your account active, please save the URL of the checkout page where you came from, contact our support, and give us the URL to help you with this issue.", comment: "User-facing tips on what to do if a Purple welcome link doesn't work"),
technical_info: "Handling Purple URL \"\(purple_url)\" failed, the `is_good_to_go` result was `\(is_good_to_go)`"
)))
}
case .none:
return .sheet(.error(.init(
user_visible_description: NSLocalizedString("You clicked on a Purple welcome link, but we could not find your checkout. This is likely a bug.", comment: "Error label upon continuing in the app from a Damus Purple purchase"),
tip: NSLocalizedString("Please double-check the checkout web page, or go to the Side Menu → \"Purple\" to check your account status. If you have already paid, but still don't see your account active, please save the URL of the checkout page where you came from, contact our support, and give us the URL to help you with this issue.", comment: "User-facing tips on what to do if a Purple welcome link doesn't work"),
technical_info: "Handling Purple URL \"\(purple_url)\" failed, the `is_good_to_go` result was `\(String(describing: is_good_to_go))`"
)))
}
}
else {
// Show the purple url contents
return .sheet(.purple(purple_url))
}
}
@MainActor
/// This function checks the status of a specific checkout id with the server
/// You should use this result immediately, since it will internally be marked as handled
@@ -418,13 +382,6 @@ class DamusPurple: StoreObserverDelegate {
let expiry: Date
let subscriber_number: Int
let active: Bool
let attributes: PurpleAccountAttributes
struct PurpleAccountAttributes: OptionSet {
let rawValue: Int
static let memberForMoreThanOneYear = PurpleAccountAttributes(rawValue: 1 << 0)
}
func ordinal() -> String? {
let number = Int(self.subscriber_number)
@@ -445,8 +402,7 @@ class DamusPurple: StoreObserverDelegate {
created_at: Date.init(timeIntervalSince1970: TimeInterval(payload.created_at)),
expiry: Date.init(timeIntervalSince1970: TimeInterval(payload.expiry)),
subscriber_number: Int(payload.subscriber_number),
active: payload.active,
attributes: (payload.attributes?.member_for_more_than_one_year ?? false) ? [.memberForMoreThanOneYear] : []
active: payload.active
)
}
@@ -456,11 +412,6 @@ class DamusPurple: StoreObserverDelegate {
let expiry: UInt64 // Unix timestamp
let subscriber_number: UInt
let active: Bool
let attributes: Attributes?
struct Attributes: Codable {
let member_for_more_than_one_year: Bool
}
}
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// DamusPurpleURL.swift
// damus
//
// Created by Daniel D'Aquino on 2024-01-13.
// Created by Daniel Nogueira on 2024-01-13.
//
import Foundation
+50 -270
View File
@@ -7,86 +7,42 @@
import Foundation
/// manages the lifetime of a thread in a thread view such as `ChatroomThreadView`
/// Makes a subscription to the relay pool to get events related to the thread
/// It also keeps track of a selected event in the thread, and can pinpoint all of its parents and reply chain
@MainActor
/// manages the lifetime of a thread
class ThreadModel: ObservableObject {
/// The original event where this thread was loaded from
/// We use this to know the starting point from which we try to load the rest of the thread
/// This is immutable because this is our starting point of the thread, and we don't expect this to ever change during the lifetime of a thread view
@Published var event: NostrEvent
let original_event: NostrEvent
/// A map of events, the reply chain, etc
/// This can be read by the view, but it can only be updated internally, because it is this classes' responsibility to ensure we load the proper events
@Published private(set) var event_map: ThreadEventMap
/// The currently selected event
/// Can only be directly changed internally. Views should set this via the `select` methods
@Published private(set) var selected_event: NostrEvent
let highlight: String?
var event_map: Set<NostrEvent>
/// All of the parent events of `selected_event` in the thread, sorted from the highest level in the thread (The root of the thread), down to the direct parent
///
/// ## Implementation notes
///
/// This is a computed property because we then don't need to worry about keeping things in sync
var parent_events: [NostrEvent] {
// This block of code helps ensure `ThreadEventMap` stays in sync with `EventCache`
let parent_events_from_cache = damus_state.events.parent_events(event: selected_event, keypair: damus_state.keypair)
for parent_event in parent_events_from_cache {
add_event(
parent_event,
keypair: damus_state.keypair,
look_for_parent_events: false, // We have all parents we need for now
publish_changes: false // Publishing changes during a view render is problematic
)
}
return parent_events_from_cache
}
/// All of the direct and indirect replies of `selected_event` in the thread. sorted chronologically
///
/// ## Implementation notes
///
/// This is a computed property because we then don't need to worry about keeping things in sync
var sorted_child_events: [NostrEvent] {
event_map.sorted_recursive_child_events(of: selected_event).filter({
should_show_event(event: $0, damus_state: damus_state) // Hide muted events from chatroom conversation
})
}
/// The damus state, needed to access the relay pool and load the thread events
let damus_state: DamusState
private let profiles_subid = UUID().description
private let base_subid = UUID().description
private let meta_subid = UUID().description
private var subids: [String] {
return [profiles_subid, base_subid, meta_subid]
}
// MARK: Initialization
/// Initialize this model
///
/// You should also call `subscribe()` to start loading thread events from the relay pool.
/// This is done manually to ensure we only load stuff when needed (e.g. when a view appears)
init(event: NostrEvent, damus_state: DamusState) {
init(event: NostrEvent, damus_state: DamusState, highlight: String? = nil) {
self.damus_state = damus_state
self.event_map = ThreadEventMap()
self.event_map = Set()
self.event = event
self.original_event = event
self.selected_event = event
self.highlight = highlight
add_event(event, keypair: damus_state.keypair)
}
/// All events in the thread, sorted in chronological order
var events: [NostrEvent] {
return event_map.sorted_events
func events() -> [NostrEvent] {
return Array(event_map).sorted(by: { a, b in
return a.created_at < b.created_at
})
}
var is_original: Bool {
return original_event.id == event.id
}
let damus_state: DamusState
// MARK: Relay pool subscription management
let profiles_subid = UUID().description
let base_subid = UUID().description
let meta_subid = UUID().description
var subids: [String] {
return [profiles_subid, base_subid, meta_subid]
}
/// Unsubscribe from events in the relay pool. Call this when unloading the view
func unsubscribe() {
self.damus_state.pool.remove_handler(sub_id: base_subid)
self.damus_state.pool.remove_handler(sub_id: meta_subid)
@@ -94,25 +50,33 @@ class ThreadModel: ObservableObject {
self.damus_state.pool.unsubscribe(sub_id: base_subid)
self.damus_state.pool.unsubscribe(sub_id: meta_subid)
self.damus_state.pool.unsubscribe(sub_id: profiles_subid)
Log.info("unsubscribing to thread %s with sub_id %s", for: .render, original_event.id.hex(), base_subid)
print("unsubscribing from thread \(event.id) with sub_id \(base_subid)")
}
@discardableResult
func set_active_event(_ ev: NostrEvent, keypair: Keypair) -> Bool {
self.event = ev
add_event(ev, keypair: keypair)
//self.objectWillChange.send()
return false
}
/// Subscribe to events in this thread. Call this when loading the view.
func subscribe() {
var meta_events = NostrFilter()
var quote_events = NostrFilter()
var event_filter = NostrFilter()
var ref_events = NostrFilter()
let thread_id = original_event.thread_id()
let thread_id = event.thread_id()
ref_events.referenced_ids = [thread_id, original_event.id]
ref_events.referenced_ids = [thread_id, event.id]
ref_events.kinds = [.text]
ref_events.limit = 1000
event_filter.ids = [thread_id, original_event.id]
event_filter.ids = [thread_id, event.id]
meta_events.referenced_ids = [original_event.id]
meta_events.referenced_ids = [event.id]
var kinds: [NostrKind] = [.zap, .text, .boost]
if !damus_state.settings.onlyzaps_mode {
@@ -122,60 +86,33 @@ class ThreadModel: ObservableObject {
meta_events.limit = 1000
quote_events.kinds = [.text]
quote_events.quotes = [original_event.id]
quote_events.quotes = [event.id]
quote_events.limit = 1000
let base_filters = [event_filter, ref_events]
let meta_filters = [meta_events, quote_events]
Log.info("subscribing to thread %s with sub_id %s", for: .render, original_event.id.hex(), base_subid)
print("subscribing to thread \(event.id) with sub_id \(base_subid)")
damus_state.pool.subscribe(sub_id: base_subid, filters: base_filters, handler: handle_event)
damus_state.pool.subscribe(sub_id: meta_subid, filters: meta_filters, handler: handle_event)
}
/// Adds an event to this thread.
/// Normally this does not need to be called externally because it is the responsibility of this class to load the events, not the view's.
/// However, this can be called externally for testing purposes (e.g. injecting events for testing)
///
/// - Parameters:
/// - ev: The event to add into the thread event map
/// - keypair: The user's keypair
/// - look_for_parent_events: Whether to search for parent events of the input event in NostrDB
/// - publish_changes: Whether to publish changes at the end
func add_event(_ ev: NostrEvent, keypair: Keypair, look_for_parent_events: Bool = true, publish_changes: Bool = true) {
if event_map.contains(id: ev.id) {
func add_event(_ ev: NostrEvent, keypair: Keypair) {
if event_map.contains(ev) {
return
}
_ = damus_state.events.upsert(ev)
damus_state.events.upsert(ev)
damus_state.replies.count_replies(ev, keypair: keypair)
damus_state.events.add_replies(ev: ev, keypair: keypair)
event_map.add(event: ev)
if look_for_parent_events {
// Add all parent events that we have on EventCache (and subsequently on NostrDB)
// This helps ensure we include as many locally-stored notes as possible even on poor networking conditions
damus_state.events.parent_events(event: ev, keypair: damus_state.keypair).forEach {
add_event(
$0, // The `lookup` function in `parent_events` turns the event into an "owned" object, so we do not need to clone here
keypair: damus_state.keypair,
look_for_parent_events: false, // We do not need deep recursion
publish_changes: false // Do not publish changes multiple times
)
}
}
if publish_changes {
objectWillChange.send()
}
event_map.insert(ev)
objectWillChange.send()
}
/// Handles an incoming event from a relay pool
///
/// Marked as private because it is this class' responsibility to load events, not the view's. Simplify the interface
@MainActor
private func handle_event(relay_id: RelayURL, ev: NostrConnectionEvent) {
func handle_event(relay_id: RelayURL, ev: NostrConnectionEvent) {
let (sub_id, done) = handle_subid_event(pool: damus_state.pool, relay_id: relay_id, ev: ev) { sid, ev in
guard subids.contains(sid) else {
return
@@ -188,7 +125,7 @@ class ThreadModel: ObservableObject {
} else if ev.is_textlike {
// handle thread quote reposts, we just count them instead of
// adding them to the thread
if let target = ev.is_quote_repost, target == self.selected_event.id {
if let target = ev.is_quote_repost, target == self.event.id {
//let _ = self.damus_state.quote_reposts.add_event(ev, target: target)
} else {
self.add_event(ev, keypair: damus_state.keypair)
@@ -202,167 +139,10 @@ class ThreadModel: ObservableObject {
if sub_id == self.base_subid {
guard let txn = NdbTxn(ndb: damus_state.ndb) else { return }
load_profiles(context: "thread", profiles_subid: self.profiles_subid, relay_id: relay_id, load: .from_events(Array(event_map.events)), damus_state: damus_state, txn: txn)
}
}
// MARK: External control interface
// Control methods created for the thread view
/// Change the currently selected event
///
/// - Parameter event: Event to select
func select(event: NostrEvent) {
self.selected_event = event
add_event(event, keypair: damus_state.keypair)
}
}
/// A thread event map, a model that holds events, indexes them, and can efficiently answer questions about a thread.
///
/// Add events that are part of a thread to this model, and use one of its many convenience functions to get answers about the hierarchy of the thread.
///
/// This does NOT perform any event loading, networking, or storage operations. This is simply a convenient/efficient way to keep and query about a thread
struct ThreadEventMap {
/// A map for keeping nostr events, and efficiently querying them by note id
///
/// Marked as `private` because:
/// - We want to hide this complexity from the user of this struct
/// - It is this struct's responsibility to keep this in sync with `event_reply_index`
private var event_map: [NoteId: NostrEvent] = [:]
/// An index of the reply hierarchy, which allows replies to be found in O(1) efficiency
///
/// ## Implementation notes
///
/// Marked as `private` because:
/// - We want to hide this complexity from the user of this struct
/// - It is this struct's responsibility to keep this in sync with `event_map`
///
/// We only store note ids to save space, as we can easily get them from `event_map`
private var event_reply_index: [NoteId: Set<NoteId>] = [:]
// MARK: External interface
/// Events in the thread, in no particular order
/// Use this when the order does not matter
var events: Set<NostrEvent> {
return Set(event_map.values)
}
/// Events in the thread, sorted chronologically. Use this when the order matters.
/// Use `.events` when the order doesn't matter, as it is more computationally efficient.
var sorted_events: [NostrEvent] {
return events.sorted(by: { a, b in
return a.created_at < b.created_at
})
}
/// Add an event to this map
///
/// Efficiency: O(1)
///
/// - Parameter event: The event to be added
mutating func add(event: NostrEvent) {
self.event_map[event.id] = event
// Update our efficient reply index
if let note_id_replied_to = event.direct_replies() {
if event_reply_index[note_id_replied_to] == nil {
event_reply_index[note_id_replied_to] = [event.id]
}
else {
event_reply_index[note_id_replied_to]?.insert(event.id)
}
load_profiles(context: "thread", profiles_subid: self.profiles_subid, relay_id: relay_id, load: .from_events(Array(event_map)), damus_state: damus_state, txn: txn)
}
}
/// Whether the thread map contains a given note, referenced by ID
///
/// Efficiency: O(1)
///
/// - Parameter id: The ID to look for
/// - Returns: True if it does, false otherwise
func contains(id: NoteId) -> Bool {
return self.event_map[id] != nil
}
/// Gets a note from the thread by its id
///
/// Efficiency: O(1)
///
/// - Parameter id: The note id
/// - Returns: The note, if it exists in the thread map.
func get(id: NoteId) -> NostrEvent? {
return self.event_map[id]
}
/// Returns all the parent events in a thread, relative to a given event
///
/// Efficiency: O(N) in the worst case
///
/// - Parameter query_event: The event for which to find the parents for
/// - Returns: An array of parent events, sorted from the highest level in the thread (The root of the thread), down to the direct parent of the query event. If query event is not found, this will return an empty array
func parent_events(of query_event: NostrEvent) -> [NostrEvent] {
var parents: [NostrEvent] = []
var event = query_event
while true {
guard let direct_reply = event.direct_replies(),
let parent_event = self.get(id: direct_reply), parent_event != event
else {
break
}
parents.append(parent_event)
event = parent_event
}
return parents.reversed()
}
/// All of the replies in a thread for a given event, including indirect replies (reply of a reply), sorted in chronological order
///
/// Efficiency: O(Nlog(N)) in the worst case scenario, coming from Swift's built-in sorting algorithm "Timsort"
///
/// - Parameter query_event: The event for which to find the children for
/// - Returns: All of the direct and indirect replies for an event, sorted in chronological order. If query event is not present, this will be an empty array.
func sorted_recursive_child_events(of query_event: NostrEvent) -> [NostrEvent] {
let all_recursive_child_events = self.recursive_child_events(of: query_event)
return all_recursive_child_events.sorted(by: { a, b in
return a.created_at < b.created_at
})
}
/// All of the replies in a thread for a given event, including indirect replies (reply of a reply), in any order
///
/// Use this when the order does not matter, as it is more efficient
///
/// Efficiency: O(N) in the worst case scenario.
///
/// - Parameter query_event: The event for which to find the children for
/// - Returns: All of the direct and indirect replies for an event, sorted in chronological order. If query event is not present, this will be an empty array.
func recursive_child_events(of query_event: NostrEvent) -> Set<NostrEvent> {
let immediate_children_ids = self.event_reply_index[query_event.id] ?? []
var immediate_children: Set<NostrEvent> = []
for immediate_child_id in immediate_children_ids {
guard let immediate_child = self.event_map[immediate_child_id] else {
// This is an internal inconsistency.
// Crash the app in debug mode to increase awareness, but let it go in production mode (not mission critical)
assertionFailure("Desync between `event_map` and `event_reply_index` should never happen in `ThreadEventMap`!")
continue
}
immediate_children.insert(immediate_child)
}
var indirect_children: Set<NdbNote> = []
for immediate_child in immediate_children {
let recursive_children = self.recursive_child_events(of: immediate_child)
indirect_children = indirect_children.union(recursive_children)
}
return immediate_children.union(indirect_children)
}
}
-107
View File
@@ -1,107 +0,0 @@
//
// URLHandler.swift
// damus
//
// Created by Daniel DAquino on 2024-09-06.
//
import Foundation
/// Parses URLs into actions within the app.
///
/// ## Implementation notes
///
/// - This exists so that we can separate the logic of parsing the URL and the actual action within the app. That makes the code more readable, testable, and extensible
struct DamusURLHandler {
/// Parses a URL, handles any needed actions within damus state, and returns the view to be opened in the app
///
/// Side effects: May mutate `damus_state` in some circumstances
///
/// - Parameters:
/// - damus_state: The Damus state. May be mutated as part of this function
/// - url: The URL to be opened
/// - Returns: A view to be shown to the user
static func handle_opening_url_and_compute_view_action(damus_state: DamusState, url: URL) async -> ContentView.ViewOpenAction {
let parsed_url_info = parse_url(url: url)
switch parsed_url_info {
case .profile(let pubkey):
return .route(.ProfileByKey(pubkey: pubkey))
case .filter(let nostrFilter):
let search = SearchModel(state: damus_state, search: nostrFilter)
return .route(.Search(search: search))
case .event(let nostrEvent):
let thread = await ThreadModel(event: nostrEvent, damus_state: damus_state)
return .route(.Thread(thread: thread))
case .event_reference(let event_reference):
return .route(.LoadableNostrEvent(note_reference: event_reference))
case .wallet_connect(let walletConnectURL):
damus_state.wallet.new(walletConnectURL)
return .route(.Wallet(wallet: damus_state.wallet))
case .script(let data):
let model = ScriptModel(data: data, state: .not_loaded)
return .route(.Script(script: model))
case .purple(let purple_url):
return await damus_state.purple.handle(purple_url: purple_url)
case nil:
break
}
return .sheet(.error(ErrorView.UserPresentableError(
user_visible_description: NSLocalizedString("Could not parse the URL you are trying to open.", comment: "User visible error description"),
tip: NSLocalizedString("Please try again, check the URL for typos, or contact support for further help.", comment: "User visible error tips"),
technical_info: "Could not find a suitable open action. User tried to open this URL: \(url.absoluteString)"
)))
}
/// Parses a URL into a structured information object.
///
/// This function does not cause any mutations on the app, or any side-effects.
///
/// - Parameter url: The URL to be parsed
/// - Returns: Structured information about the contents inside the URL. Returns `nil` if URL is not compatible, invalid, or could not be parsed for some reason.
static func parse_url(url: URL) -> ParsedURLInfo? {
if let purple_url = DamusPurpleURL(url: url) {
return .purple(purple_url)
}
if let nwc = WalletConnectURL(str: url.absoluteString) {
return .wallet_connect(nwc)
}
guard let link = decode_nostr_uri(url.absoluteString) else {
return nil
}
switch link {
case .ref(let ref):
switch ref {
case .pubkey(let pk):
return .profile(pk)
case .event(let noteid):
return .event_reference(.note_id(noteid))
case .hashtag(let ht):
return .filter(.filter_hashtag([ht.hashtag]))
case .param, .quote, .reference:
// doesn't really make sense here
break
case .naddr(let naddr):
return .event_reference(.naddr(naddr))
}
case .filter(let filt):
return .filter(filt)
case .script(let script):
return .script(script)
}
return nil
}
enum ParsedURLInfo {
case profile(Pubkey)
case filter(NostrFilter)
case event(NostrEvent)
case event_reference(LoadableNostrEventViewModel.NoteReference)
case wallet_connect(WalletConnectURL)
case script([UInt8])
case purple(DamusPurpleURL)
}
}
-8
View File
@@ -201,10 +201,6 @@ class UserSettingsStore: ObservableObject {
@Setting(key: "developer_mode", default_value: false)
var developer_mode: Bool
/// Makes all post content gibberish and blurhashes images, to avoid distractions when developers are working.
@Setting(key: "undistract_mode", default_value: false)
var undistractMode: Bool
@Setting(key: "always_show_onboarding_suggestions", default_value: false)
var always_show_onboarding_suggestions: Bool
@@ -328,13 +324,9 @@ class UserSettingsStore: ObservableObject {
// MARK: Internal, hidden settings
// TODO: Get rid of this once we have NostrDB query capabilities integrated
@Setting(key: "latest_contact_event_id", default_value: nil)
var latest_contact_event_id_hex: String?
// TODO: Get rid of this once we have NostrDB query capabilities integrated
@Setting(key: "draft_event_ids", default_value: nil)
var draft_event_ids: [String]?
// MARK: Helper types
-30
View File
@@ -13,17 +13,10 @@ enum WalletConnectState {
case none
}
/// Models and manages the user's NWC wallet based on the app's settings
class WalletModel: ObservableObject {
var settings: UserSettingsStore
private(set) var previous_state: WalletConnectState
var initial_percent: Int
/// The wallet's balance, in sats.
/// Starts with `nil` to signify it is not loaded yet
@Published private(set) var balance: Int64? = nil
/// The list of NWC transactions made in the wallet
/// Starts with `nil` to signify it is not loaded yet
@Published private(set) var transactions: [WalletConnect.Transaction]? = nil
@Published private(set) var connect_state: WalletConnectState
@@ -68,27 +61,4 @@ class WalletModel: ObservableObject {
self.connect_state = .existing(nwc)
self.previous_state = .existing(nwc)
}
/// Handles an NWC response event and updates the model.
///
/// This takes a response received from the NWC relay and updates the internal state of this model.
///
/// - Parameter response: The NWC response received from the network
func handle_nwc_response(response: WalletConnect.FullWalletResponse) {
switch response.response.result {
case .get_balance(let balanceResp):
self.balance = balanceResp.balance / 1000
case .none:
return
case .some(.pay_invoice(_)):
return
case .list_transactions(let transactionsResp):
self.transactions = transactionsResp.transactions
}
}
func resetWalletStateInformation() {
self.transactions = nil
self.balance = nil
}
}
-55
View File
@@ -1,55 +0,0 @@
//
// NIP04.swift
// damus
//
// Created by Daniel DAquino on 2025-03-10.
//
import Foundation
/// Functions and utilities for the NIP-04 spec
struct NIP04 {}
extension NIP04 {
/// Encrypts a message using NIP-04.
static func encrypt_message(message: String, privkey: Privkey, to_pk: Pubkey, encoding: EncEncoding = .base64) -> String? {
let iv = random_bytes(count: 16).bytes
guard let shared_sec = get_shared_secret(privkey: privkey, pubkey: to_pk) else {
return nil
}
let utf8_message = Data(message.utf8).bytes
guard let enc_message = aes_encrypt(data: utf8_message, iv: iv, shared_sec: shared_sec) else {
return nil
}
switch encoding {
case .base64:
return encode_dm_base64(content: enc_message.bytes, iv: iv)
case .bech32:
return encode_dm_bech32(content: enc_message.bytes, iv: iv)
}
}
/// Creates an event with encrypted `contents` field, using NIP-04
static func create_encrypted_event(_ message: String, to_pk: Pubkey, tags: [[String]], keypair: FullKeypair, created_at: UInt32, kind: UInt32) -> NostrEvent? {
let privkey = keypair.privkey
guard let enc_content = encrypt_message(message: message, privkey: privkey, to_pk: to_pk) else {
return nil
}
return NostrEvent(content: enc_content, keypair: keypair.to_keypair(), kind: kind, tags: tags, createdAt: created_at)
}
/// Creates a NIP-04 style direct message event
static func create_dm(_ message: String, to_pk: Pubkey, tags: [[String]], keypair: Keypair, created_at: UInt32? = nil) -> NostrEvent?
{
let created = created_at ?? UInt32(Date().timeIntervalSince1970)
guard let keypair = keypair.to_full() else {
return nil
}
return create_encrypted_event(message, to_pk: to_pk, tags: tags, keypair: keypair, created_at: created, kind: 4)
}
}
-119
View File
@@ -1,119 +0,0 @@
//
// NIP37Draft.swift
// damus
//
// Created by Daniel DAquino on 2025-01-20.
//
import Foundation
/// This models a NIP-37 draft.
///
/// It is an immutable data structure that automatically makes both sides of a NIP-37 draft available: Its unwrapped form and wrapped form.
///
/// This is useful for keeping it or passing it around to other functions when both sides will be used, or it is not known which side of it will be used.
///
/// Just initialize it, and read its properties.
struct NIP37Draft {
// MARK: Properties
// Implementation note: Must be immutable to maintain integrity of the structure.
/// The wrapped version of the draft. That is, a NIP-37 note with draft contents encrypted.
let wrapped_note: NdbNote
/// The unwrapped version of the draft. That is, the actual note that was being drafted.
let unwrapped_note: NdbNote
/// The unique ID of the draft, as per NIP-37
var id: String? {
return self.wrapped_note.referenced_params.first?.param.string()
}
// MARK: Initialization
/// Basic initializer
///
/// ## Implementation notes
///
/// - Using this externally defeats the whole purpose of using this struct, so this is kept private.
private init(wrapped_note: NdbNote, unwrapped_note: NdbNote) {
self.wrapped_note = wrapped_note
self.unwrapped_note = unwrapped_note
}
/// Initializes object with a wrapped NIP-37 note, if the keys can decrypt it.
/// - Parameters:
/// - wrapped_note: NIP-37 note
/// - keypair: The keys to decrypt
init?(wrapped_note: NdbNote, keypair: FullKeypair) throws {
self.wrapped_note = wrapped_note
guard let unwrapped_note = try Self.unwrap(note: wrapped_note, keypair: keypair) else { return nil }
self.unwrapped_note = unwrapped_note
}
/// Initializes object with an event to be wrapped into a NIP-37 draft
/// - Parameters:
/// - unwrapped_note: a note to be wrapped
/// - draft_id: the unique ID of this draft, as per NIP-37
/// - keypair: the keys to use for encrypting
init?(unwrapped_note: NdbNote, draft_id: String, keypair: FullKeypair) throws {
self.unwrapped_note = unwrapped_note
guard let wrapped_note = try Self.wrap(note: unwrapped_note, draft_id: draft_id, keypair: keypair) else { return nil }
self.wrapped_note = wrapped_note
}
// MARK: Static functions
// Use these when you just need to wrap/unwrap once
/// A function that wraps a note into NIP-37 draft event
/// - Parameters:
/// - note: the note that needs to be wrapped
/// - draft_id: the unique ID of the draft, as per NIP-37
/// - keypair: the keys to use for encrypting
/// - Returns: A NIP-37 draft, if it succeeds.
static func wrap(note: NdbNote, draft_id: String, keypair: FullKeypair) throws -> NdbNote? {
let note_json_data = try JSONEncoder().encode(note)
guard let note_json_string = String(data: note_json_data, encoding: .utf8) else {
throw NIP37DraftEventError.encoding_error
}
guard let contents = try? NIP44v2Encryption.encrypt(plaintext: note_json_string, privateKeyA: keypair.privkey, publicKeyB: keypair.pubkey) else {
return nil
}
var tags = [
["d", draft_id],
["k", String(note.kind)],
]
if let replied_to_note = note.direct_replies() {
tags.append(["e", replied_to_note.hex()])
}
guard let wrapped_event = NostrEvent(
content: contents,
keypair: keypair.to_keypair(),
kind: NostrKind.draft.rawValue,
tags: tags
) else { return nil }
return wrapped_event
}
/// A function that unwraps and decrypts a NIP-37 draft
/// - Parameters:
/// - note: NIP-37 note to be unwrapped
/// - keypair: The keys to use for decrypting
/// - Returns: The unwrapped note, if it can be decrypted/unwrapped.
static func unwrap(note: NdbNote, keypair: FullKeypair) throws -> NdbNote? {
let wrapped_note = note
guard wrapped_note.known_kind == .draft else { return nil }
guard let draft_event_json = try? NIP44v2Encryption.decrypt(
payload: wrapped_note.content,
privateKeyA: keypair.privkey,
publicKeyB: keypair.pubkey
) else { return nil }
return NdbNote.owned_from_json(json: draft_event_json)
}
enum NIP37DraftEventError: Error {
case invalid_keypair
case encoding_error
}
}
-357
View File
@@ -1,357 +0,0 @@
//
// NIP44.swift
// damus
//
// Based on NIP44v2Encrypting.swift created by Terry Yiu on 3/16/24, from https://github.com/nostr-sdk/nostr-sdk-ios, which is MIT licensed.
//
// MIT License
//
// Copyright (c) 2023 Nostr SDK
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
// Adapted by Daniel DAquino on 2025-02-10.
//
import Foundation
import CryptoKit
import CryptoSwift
import secp256k1
struct NIP44v2Encryption {
/// Produces a `String` containing `plaintext` that has been encrypted using the `privateKey` of user A and the `publicKey` of user B.
///
/// The result is non-deterministic because a cryptographically secure pseudorandom generated nonce is used each time,
/// but can be decrypted deterministically with a call to ``NIP44v2Encryption/decrypt(payload:privateKeyA:publicKeyB:)``,
/// where user A and user B are interchangeable.
///
/// This function can `throw` an error from ``EncryptionError`` if it fails to encrypt the plaintext.
///
/// - Parameters:
/// - plaintext: The plaintext to encrypt.
/// - privateKeyA: The private key of user A.
/// - publicKeyB: The public key of user B.
/// - Returns: The encrypted ciphertext.
static func encrypt(plaintext: String, privateKeyA: Privkey, publicKeyB: Pubkey) throws -> String {
let conversationKey = try conversationKey(privateKeyA: privateKeyA, publicKeyB: publicKeyB)
return try encrypt(plaintext: plaintext, conversationKey: conversationKey)
}
/// Produces a `String` containing `payload` that has been decrypted using the `privateKey` of user A and the `publicKey` of user B,
/// and the result is identical to if the `privateKey` of user B and `publicKey` of user A were used to decrypt `payload` instead.
///
/// Any ciphertext returned from the call to ``NIP44v2Encryption/encrypt(plaintext:privateKeyA:publicKeyB:)``
/// can be decrypted, where user A and B are interchangeable.
///
/// This function can `throw` an error from ``EncryptionError`` if it fails to decrypt the payload.
///
/// - Parameters:
/// - payload: The payload to decrypt.
/// - privateKeyA: The private key of user A.
/// - publicKeyB: The public key of user B.
/// - Returns: The decrypted plaintext message.
static func decrypt(payload: String, privateKeyA: Privkey, publicKeyB: Pubkey) throws -> String {
let conversationKey = try conversationKey(privateKeyA: privateKeyA, publicKeyB: publicKeyB)
return try decrypt(payload: payload, conversationKey: conversationKey)
}
/// Calculates length of the padded byte array.
static func calculatePaddedLength(_ unpaddedLength: Int) throws -> Int {
guard unpaddedLength > 0 else {
throw EncryptionError.unpaddedLengthInvalid(unpaddedLength)
}
if unpaddedLength <= 32 {
return 32
}
let nextPower = 1 << (Int(floor(log2(Double(unpaddedLength) - 1))) + 1)
let chunk: Int
if nextPower <= 256 {
chunk = 32
} else {
chunk = nextPower / 8
}
return chunk * (Int(floor((Double(unpaddedLength) - 1) / Double(chunk))) + 1)
}
/// Converts unpadded plaintext to padded bytes.
static func pad(_ plaintext: String) throws -> Data {
guard let unpadded = plaintext.data(using: .utf8) else {
throw EncryptionError.utf8EncodingFailed
}
let unpaddedLength = unpadded.count
guard 1...65535 ~= unpaddedLength else {
throw EncryptionError.plaintextLengthInvalid(unpaddedLength)
}
var prefix = Data(count: 2)
prefix.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) in
ptr.storeBytes(of: UInt16(unpaddedLength).bigEndian, as: UInt16.self)
}
let suffix = Data(count: try calculatePaddedLength(unpaddedLength) - unpaddedLength)
return prefix + unpadded + suffix
}
/// Converts padded bytes to unpadded plaintext.
static func unpad(_ padded: Data) throws -> String {
guard padded.count >= 2 else {
throw EncryptionError.paddingInvalid
}
let unpaddedLength = (Int(padded[0]) << 8) | Int(padded[1])
guard 2+unpaddedLength <= padded.count else {
throw EncryptionError.paddingInvalid
}
let unpadded = toBytes(from: padded)[2..<2+unpaddedLength]
let paddedLength = try calculatePaddedLength(unpaddedLength)
guard unpaddedLength > 0,
unpadded.count == unpaddedLength,
padded.count == 2 + paddedLength,
let result = String(data: Data(unpadded), encoding: .utf8) else {
throw EncryptionError.paddingInvalid
}
return result
}
static func decodePayload(_ payload: String) throws -> DecodedPayload {
let payloadLength = payload.count
guard payloadLength > 0 && payload.first != "#" else {
throw EncryptionError.unknownVersion()
}
guard 132...87472 ~= payloadLength else {
throw EncryptionError.payloadSizeInvalid(payloadLength)
}
guard let data = Data(base64Encoded: payload) else {
throw EncryptionError.base64EncodingFailed
}
let dataLength = data.count
guard 99...65603 ~= dataLength else {
throw EncryptionError.dataSizeInvalid(dataLength)
}
guard let version = data.first else {
throw EncryptionError.unknownVersion()
}
guard version == 2 else {
throw EncryptionError.unknownVersion(Int(version))
}
let nonce = data[data.index(data.startIndex, offsetBy: 1)..<data.index(data.startIndex, offsetBy: 33)]
let ciphertext = data[data.index(data.startIndex, offsetBy: 33)..<data.index(data.startIndex, offsetBy: dataLength - 32)]
let mac = data[data.index(data.startIndex, offsetBy: dataLength - 32)..<data.index(data.startIndex, offsetBy: dataLength)]
return DecodedPayload(nonce: nonce, ciphertext: ciphertext, mac: mac)
}
static func hmacAad(key: Data, message: Data, aad: Data) throws -> Data {
guard aad.count == 32 else {
throw EncryptionError.aadLengthInvalid(aad.count)
}
let combined = aad + message
return Data(CryptoKit.HMAC<CryptoKit.SHA256>.authenticationCode(for: combined, using: SymmetricKey(data: key)))
}
static func toBytes(from data: Data) -> [UInt8] {
data.withUnsafeBytes { bytesPointer in Array(bytesPointer) }
}
static func preparePublicKeyBytes(from publicKey: Pubkey) throws -> [UInt8] {
let publicKeyBytes = publicKey.bytes
let prefix = Data([2])
let prefixBytes = toBytes(from: prefix)
return prefixBytes + publicKeyBytes
}
static func parsePublicKey(from bytes: [UInt8]) throws -> secp256k1_pubkey {
var publicKey = secp256k1_pubkey()
guard secp256k1_ec_pubkey_parse(secp256k1.Context.raw, &publicKey, bytes, bytes.count) == 1 else {
throw EncryptionError.publicKeyInvalid
}
return publicKey
}
static func computeSharedSecret(using publicKey: secp256k1_pubkey, and privateKeyBytes: [UInt8]) throws -> [UInt8] {
var sharedSecret = [UInt8](repeating: 0, count: 32)
var mutablePublicKey = publicKey
// Multiplication of point B by scalar a (a B), defined in [BIP340](https://github.com/bitcoin/bips/blob/e918b50731397872ad2922a1b08a5a4cd1d6d546/bip-0340.mediawiki).
// The operation produces a shared point, and we encode the shared point's 32-byte x coordinate, using method bytes(P) from BIP340.
// Private and public keys must be validated as per BIP340: pubkey must be a valid, on-curve point, and private key must be a scalar in range [1, secp256k1_order - 1]
guard secp256k1_ecdh(secp256k1.Context.raw, &sharedSecret, &mutablePublicKey, privateKeyBytes, { (output, x32, _, _) in
memcpy(output, x32, 32)
return 1
}, nil) != 0 else {
throw EncryptionError.sharedSecretComputationFailed
}
return sharedSecret
}
/// Calculates long-term key between users A and B.
/// The conversation key of A's private key and B's public key is equal to the conversation key of B's private key and A's public key.
static func conversationKey(privateKeyA: Privkey, publicKeyB: Pubkey) throws -> ContiguousBytes {
let privateKeyABytes = privateKeyA.bytes
let publicKeyBBytes = try preparePublicKeyBytes(from: publicKeyB)
let parsedPublicKeyB = try parsePublicKey(from: publicKeyBBytes)
let sharedSecret = try computeSharedSecret(using: parsedPublicKeyB, and: privateKeyABytes)
return CryptoKit.HKDF<CryptoKit.SHA256>.extract(inputKeyMaterial: SymmetricKey(data: sharedSecret), salt: Data("nip44-v2".utf8))
}
/// Calculates unique per-message key.
static func messageKeys(conversationKey: ContiguousBytes, nonce: Data) throws -> MessageKeys {
let conversationKeyByteCount = conversationKey.bytes.count
guard conversationKeyByteCount == 32 else {
throw EncryptionError.conversationKeyLengthInvalid(conversationKeyByteCount)
}
guard nonce.count == 32 else {
throw EncryptionError.nonceLengthInvalid(nonce.count)
}
let keys = CryptoKit.HKDF<CryptoKit.SHA256>.expand(pseudoRandomKey: conversationKey, info: nonce, outputByteCount: 76)
let keysBytes = keys.bytes
let chaChaKey = Data(keysBytes[0..<32])
let chaChaNonce = Data(keysBytes[32..<44])
let hmacKey = Data(keysBytes[44..<76])
return MessageKeys(chaChaKey: chaChaKey, chaChaNonce: chaChaNonce, hmacKey: hmacKey)
}
static func encrypt(plaintext: String, conversationKey: ContiguousBytes, nonce: Data? = nil) throws -> String {
let nonceData: Data
if let nonce {
nonceData = nonce
} else {
// Fetches randomness from CSPRNG.
nonceData = Data.secureRandomBytes(count: 32)
}
let messageKeys = try messageKeys(conversationKey: conversationKey, nonce: nonceData)
let padded = try pad(plaintext)
let paddedBytes = toBytes(from: padded)
let chaChaKey = toBytes(from: messageKeys.chaChaKey)
let chaChaNonce = toBytes(from: messageKeys.chaChaNonce)
let ciphertext = try ChaCha20(key: chaChaKey, iv: chaChaNonce).encrypt(paddedBytes)
let ciphertextData = Data(ciphertext)
let mac = try hmacAad(key: messageKeys.hmacKey, message: ciphertextData, aad: nonceData)
let data = Data([2]) + nonceData + ciphertextData + mac
return data.base64EncodedString()
}
static func decrypt(payload: String, conversationKey: ContiguousBytes) throws -> String {
let decodedPayload = try decodePayload(payload)
let nonce = decodedPayload.nonce
let ciphertext = decodedPayload.ciphertext
let ciphertextBytes = toBytes(from: ciphertext)
let mac = decodedPayload.mac
let messageKeys = try messageKeys(conversationKey: conversationKey, nonce: nonce)
let calculatedMac = try hmacAad(key: messageKeys.hmacKey, message: ciphertext, aad: nonce)
guard calculatedMac == mac else {
throw EncryptionError.macInvalid
}
let chaChaNonce = toBytes(from: messageKeys.chaChaNonce)
let chaChaKey = toBytes(from: messageKeys.chaChaKey)
let paddedPlaintext = try ChaCha20(key: chaChaKey, iv: chaChaNonce).decrypt(ciphertextBytes)
let paddedPlaintextData = Data(paddedPlaintext.bytes)
return try unpad(paddedPlaintextData)
}
}
// MARK: - Helper structures and extensions
extension Data {
/// Random data of a given size, from CSPRNG
/// - Parameter count: The size of the data, in bytes
/// - Returns: Bytes randomly generated from CSPRNG
static func secureRandomBytes(count: Int) -> Data {
var bytes = [Int8](repeating: 0, count: count)
guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else {
fatalError("can't copy secure random data")
}
return Data(bytes: bytes, count: count)
}
}
extension NIP44v2Encryption {
struct DecodedPayload {
let nonce: Data
let ciphertext: Data
let mac: Data
}
struct MessageKeys {
let chaChaKey: Data
let chaChaNonce: Data
let hmacKey: Data
}
public enum EncryptionError: Error {
case aadLengthInvalid(Int)
case base64EncodingFailed
case chaCha20DecryptionFailed
case chaCha20EncryptionFailed
case conversationKeyLengthInvalid(Int)
case dataSizeInvalid(Int)
case macInvalid
case nonceLengthInvalid(Int)
case paddingInvalid
case payloadSizeInvalid(Int)
case plaintextLengthInvalid(Int)
case privateKeyInvalid
case publicKeyInvalid
case sharedSecretComputationFailed
case unknownVersion(Int? = nil)
case unpaddedLengthInvalid(Int)
case utf8EncodingFailed
}
}
+3 -4
View File
@@ -31,8 +31,7 @@ class ProfileRecord {
}
guard let profile = data.profile,
let addr = (profile.lud16 ?? profile.lud06)?.trimmingCharacters(in: .whitespaces)
else {
let addr = profile.lud16 ?? profile.lud06 else {
return nil;
}
@@ -58,7 +57,7 @@ extension NdbProfile {
}
static func displayName(profile: Profile?, pubkey: Pubkey) -> DisplayName {
return DisplayName(name: profile?.name, display_name: profile?.display_name, pubkey: pubkey)
return parse_display_name(profile: profile, pubkey: pubkey)
}
var damus_donation: Int? {
@@ -302,7 +301,7 @@ class Profile: Codable {
*/
func make_test_profile() -> Profile {
return Profile(name: "jb55", display_name: "Will", about: "Its a me", picture: "https://cdn.jb55.com/img/red-me.jpg", banner: "https://pbs.twimg.com/profile_banners/9918032/1531711830/600x200", website: "jb55.com", lud06: nil, lud16: "jb55@jb55.com", nip05: "jb55@jb55.com", damus_donation: 1)
return Profile(name: "jb55", display_name: "Will", about: "Its a me", picture: "https://cdn.jb55.com/img/red-me.jpg", banner: "https://pbs.twimg.com/profile_banners/9918032/1531711830/600x200", website: "jb55.com", lud06: "jb55@jb55.com", lud16: nil, nip05: "jb55@jb55.com", damus_donation: 1)
}
func make_ln_url(_ str: String?) -> URL? {
+1 -1
View File
@@ -68,7 +68,7 @@ func make_private_zap_request_event(identity: FullKeypair, enc_key: FullKeypair,
guard let note = NostrEvent(content: message, keypair: identity.to_keypair(), kind: 9733, tags: tags),
let note_json = encode_json(note),
let enc = NIP04.encrypt_message(message: note_json, privkey: enc_key.privkey, to_pk: target.pubkey, encoding: .bech32)
let enc = encrypt_message(message: note_json, privkey: enc_key.privkey, to_pk: target.pubkey, encoding: .bech32)
else {
return nil
}
-1
View File
@@ -19,7 +19,6 @@ enum NostrKind: UInt32, Codable {
case chat = 42
case mute_list = 10000
case list_deprecated = 30000
case draft = 31234
case longform = 30023
case zap = 9735
case zap_request = 9734
+1 -1
View File
@@ -45,7 +45,7 @@ enum NostrResponse {
static func owned_from_json(json: String) -> NostrResponse? {
return json.withCString{ cstr in
let bufsize: Int = max(Int(Double(json.utf8.count) * 8.0), Int(getpagesize()))
let bufsize: Int = max(Int(Double(json.utf8.count) * 4.0), Int(getpagesize()))
let data = malloc(bufsize)
if data == nil {
+15 -7
View File
@@ -7,11 +7,19 @@
import Foundation
extension QueueableNotify<LossyLocalNotification> {
/// A shared singleton for opening local and push user notifications
///
/// ## Implementation notes
///
/// - The queue can only hold one element. This is done because if the user hypothetically opened 10 push notifications and there was a lag, we wouldn't want the app to suddenly open 10 different things.
static let shared = QueueableNotify(maxQueueItems: 1)
struct LocalNotificationNotify: Notify {
typealias Payload = LossyLocalNotification
var payload: Payload
}
extension NotifyHandler {
static var local_notification: NotifyHandler<LocalNotificationNotify> {
.init()
}
}
extension Notifications {
static func local_notification(_ payload: LossyLocalNotification) -> Notifications<LocalNotificationNotify> {
.init(.init(payload: payload))
}
}
-90
View File
@@ -1,90 +0,0 @@
//
// QueueableNotify.swift
// damus
//
// Created by Daniel DAquino on 2025-02-14.
//
/// This notifies another object about some payload,
/// with automatic "queueing" of messages if there are no listeners.
///
/// When used as a singleton, this can be used to easily send notifications to be handled at the app-level.
///
/// This serves the same purpose as `Notify`, except this implements the queueing of messages,
/// which means that messages can be handled even if the listener is not instantiated yet.
///
/// **Example:** The app delegate can send some events that need handling from `ContentView` but some can occur before `ContentView` is even instantiated.
///
///
/// ## Usage notes
///
/// - This code was mainly written to have one listener at a time. Have more than one listener may be possible, but this class has not been tested/optimized for that purpose.
///
///
/// ## Implementation notes
///
/// - This makes heavy use of `AsyncStream` and continuations, because that allows complexities here to be handled elegantly with a simple "for-in" loop
/// - Without this, it would take a couple of callbacks and manual handling of queued items to achieve the same effect
/// - Modeled as an `actor` for extra thread-safety
actor QueueableNotify<T: Sendable> {
/// The continuation, which allows us to publish new items to the listener
/// If `nil`, that means there is no listeners to the stream, which is used for determining whether to queue new incoming items.
private var continuation: AsyncStream<T>.Continuation?
/// Holds queue items
private var queue: [T] = []
/// The maximum amount of items allowed in the queue. Older items will be discarded from the queue after it is full
var maxQueueItems: Int
/// Initializes the object
/// - Parameter maxQueueItems: The maximum amount of items allowed in the queue. Older items will be discarded from the queue after it is full
init(maxQueueItems: Int) {
self.maxQueueItems = maxQueueItems
}
/// The async stream, used for listening for notifications
///
/// This will first stream the queued "inbox" items that the listener may have missed, and then it will do a real-time stream of new items as they come in.
///
/// Example:
///
/// ```swift
/// for await notification in queueableNotify.stream {
/// // Do something with the notification
/// }
/// ```
var stream: AsyncStream<T> {
return AsyncStream { continuation in
// Stream queued "inbox" items that the listener may have missed
for item in queue {
continuation.yield(item)
}
// Clean up if the stream closes
continuation.onTermination = { continuation in
Task { await self.cleanup() }
}
// Point to this stream, so that it can receive new updates
self.continuation = continuation
}
}
/// Cleans up after a stream is closed by the listener
private func cleanup() {
self.continuation = nil // This will cause new items to be queued for when another listener is attached
}
/// Adds a new notification item to be handled by a listener.
///
/// This will automatically stream the new item to the listener, or queue the item if no one is listening
func add(item: T) {
while queue.count >= maxQueueItems { queue.removeFirst() } // Ensures queue stays within the desired size
guard let continuation else {
// No one is listening, queue it (send it to an inbox for later handling)
queue.append(item)
return
}
// Send directly to the active listener stream
continuation.yield(item)
}
}
-8
View File
@@ -7,14 +7,9 @@
import Foundation
/// General app-wide constants
///
/// ## Implementation notes:
/// - Force unwrapping in this class is generally ok, because the contents are static, and so we can easily provide guarantees that they will not crash the app.
class Constants {
//static let EXAMPLE_DEMOS: DamusState = .empty
static let DAMUS_APP_GROUP_IDENTIFIER: String = "group.com.damus"
static let IMAGE_CACHE_DIRNAME: String = "ImageCache"
static let MAIN_APP_BUNDLE_IDENTIFIER: String = "com.jb55.damus2"
static let NOTIFICATION_EXTENSION_BUNDLE_IDENTIFIER: String = "com.jb55.damus2.DamusNotificationService"
@@ -37,9 +32,6 @@ class Constants {
static let DAMUS_WEBSITE_STAGING_URL: URL = URL(string: "https://staging.damus.io")!
static let DAMUS_WEBSITE_PRODUCTION_URL: URL = URL(string: "https://damus.io")!
// MARK: Damus Company Info
static let SUPPORT_PUBKEY: Pubkey = Pubkey(hex: "3efdaebb1d8923ebd99c9e7ace3b4194ab45512e2be79c1b7d68d9243e0d2681")!
// MARK: General constants
static let GIF_IMAGE_TYPE: String = "com.compuserve.gif"
}
+7 -32
View File
@@ -10,15 +10,7 @@ import Foundation
enum DisplayName: Equatable {
case both(username: String, displayName: String)
case one(String)
init (profile: Profile?, pubkey: Pubkey) {
self = parse_display_name(name: profile?.name, display_name: profile?.display_name, pubkey: pubkey)
}
init (name: String?, display_name: String?, pubkey: Pubkey) {
self = parse_display_name(name: name, display_name: display_name, pubkey: pubkey)
}
var displayName: String {
switch self {
case .one(let one):
@@ -36,37 +28,20 @@ enum DisplayName: Equatable {
return username
}
}
func nameComponents() -> PersonNameComponents {
var components = PersonNameComponents()
switch self {
case .one(let one):
components.nickname = one
return components
case .both(username: let username, displayName: let displayName):
components.nickname = username
let names = displayName.split(separator: " ")
if let name = names.first {
components.givenName = String(name)
components.familyName = names.dropFirst().joined(separator: " ")
}
return components
}
}
}
func parse_display_name(name: String?, display_name: String?, pubkey: Pubkey) -> DisplayName {
func parse_display_name(profile: Profile?, pubkey: Pubkey) -> DisplayName {
if pubkey == ANON_PUBKEY {
return .one(NSLocalizedString("Anonymous", comment: "Placeholder display name of anonymous user."))
}
if name == nil && display_name == nil {
guard let profile else {
return .one(abbrev_bech32_pubkey(pubkey: pubkey))
}
let name = name?.isEmpty == false ? name : nil
let disp_name = display_name?.isEmpty == false ? display_name : nil
let name = profile.name?.isEmpty == false ? profile.name : nil
let disp_name = profile.display_name?.isEmpty == false ? profile.display_name : nil
if let name, let disp_name, name != disp_name {
return .both(username: name, displayName: disp_name)
-15
View File
@@ -1,15 +0,0 @@
//
// ExtraFonts.swift
// damus
//
// Created by Daniel DAquino on 2025-03-13.
//
import SwiftUI
extension Font {
// Note: When changing the font size accessibility setting, these styles only update after an app restart. It's a current limitation of this.
static let veryLargeTitle: Font = .system(size: UIFont.preferredFont(forTextStyle: .largeTitle).pointSize * 1.5, weight: .bold) // Makes a bigger title while allowing for iOS dynamic font sizing to take effect
static let veryVeryLargeTitle: Font = .system(size: UIFont.preferredFont(forTextStyle: .largeTitle).pointSize * 2.1, weight: .bold) // Makes a bigger title while allowing for iOS dynamic font sizing to take effect
}
-11
View File
@@ -21,17 +21,6 @@ let ANON_PUBKEY = Pubkey(Data([
struct FullKeypair: Equatable {
let pubkey: Pubkey
let privkey: Privkey
init(pubkey: Pubkey, privkey: Privkey) {
self.pubkey = pubkey
self.privkey = privkey
}
init?(privkey: Privkey) {
self.privkey = privkey
guard let pubkey = privkey_to_pubkey_raw(sec: privkey.bytes) else { return nil }
self.pubkey = pubkey
}
func to_keypair() -> Keypair {
return Keypair(pubkey: pubkey, privkey: privkey)
-3
View File
@@ -14,9 +14,6 @@ enum LogCategory: String {
case render
case storage
case networking
case timeline
/// Logs related to Nostr Wallet Connect components
case nwc
case push_notifications
case damus_purple
case image_uploading
+1 -7
View File
@@ -32,7 +32,6 @@ enum Route: Hashable {
case DeveloperSettings(settings: UserSettingsStore)
case FirstAidSettings(settings: UserSettingsStore)
case Thread(thread: ThreadModel)
case LoadableNostrEvent(note_reference: LoadableNostrEventViewModel.NoteReference)
case Reposts(reposts: EventsModel)
case QuoteReposts(quotes: EventsModel)
case Reactions(reactions: EventsModel)
@@ -97,8 +96,6 @@ enum Route: Hashable {
case .Thread(let thread):
ChatroomThreadView(damus: damusState, thread: thread)
//ThreadView(state: damusState, thread: thread)
case .LoadableNostrEvent(let note_reference):
LoadableNostrEventView(state: damusState, note_reference: note_reference)
case .Reposts(let reposts):
RepostsView(damus_state: damusState, model: reposts)
case .QuoteReposts(let quote_reposts):
@@ -189,10 +186,7 @@ enum Route: Hashable {
hasher.combine("firstAidSettings")
case .Thread(let threadModel):
hasher.combine("thread")
hasher.combine(threadModel.original_event.id)
case .LoadableNostrEvent(note_reference: let note_reference):
hasher.combine("loadable_nostr_event")
hasher.combine(note_reference)
hasher.combine(threadModel.event.id)
case .Reposts(let reposts):
hasher.combine("reposts")
hasher.combine(reposts.target)
-30
View File
@@ -1,30 +0,0 @@
//
// Undistractor.swift
// damus
//
// Created by Daniel DAquino on 2025-02-19.
//
/// Keeping the minds of developers safe from the occupational hazard of social media distractions when testing Damus since 2025
struct Undistractor {
static func makeGibberish(text: String) -> String {
let lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
let uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var transformedText = ""
for char in text {
if lowercaseLetters.contains(char) {
if let randomLetter = lowercaseLetters.randomElement() {
transformedText.append(randomLetter)
}
} else if uppercaseLetters.contains(char) {
if let randomLetter = uppercaseLetters.randomElement() {
transformedText.append(randomLetter)
}
} else {
transformedText.append(char)
}
}
return transformedText
}
}
+118
View File
@@ -0,0 +1,118 @@
//
// WalletConnect+.swift
// damus
//
// Created by Daniel DAquino on 2023-11-27.
//
import Foundation
func make_wallet_pay_invoice_request(invoice: String) -> WalletRequest<PayInvoiceRequest> {
let data = PayInvoiceRequest(invoice: invoice)
return WalletRequest(method: "pay_invoice", params: data)
}
func make_wallet_balance_request() -> WalletRequest<EmptyRequest> {
return WalletRequest(method: "get_balance", params: nil)
}
struct EmptyRequest: Codable {
}
struct PayInvoiceRequest: Codable {
let invoice: String
}
func make_wallet_connect_request<T>(req: WalletRequest<T>, to_pk: Pubkey, keypair: FullKeypair) -> NostrEvent? {
let tags = [to_pk.tag]
let created_at = UInt32(Date().timeIntervalSince1970)
guard let content = encode_json(req) else {
return nil
}
return create_encrypted_event(content, to_pk: to_pk, tags: tags, keypair: keypair, created_at: created_at, kind: 23194)
}
func subscribe_to_nwc(url: WalletConnectURL, pool: RelayPool) {
var filter = NostrFilter(kinds: [.nwc_response])
filter.authors = [url.pubkey]
filter.limit = 0
let sub = NostrSubscribe(filters: [filter], sub_id: "nwc")
pool.send(.subscribe(sub), to: [url.relay], skip_ephemeral: false)
}
@discardableResult
func nwc_pay(url: WalletConnectURL, pool: RelayPool, post: PostBox, invoice: String, delay: TimeInterval? = 5.0, on_flush: OnFlush? = nil) -> NostrEvent? {
let req = make_wallet_pay_invoice_request(invoice: invoice)
guard let ev = make_wallet_connect_request(req: req, to_pk: url.pubkey, keypair: url.keypair) else {
return nil
}
try? pool.add_relay(.nwc(url: url.relay))
subscribe_to_nwc(url: url, pool: pool)
post.send(ev, to: [url.relay], skip_ephemeral: false, delay: delay, on_flush: on_flush)
return ev
}
func nwc_success(state: DamusState, resp: FullWalletResponse) {
// find the pending zap and mark it as pending-confirmed
for kv in state.zaps.our_zaps {
let zaps = kv.value
for zap in zaps {
guard case .pending(let pzap) = zap,
case .nwc(let nwc_state) = pzap.state,
case .postbox_pending(let nwc_req) = nwc_state.state,
nwc_req.id == resp.req_id
else {
continue
}
if nwc_state.update_state(state: .confirmed) {
// notify the zaps model of an update so it can mark them as paid
state.events.get_cache_data(NoteId(pzap.target.id)).zaps_model.objectWillChange.send()
print("NWC success confirmed")
}
return
}
}
}
func send_donation_zap(pool: RelayPool, postbox: PostBox, nwc: WalletConnectURL, percent: Int, base_msats: Int64) async {
let percent_f = Double(percent) / 100.0
let donations_msats = Int64(percent_f * Double(base_msats))
let payreq = LNUrlPayRequest(allowsNostr: true, commentAllowed: nil, nostrPubkey: "", callback: "https://sendsats.lol/@damus")
guard let invoice = await fetch_zap_invoice(payreq, zapreq: nil, msats: donations_msats, zap_type: .non_zap, comment: nil) else {
// we failed... oh well. no donation for us.
print("damus-donation failed to fetch invoice")
return
}
print("damus-donation donating...")
nwc_pay(url: nwc, pool: pool, post: postbox, invoice: invoice, delay: nil)
}
func nwc_error(zapcache: Zaps, evcache: EventCache, resp: FullWalletResponse) {
// find a pending zap with the nwc request id associated with this response and remove it
for kv in zapcache.our_zaps {
let zaps = kv.value
for zap in zaps {
guard case .pending(let pzap) = zap,
case .nwc(let nwc_state) = pzap.state,
case .postbox_pending(let req) = nwc_state.state,
req.id == resp.req_id
else {
continue
}
// remove the pending zap if there was an error
let reqid = ZapRequestId(from_pending: pzap)
remove_zap(reqid: reqid, zapcache: zapcache, evcache: evcache)
return
}
}
}
+155
View File
@@ -0,0 +1,155 @@
//
// WalletConnect.swift
// damus
//
// Created by William Casarin on 2023-03-22.
//
import Foundation
struct WalletConnectURL: Equatable {
static func == (lhs: WalletConnectURL, rhs: WalletConnectURL) -> Bool {
return lhs.keypair == rhs.keypair &&
lhs.pubkey == rhs.pubkey &&
lhs.relay == rhs.relay
}
let relay: RelayURL
let keypair: FullKeypair
let pubkey: Pubkey
let lud16: String?
func to_url() -> URL {
var urlComponents = URLComponents()
urlComponents.scheme = "nostrwalletconnect"
urlComponents.host = pubkey.hex()
urlComponents.queryItems = [
URLQueryItem(name: "relay", value: relay.absoluteString),
URLQueryItem(name: "secret", value: keypair.privkey.hex())
]
if let lud16 {
urlComponents.queryItems?.append(URLQueryItem(name: "lud16", value: lud16))
}
return urlComponents.url!
}
init?(str: String) {
guard let components = URLComponents(string: str),
components.scheme == "nostrwalletconnect" || components.scheme == "nostr+walletconnect",
// The line below provides flexibility for both `nostrwalletconnect://` (non-compliant, but commonly used) and `nostrwalletconnect:` (NIP-47 compliant) formats
let encoded_pubkey = components.path == "" ? components.host : components.path,
let pubkey = hex_decode_pubkey(encoded_pubkey),
let items = components.queryItems,
let relay = items.first(where: { qi in qi.name == "relay" })?.value,
let relay_url = RelayURL(relay),
let secret = items.first(where: { qi in qi.name == "secret" })?.value,
secret.utf8.count == 64,
let decoded = hex_decode(secret)
else {
return nil
}
let privkey = Privkey(Data(decoded))
guard let our_pk = privkey_to_pubkey(privkey: privkey) else { return nil }
let lud16 = items.first(where: { qi in qi.name == "lud16" })?.value
let keypair = FullKeypair(pubkey: our_pk, privkey: privkey)
self = WalletConnectURL(pubkey: pubkey, relay: relay_url, keypair: keypair, lud16: lud16)
}
init(pubkey: Pubkey, relay: RelayURL, keypair: FullKeypair, lud16: String?) {
self.pubkey = pubkey
self.relay = relay
self.keypair = keypair
self.lud16 = lud16
}
}
struct WalletRequest<T: Codable>: Codable {
let method: String
let params: T?
}
struct WalletResponseErr: Codable {
let code: String?
let message: String?
}
struct PayInvoiceResponse: Decodable {
let preimage: String
}
enum WalletResponseResultType: String {
case pay_invoice
}
enum WalletResponseResult {
case pay_invoice(PayInvoiceResponse)
}
struct FullWalletResponse {
let req_id: NoteId
let response: WalletResponse
init?(from: NostrEvent, nwc: WalletConnectURL) async {
guard let note_id = from.referenced_ids.first else {
return nil
}
self.req_id = note_id
let ares = Task {
guard let json = decrypt_dm(nwc.keypair.privkey, pubkey: nwc.pubkey, content: from.content, encoding: .base64),
let resp: WalletResponse = decode_json(json)
else {
let resp: WalletResponse? = nil
return resp
}
return resp
}
guard let res = await ares.value else {
return nil
}
self.response = res
}
}
struct WalletResponse: Decodable {
let result_type: WalletResponseResultType
let error: WalletResponseErr?
let result: WalletResponseResult?
private enum CodingKeys: CodingKey {
case result_type, error, result
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let result_type_str = try container.decode(String.self, forKey: .result_type)
guard let result_type = WalletResponseResultType(rawValue: result_type_str) else {
throw DecodingError.typeMismatch(WalletResponseResultType.self, .init(codingPath: decoder.codingPath, debugDescription: "result_type \(result_type_str) is unknown"))
}
self.result_type = result_type
self.error = try container.decodeIfPresent(WalletResponseErr.self, forKey: .error)
guard self.error == nil else {
self.result = nil
return
}
switch result_type {
case .pay_invoice:
let res = try container.decode(PayInvoiceResponse.self, forKey: .result)
self.result = .pay_invoice(res)
}
}
}
-137
View File
@@ -1,137 +0,0 @@
//
// Request.swift
// damus
//
// Created by Daniel DAquino on 2025-03-10.
//
import Foundation
extension WalletConnect {
/// Models a request to an NWC wallet provider
enum Request: Codable {
/// Pay an invoice
case payInvoice(
/// bolt-11 invoice string
invoice: String
)
/// Get the current wallet balance
case getBalance
/// Get the current wallet transaction history
case getTransactionList(
/// Starting timestamp in seconds since epoch (inclusive), optional.
from: UInt64?,
/// Ending timestamp in seconds since epoch (inclusive), optional.
until: UInt64?,
/// Maximum number of invoices to return, optional.
limit: Int?,
/// Offset of the first invoice to return, optional.
offset: Int?,
/// Include unpaid invoices, optional, default false.
unpaid: Bool?,
/// "incoming" for invoices, "outgoing" for payments, undefined for both.
type: String?
)
// MARK: - Interface
/// Converts the NWC request into a raw Nostr event to be sent in the network
///
/// - Parameters:
/// - to_pk: The destination pubkey (used for encryption)
/// - keypair: The requester's pubkey (used for encryption and signing)
/// - Returns: The NWC request in a raw Nostr Event format, or nil if it cannot be encoded
func to_nostr_event(to_pk: Pubkey, keypair: FullKeypair) -> NostrEvent? {
let tags = [to_pk.tag]
let created_at = UInt32(Date().timeIntervalSince1970)
guard let content = encode_json(self) else {
return nil
}
return NIP04.create_encrypted_event(content, to_pk: to_pk, tags: tags, keypair: keypair, created_at: created_at, kind: NostrKind.nwc_request.rawValue)
}
// MARK: - Encoding and decoding
/// Keys for top-level JSON
private enum CodingKeys: String, CodingKey {
case method
case params
}
/// Keys for the JSON inside the "params" object
private enum ParamKeys: String, CodingKey {
case invoice
case from, until, limit, offset, unpaid, type
}
/// Constants for possible request "method" verbs
private enum Method: String {
case payInvoice = "pay_invoice"
case getBalance = "get_balance"
case listTransactions = "list_transactions"
}
/// Decodes a payload into this request structure
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let method = try container.decode(String.self, forKey: .method)
switch method {
case Method.payInvoice.rawValue:
let paramsContainer = try container.nestedContainer(keyedBy: ParamKeys.self, forKey: .params)
let invoice = try paramsContainer.decode(String.self, forKey: .invoice)
self = .payInvoice(invoice: invoice)
case Method.getBalance.rawValue:
// No params to decode
self = .getBalance
case Method.listTransactions.rawValue:
let paramsContainer = try container.nestedContainer(keyedBy: ParamKeys.self, forKey: .params)
let from = try paramsContainer.decodeIfPresent(UInt64.self, forKey: .from)
let until = try paramsContainer.decodeIfPresent(UInt64.self, forKey: .until)
let limit = try paramsContainer.decodeIfPresent(Int.self, forKey: .limit)
let offset = try paramsContainer.decodeIfPresent(Int.self, forKey: .offset)
let unpaid = try paramsContainer.decodeIfPresent(Bool.self, forKey: .unpaid)
let type = try paramsContainer.decodeIfPresent(String.self, forKey: .type)
self = .getTransactionList(from: from, until: until, limit: limit, offset: offset, unpaid: unpaid, type: type)
default:
throw DecodingError.dataCorruptedError(
forKey: .method,
in: container,
debugDescription: "Unknown wallet method \"\(method)\""
)
}
}
/// Encodes this request structure into a payload
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .payInvoice(let invoice):
try container.encode(Method.payInvoice.rawValue, forKey: .method)
var paramsContainer = container.nestedContainer(keyedBy: ParamKeys.self, forKey: .params)
try paramsContainer.encode(invoice, forKey: .invoice)
case .getBalance:
try container.encode(Method.getBalance.rawValue, forKey: .method)
// "params": null
try container.encodeNil(forKey: .params)
case .getTransactionList(let from, let until, let limit, let offset, let unpaid, let type):
try container.encode(Method.listTransactions.rawValue, forKey: .method)
var paramsContainer = container.nestedContainer(keyedBy: ParamKeys.self, forKey: .params)
try paramsContainer.encodeIfPresent(from, forKey: .from)
try paramsContainer.encodeIfPresent(until, forKey: .until)
try paramsContainer.encodeIfPresent(limit, forKey: .limit)
try paramsContainer.encodeIfPresent(offset, forKey: .offset)
try paramsContainer.encodeIfPresent(unpaid, forKey: .unpaid)
try paramsContainer.encodeIfPresent(type, forKey: .type)
}
}
}
}
-110
View File
@@ -1,110 +0,0 @@
//
// Response.swift
// damus
//
// Created by Daniel DAquino on 2025-03-10.
//
extension WalletConnect {
/// Models a response from the NWC provider
struct Response: Decodable {
let result_type: Response.Result.ResultType
let error: WalletResponseErr?
let result: Response.Result?
private enum CodingKeys: CodingKey {
case result_type, error, result
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let result_type_str = try container.decode(String.self, forKey: .result_type)
guard let result_type = Response.Result.ResultType(rawValue: result_type_str) else {
throw DecodingError.typeMismatch(Response.Result.ResultType.self, .init(codingPath: decoder.codingPath, debugDescription: "result_type \(result_type_str) is unknown"))
}
self.result_type = result_type
self.error = try container.decodeIfPresent(WalletResponseErr.self, forKey: .error)
guard self.error == nil else {
self.result = nil
return
}
switch result_type {
case .pay_invoice:
let res = try container.decode(Result.PayInvoiceResponse.self, forKey: .result)
self.result = .pay_invoice(res)
case .get_balance:
let res = try container.decode(Result.GetBalanceResponse.self, forKey: .result)
self.result = .get_balance(res)
case .list_transactions:
let res = try container.decode(Result.ListTransactionsResponse.self, forKey: .result)
self.result = .list_transactions(res)
}
}
}
struct FullWalletResponse {
let req_id: NoteId
let response: Response
init?(from: NostrEvent, nwc: WalletConnect.ConnectURL) async {
guard let note_id = from.referenced_ids.first else {
return nil
}
self.req_id = note_id
let ares = Task {
guard let json = decrypt_dm(nwc.keypair.privkey, pubkey: nwc.pubkey, content: from.content, encoding: .base64),
let resp: WalletConnect.Response = decode_json(json)
else {
let resp: WalletConnect.Response? = nil
return resp
}
return resp
}
guard let res = await ares.value else {
return nil
}
self.response = res
}
}
struct WalletResponseErr: Codable {
let code: String?
let message: String?
}
}
extension WalletConnect.Response {
/// The response data resulting from an NWC request
enum Result {
case pay_invoice(PayInvoiceResponse)
case get_balance(GetBalanceResponse)
case list_transactions(ListTransactionsResponse)
enum ResultType: String {
case pay_invoice
case get_balance
case list_transactions
}
struct PayInvoiceResponse: Decodable {
let preimage: String
}
struct GetBalanceResponse: Decodable {
let balance: Int64
}
struct ListTransactionsResponse: Decodable {
let transactions: [WalletConnect.Transaction]
}
}
}
@@ -1,170 +0,0 @@
//
// WalletConnect+.swift
// damus
//
// Created by Daniel DAquino on 2023-11-27.
//
import Foundation
// TODO: Eventually we should move these convenience functions into structured classes responsible for managing this type of functionality, such as `WalletModel`
extension WalletConnect {
/// Creates and sends a subscription to an NWC relay requesting NWC responses to be sent back.
///
/// Notes: This assumes there is already a listener somewhere else
///
/// - Parameters:
/// - url: The Nostr Wallet Connect URL containing connection info to the NWC wallet
/// - pool: The RelayPool to send the subscription request through
static func subscribe(url: WalletConnectURL, pool: RelayPool) {
var filter = NostrFilter(kinds: [.nwc_response])
filter.authors = [url.pubkey]
filter.limit = 0
let sub = NostrSubscribe(filters: [filter], sub_id: "nwc")
pool.send(.subscribe(sub), to: [url.relay], skip_ephemeral: false)
}
/// Sends out a request to pay an invoice to the NWC relay, and ensures that:
/// 1. the NWC relay is connected and we are listening to NWC events
/// 2. the NWC relay is connected and we are listening to NWC
///
/// Note: This does not return information about whether the payment is succesful or not. The actual confirmation is handled elsewhere around `HomeModel` and `WalletModel`
///
/// - Parameters:
/// - url: The NWC wallet connection URL
/// - pool: The relay pool to connect to
/// - post: The postbox to send events in
/// - delay: The delay before actually sending the request to the network _(this makes it possible to cancel a zap)_
/// - on_flush: A callback to call after the event has been flushed to the network
/// - Returns: The Nostr Event that was sent to the network, representing the request that was made
@discardableResult
static func pay(url: WalletConnectURL, pool: RelayPool, post: PostBox, invoice: String, delay: TimeInterval? = 5.0, on_flush: OnFlush? = nil) -> NostrEvent? {
let req = WalletConnect.Request.payInvoice(invoice: invoice)
guard let ev = req.to_nostr_event(to_pk: url.pubkey, keypair: url.keypair) else {
return nil
}
try? pool.add_relay(.nwc(url: url.relay)) // Ensure the NWC relay is connected
WalletConnect.subscribe(url: url, pool: pool) // Ensure we are listening to NWC updates from the relay
post.send(ev, to: [url.relay], skip_ephemeral: false, delay: delay, on_flush: on_flush)
return ev
}
/// Sends out a wallet balance request to the NWC relay, and ensures that:
/// 1. the NWC relay is connected and we are listening to NWC events
/// 2. the NWC relay is connected and we are listening to NWC
///
/// Note: This does not return the actual balance information. The actual balance is handled elsewhere around `HomeModel` and `WalletModel`
///
/// - Parameters:
/// - url: The NWC wallet connection URL
/// - pool: The relay pool to connect to
/// - post: The postbox to send events in
/// - delay: The delay before actually sending the request to the network
/// - on_flush: A callback to call after the event has been flushed to the network
/// - Returns: The Nostr Event that was sent to the network, representing the request that was made
@discardableResult
static func request_balance_information(url: WalletConnectURL, pool: RelayPool, post: PostBox, delay: TimeInterval? = 0.0, on_flush: OnFlush? = nil) -> NostrEvent? {
let req = WalletConnect.Request.getBalance
guard let ev = req.to_nostr_event(to_pk: url.pubkey, keypair: url.keypair) else {
return nil
}
try? pool.add_relay(.nwc(url: url.relay)) // Ensure the NWC relay is connected
WalletConnect.subscribe(url: url, pool: pool) // Ensure we are listening to NWC updates from the relay
post.send(ev, to: [url.relay], skip_ephemeral: false, delay: delay, on_flush: on_flush)
return ev
}
/// Sends out a wallet transaction list request to the NWC relay, and ensures that:
/// 1. the NWC relay is connected and we are listening to NWC events
/// 2. the NWC relay is connected and we are listening to NWC
///
/// Note: This does not return the actual transaction list. The actual transaction list is handled elsewhere around `HomeModel` and `WalletModel`
///
/// - Parameters:
/// - url: The NWC wallet connection URL
/// - pool: The relay pool to connect to
/// - post: The postbox to send events in
/// - delay: The delay before actually sending the request to the network
/// - on_flush: A callback to call after the event has been flushed to the network
/// - Returns: The Nostr Event that was sent to the network, representing the request that was made
@discardableResult
static func request_transaction_list(url: WalletConnectURL, pool: RelayPool, post: PostBox, delay: TimeInterval? = 0.0, on_flush: OnFlush? = nil) -> NostrEvent? {
let req = WalletConnect.Request.getTransactionList(from: nil, until: nil, limit: 10, offset: 0, unpaid: false, type: "")
guard let ev = req.to_nostr_event(to_pk: url.pubkey, keypair: url.keypair) else {
return nil
}
try? pool.add_relay(.nwc(url: url.relay)) // Ensure the NWC relay is connected
WalletConnect.subscribe(url: url, pool: pool) // Ensure we are listening to NWC updates from the relay
post.send(ev, to: [url.relay], skip_ephemeral: false, delay: delay, on_flush: on_flush)
return ev
}
static func handle_zap_success(state: DamusState, resp: WalletConnect.FullWalletResponse) {
// find the pending zap and mark it as pending-confirmed
for kv in state.zaps.our_zaps {
let zaps = kv.value
for zap in zaps {
guard case .pending(let pzap) = zap,
case .nwc(let nwc_state) = pzap.state,
case .postbox_pending(let nwc_req) = nwc_state.state,
nwc_req.id == resp.req_id
else {
continue
}
if nwc_state.update_state(state: .confirmed) {
// notify the zaps model of an update so it can mark them as paid
state.events.get_cache_data(NoteId(pzap.target.id)).zaps_model.objectWillChange.send()
print("NWC success confirmed")
}
return
}
}
}
/// Send a donation zap to the Damus team
static func send_donation_zap(pool: RelayPool, postbox: PostBox, nwc: WalletConnectURL, percent: Int, base_msats: Int64) async {
let percent_f = Double(percent) / 100.0
let donations_msats = Int64(percent_f * Double(base_msats))
let payreq = LNUrlPayRequest(allowsNostr: true, commentAllowed: nil, nostrPubkey: "", callback: "https://sendsats.lol/@damus")
guard let invoice = await fetch_zap_invoice(payreq, zapreq: nil, msats: donations_msats, zap_type: .non_zap, comment: nil) else {
// we failed... oh well. no donation for us.
print("damus-donation failed to fetch invoice")
return
}
print("damus-donation donating...")
WalletConnect.pay(url: nwc, pool: pool, post: postbox, invoice: invoice, delay: nil)
}
/// Handles a received Nostr Wallet Connect error
static func handle_error(zapcache: Zaps, evcache: EventCache, resp: WalletConnect.FullWalletResponse) {
// find a pending zap with the nwc request id associated with this response and remove it
for kv in zapcache.our_zaps {
let zaps = kv.value
for zap in zaps {
guard case .pending(let pzap) = zap,
case .nwc(let nwc_state) = pzap.state,
case .postbox_pending(let req) = nwc_state.state,
req.id == resp.req_id
else {
continue
}
// remove the pending zap if there was an error
let reqid = ZapRequestId(from_pending: pzap)
remove_zap(reqid: reqid, zapcache: zapcache, evcache: evcache)
return
}
}
}
}
@@ -1,92 +0,0 @@
//
// WalletConnect.swift
// damus
//
// Created by William Casarin on 2023-03-22.
//
import Foundation
struct WalletConnect {}
typealias WalletConnectURL = WalletConnect.ConnectURL // Declared to facilitate refactor
extension WalletConnect {
/// Models a decoded NWC URL, containing information to connect to an NWC wallet.
struct ConnectURL: Equatable {
let relay: RelayURL
let keypair: FullKeypair
let pubkey: Pubkey
let lud16: String?
static func == (lhs: ConnectURL, rhs: ConnectURL) -> Bool {
return lhs.keypair == rhs.keypair &&
lhs.pubkey == rhs.pubkey &&
lhs.relay == rhs.relay
}
func to_url() -> URL {
var urlComponents = URLComponents()
urlComponents.scheme = "nostrwalletconnect"
urlComponents.host = pubkey.hex()
urlComponents.queryItems = [
URLQueryItem(name: "relay", value: relay.absoluteString),
URLQueryItem(name: "secret", value: keypair.privkey.hex())
]
if let lud16 {
urlComponents.queryItems?.append(URLQueryItem(name: "lud16", value: lud16))
}
return urlComponents.url!
}
init?(str: String) {
guard let components = URLComponents(string: str),
components.scheme == "nostrwalletconnect" || components.scheme == "nostr+walletconnect",
// The line below provides flexibility for both `nostrwalletconnect://` (non-compliant, but commonly used) and `nostrwalletconnect:` (NIP-47 compliant) formats
let encoded_pubkey = components.path == "" ? components.host : components.path,
let pubkey = hex_decode_pubkey(encoded_pubkey),
let items = components.queryItems,
let relay = items.first(where: { qi in qi.name == "relay" })?.value,
let relay_url = RelayURL(relay),
let secret = items.first(where: { qi in qi.name == "secret" })?.value,
secret.utf8.count == 64,
let decoded = hex_decode(secret)
else {
return nil
}
let privkey = Privkey(Data(decoded))
guard let our_pk = privkey_to_pubkey(privkey: privkey) else { return nil }
let lud16 = items.first(where: { qi in qi.name == "lud16" })?.value
let keypair = FullKeypair(pubkey: our_pk, privkey: privkey)
self = ConnectURL(pubkey: pubkey, relay: relay_url, keypair: keypair, lud16: lud16)
}
init(pubkey: Pubkey, relay: RelayURL, keypair: FullKeypair, lud16: String?) {
self.pubkey = pubkey
self.relay = relay
self.keypair = keypair
self.lud16 = lud16
}
}
/// Models an NWC wallet transaction
struct Transaction: Decodable, Equatable, Hashable {
let type: String
let invoice: String?
let description: String?
let description_hash: String?
let preimage: String?
let payment_hash: String?
let amount: Int64
let fees_paid: Int64?
let created_at: UInt64 // unixtimestamp, // invoice/payment creation time
let expires_at: UInt64? // unixtimestamp, // invoice expiration time, optional if not applicable
let settled_at: UInt64? // unixtimestamp, // invoice/payment settlement time, optional if unpaid
//"metadata": {} // generic metadata that can be used to add things like zap/boostagram details for a payer name/comment/etc.
}
}
+1 -1
View File
@@ -298,7 +298,7 @@ struct ChatEventView: View {
}
.swipeSpacing(-20)
.swipeActionsStyle(.mask)
.swipeMinimumDistance(40)
.swipeMinimumDistance(20)
.swipeDragGesturePriority(.normal)
}
}
+40 -16
View File
@@ -13,24 +13,47 @@ struct ChatroomThreadView: View {
@State var once: Bool = false
let damus: DamusState
@ObservedObject var thread: ThreadModel
@State var highlighted_note_id: NoteId? = nil
@State var selected_note_id: NoteId? = nil
@State var user_just_posted_flag: Bool = false
@Namespace private var animation
@State var parent_events: [NostrEvent] = []
@State var sorted_child_events: [NostrEvent] = []
func compute_events(selected_event: NostrEvent? = nil) {
let selected_event = selected_event ?? thread.event
self.parent_events = damus.events.parent_events(event: selected_event, keypair: damus.keypair)
let all_recursive_child_events = self.recursive_child_events(event: selected_event)
self.sorted_child_events = all_recursive_child_events.filter({
should_show_event(event: $0, damus_state: damus) // Hide muted events from chatroom conversation
}).sorted(by: { a, b in
return a.created_at < b.created_at
})
}
func recursive_child_events(event: NdbNote) -> [NdbNote] {
let immediate_children = damus.events.child_events(event: event)
var indirect_children: [NdbNote] = []
for immediate_child in immediate_children {
indirect_children.append(contentsOf: self.recursive_child_events(event: immediate_child))
}
return immediate_children + indirect_children
}
func go_to_event(scroller: ScrollViewProxy, note_id: NoteId) {
scroll_to_event(scroller: scroller, id: note_id, delay: 0, animate: true, anchor: .top)
highlighted_note_id = note_id
selected_note_id = note_id
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
withAnimation {
highlighted_note_id = nil
selected_note_id = nil
}
})
}
func set_active_event(scroller: ScrollViewProxy, ev: NdbNote) {
withAnimation {
self.thread.select(event: ev)
self.compute_events(selected_event: ev)
thread.set_active_event(ev, keypair: self.damus.keypair)
self.go_to_event(scroller: scroller, note_id: ev.id)
}
}
@@ -40,7 +63,7 @@ struct ChatroomThreadView: View {
ScrollView(.vertical) {
LazyVStack(alignment: .leading, spacing: 8) {
// MARK: - Parents events view
ForEach(thread.parent_events, id: \.id) { parent_event in
ForEach(parent_events, id: \.id) { parent_event in
EventMutingContainerView(damus_state: damus, event: parent_event) {
EventView(damus: damus, event: parent_event)
.matchedGeometryEffect(id: parent_event.id.hex(), in: animation, anchor: .center)
@@ -70,7 +93,7 @@ struct ChatroomThreadView: View {
// MARK: - Actual event view
EventMutingContainerView(
damus_state: damus,
event: self.thread.selected_event,
event: self.thread.event,
muteBox: { event_shown, muted_reason in
AnyView(
EventMutedBoxView(shown: event_shown, reason: muted_reason)
@@ -78,19 +101,19 @@ struct ChatroomThreadView: View {
)
}
) {
SelectedEventView(damus: damus, event: self.thread.selected_event, size: .selected)
.matchedGeometryEffect(id: self.thread.selected_event.id.hex(), in: animation, anchor: .center)
SelectedEventView(damus: damus, event: self.thread.event, size: .selected)
.matchedGeometryEffect(id: self.thread.event.id.hex(), in: animation, anchor: .center)
}
.id(self.thread.selected_event.id)
.id(self.thread.event.id)
// MARK: - Children view
let events = thread.sorted_child_events
let events = sorted_child_events
let count = events.count
SwipeViewGroup {
ForEach(Array(zip(events, events.indices)), id: \.0.id) { (ev, ind) in
ChatEventView(event: events[ind],
selected_event: self.thread.selected_event,
selected_event: self.thread.event,
prev_ev: ind > 0 ? events[ind-1] : nil,
next_ev: ind == count-1 ? nil : events[ind+1],
damus_state: damus,
@@ -101,7 +124,7 @@ struct ChatroomThreadView: View {
focus_event: {
self.set_active_event(scroller: scroller, ev: ev)
},
highlight_bubble: highlighted_note_id == ev.id,
highlight_bubble: selected_note_id == ev.id,
bar: make_actionbar_model(ev: ev.id, damus: damus)
)
.padding(.horizontal)
@@ -125,14 +148,16 @@ struct ChatroomThreadView: View {
}
})
.onReceive(thread.objectWillChange) {
if let last_event = thread.events.last, last_event.pubkey == damus.pubkey, user_just_posted_flag {
self.compute_events()
if let last_event = thread.events().last, last_event.pubkey == damus.pubkey, user_just_posted_flag {
self.go_to_event(scroller: scroller, note_id: last_event.id)
user_just_posted_flag = false
}
}
.onAppear() {
thread.subscribe()
scroll_to_event(scroller: scroller, id: thread.selected_event.id, delay: 0.1, animate: false)
self.compute_events()
scroll_to_event(scroller: scroller, id: thread.event.id, delay: 0.1, animate: false)
}
.onDisappear() {
thread.unsubscribe()
@@ -168,7 +193,6 @@ struct ChatroomView_Previews: PreviewProvider {
}
}
@MainActor
func scroll_after_load(thread: ThreadModel, proxy: ScrollViewProxy) {
scroll_to_event(scroller: proxy, id: thread.selected_event.id, delay: 0.1, animate: false)
scroll_to_event(scroller: proxy, id: thread.event.id, delay: 0.1, animate: false)
}
+63 -108
View File
@@ -18,26 +18,11 @@ struct ConfigView: View {
@State var delete_account_warning: Bool = false
@State var confirm_delete_account: Bool = false
@State var delete_text: String = ""
@State private var searchText: String = ""
@ObservedObject var settings: UserSettingsStore
// String constants
private let DELETE_KEYWORD = "DELETE"
private let keysTitle = NSLocalizedString("Keys", comment: "Settings section for managing keys")
private let appearanceTitle = NSLocalizedString("Appearance and filters", comment: "Section header for text, appearance, and content filter settings")
private let searchUniverseTitle = NSLocalizedString("Search / Universe", comment: "Section header for search/universe settings")
private let notificationsTitle = NSLocalizedString("Notifications", comment: "Section header for Damus notifications")
private let zapsTitle = NSLocalizedString("Zaps", comment: "Section header for zap settings")
private let translationTitle = NSLocalizedString("Translation", comment: "Section header for text and appearance settings")
private let reactionsTitle = NSLocalizedString("Reactions", comment: "Section header for reactions settings")
private let developerTitle = NSLocalizedString("Developer", comment: "Section header for developer settings")
private let firstAidTitle = NSLocalizedString("First Aid", comment: "Section header for first aid tools and settings")
private let signOutTitle = NSLocalizedString("Sign out", comment: "Sidebar menu label to sign out of the account.")
private let deleteAccountTitle = NSLocalizedString("Delete Account", comment: "Button to delete the user's account.")
private let versionTitle = NSLocalizedString("Version", comment: "Section title for displaying the version number of the Damus app.")
private let copyString = NSLocalizedString("Copy", comment: "Context menu option for copying the version of damus.")
init(state: DamusState) {
self.state = state
_settings = ObservedObject(initialValue: state.settings)
@@ -46,122 +31,91 @@ struct ConfigView: View {
func textColor() -> Color {
colorScheme == .light ? DamusColors.black : DamusColors.white
}
func showSettingsButton(title : String)->Bool{
return searchText.isEmpty || title.lowercased().contains(searchText.lowercased())
}
var body: some View {
ZStack(alignment: .leading) {
Form {
Section {
// Keys
if showSettingsButton(title: keysTitle){
NavigationLink(value:Route.KeySettings(keypair: state.keypair)){
IconLabel(keysTitle,img_name:"Key",color:.purple)
}
}
// Appearance and filters
if showSettingsButton(title: appearanceTitle){
NavigationLink(value:Route.AppearanceSettings(settings: settings)){
IconLabel(appearanceTitle,img_name:"eye",color:.red)
}
}
// Search/Universe
if showSettingsButton(title: searchUniverseTitle){
NavigationLink(value: Route.SearchSettings(settings: settings)){
IconLabel(searchUniverseTitle,img_name:"search",color:.red)
}
NavigationLink(value: Route.KeySettings(keypair: state.keypair)) {
IconLabel(NSLocalizedString("Keys", comment: "Settings section for managing keys"), img_name: "Key", color: .purple)
}
//Notifications
if showSettingsButton(title: notificationsTitle){
NavigationLink(value: Route.NotificationSettings(settings: settings)){
IconLabel(notificationsTitle,img_name:"notification-bell-on",color:.blue)
}
NavigationLink(value: Route.AppearanceSettings(settings: settings)) {
IconLabel(NSLocalizedString("Appearance and filters", comment: "Section header for text, appearance, and content filter settings"), img_name: "eye", color: .red)
}
//Zaps
if showSettingsButton(title: zapsTitle){
NavigationLink(value: Route.ZapSettings(settings: settings)){
IconLabel(zapsTitle,img_name:"zap.fill",color:.orange)
}
NavigationLink(value: Route.SearchSettings(settings: settings)) {
IconLabel(NSLocalizedString("Search/Universe", comment: "Section header for search/universe settings"), img_name: "search", color: .red)
}
//Translation
if showSettingsButton(title: translationTitle){
NavigationLink(value: Route.TranslationSettings(settings: settings)){
IconLabel(translationTitle,img_name:"globe",color:.green)
}
NavigationLink(value: Route.NotificationSettings(settings: settings)) {
IconLabel(NSLocalizedString("Notifications", comment: "Section header for Damus notifications"), img_name: "notification-bell-on", color: .blue)
}
//Reactions
if showSettingsButton(title: reactionsTitle){
NavigationLink(value: Route.ReactionsSettings(settings: settings)){
IconLabel(reactionsTitle,img_name:"shaka.fill",color:.purple)
}
NavigationLink(value: Route.ZapSettings(settings: settings)) {
IconLabel(NSLocalizedString("Zaps", comment: "Section header for zap settings"), img_name: "zap.fill", color: .orange)
}
//Developer
if showSettingsButton(title: developerTitle){
NavigationLink(value: Route.DeveloperSettings(settings: settings)){
IconLabel(developerTitle,img_name:"magic-stick2.fill",color:DamusColors.adaptableBlack)
}
NavigationLink(value: Route.TranslationSettings(settings: settings)) {
IconLabel(NSLocalizedString("Translation", comment: "Section header for text and appearance settings"), img_name: "globe", color: .green)
}
//First Aid
if showSettingsButton(title: firstAidTitle){
NavigationLink(value: Route.FirstAidSettings(settings: settings)){
IconLabel(firstAidTitle,img_name:"help2",color: .red)
}
NavigationLink(value: Route.ReactionsSettings(settings: settings)) {
IconLabel(NSLocalizedString("Reactions", comment: "Section header for reactions settings"), img_name: "shaka.fill", color: .purple)
}
NavigationLink(value: Route.DeveloperSettings(settings: settings)) {
IconLabel(NSLocalizedString("Developer", comment: "Section header for developer settings"), img_name: "magic-stick2.fill", color: DamusColors.adaptableBlack)
}
NavigationLink(value: Route.FirstAidSettings(settings: settings)) {
IconLabel(NSLocalizedString("First Aid", comment: "Section header for first aid tools and settings"), img_name: "help2", color: .red)
}
}
//Sign out Section
if showSettingsButton(title: signOutTitle){
Section(signOutTitle){
Section(NSLocalizedString("Sign Out", comment: "Section title for signing out")) {
Button(action: {
if state.keypair.privkey == nil {
logout(state)
} else {
confirm_logout = true
}
}, label: {
Label(NSLocalizedString("Sign out", comment: "Sidebar menu label to sign out of the account."), image: "logout")
.foregroundColor(textColor())
.frame(maxWidth: .infinity, alignment: .leading)
})
}
if state.is_privkey_user {
Section(header: Text("Permanently Delete Account", comment: "Section title for deleting the user")) {
Button(action: {
if state.keypair.privkey == nil {
logout(state)
} else {
confirm_logout = true
}
delete_account_warning = true
}, label: {
Label(signOutTitle, image: "logout")
.foregroundColor(textColor())
Label(NSLocalizedString("Delete Account", comment: "Button to delete the user's account."), image: "delete")
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundColor(.red)
})
}
}
// Delete Account
if showSettingsButton(title: deleteAccountTitle){
if state.is_privkey_user {
Section(header: Text("Permanently Delete Account", comment: "Section title for deleting the user")) {
Button(action: {
delete_account_warning = true
}, label: {
Label(deleteAccountTitle, image: "delete")
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundColor(.red)
})
}
}
}
// Version info
if showSettingsButton(title: versionTitle) {
Section(
header: Text(versionTitle),
footer: Text("").padding(.bottom, tabHeight + getSafeAreaBottom())
) {
Text(verbatim: VersionInfo.version)
.contextMenu {
Button {
UIPasteboard.general.string = VersionInfo.version
} label: {
Label(copyString, image: "copy2")
}
Section(
header: Text(NSLocalizedString("Version", comment: "Section title for displaying the version number of the Damus app.")),
footer: Text("").padding(.bottom, tabHeight + getSafeAreaBottom())
) {
Text(verbatim: VersionInfo.version)
.contextMenu {
Button {
UIPasteboard.general.string = VersionInfo.version
} label: {
Label(NSLocalizedString("Copy", comment: "Context menu option for copying the version of damus."), image: "copy2")
}
}
}
}
}
}
.navigationTitle(NSLocalizedString("Settings", comment: "Navigation title for Settings view."))
.navigationBarTitleDisplayMode(.large)
.searchable(text: $searchText,prompt: "Search within settings")
.alert(NSLocalizedString("WARNING:\n\nTHIS WILL SIGN AN EVENT THAT DELETES THIS ACCOUNT.\n\nYOU WILL NO LONGER BE ABLE TO LOG INTO DAMUS USING THIS ACCOUNT KEY.\n\n ARE YOU SURE YOU WANT TO CONTINUE?", comment: "Alert for deleting the users account."), isPresented: $delete_account_warning) {
Button(NSLocalizedString("Cancel", comment: "Cancel deleting the user."), role: .cancel) {
@@ -200,6 +154,7 @@ struct ConfigView: View {
dismiss()
}
}
}
struct ConfigView_Previews: PreviewProvider {
+41 -1
View File
@@ -131,7 +131,7 @@ struct DMChatView: View, KeyboardReadable {
.map(\.asString)
.joined(separator: "")
guard let dm = NIP04.create_dm(content, to_pk: pubkey, tags: tags, keypair: damus_state.keypair) else {
guard let dm = create_dm(content, to_pk: pubkey, tags: tags, keypair: damus_state.keypair) else {
print("error creating dm")
return
}
@@ -176,6 +176,46 @@ struct DMChatView_Previews: PreviewProvider {
}
}
func encrypt_message(message: String, privkey: Privkey, to_pk: Pubkey, encoding: EncEncoding = .base64) -> String? {
let iv = random_bytes(count: 16).bytes
guard let shared_sec = get_shared_secret(privkey: privkey, pubkey: to_pk) else {
return nil
}
let utf8_message = Data(message.utf8).bytes
guard let enc_message = aes_encrypt(data: utf8_message, iv: iv, shared_sec: shared_sec) else {
return nil
}
switch encoding {
case .base64:
return encode_dm_base64(content: enc_message.bytes, iv: iv)
case .bech32:
return encode_dm_bech32(content: enc_message.bytes, iv: iv)
}
}
func create_encrypted_event(_ message: String, to_pk: Pubkey, tags: [[String]], keypair: FullKeypair, created_at: UInt32, kind: UInt32) -> NostrEvent? {
let privkey = keypair.privkey
guard let enc_content = encrypt_message(message: message, privkey: privkey, to_pk: to_pk) else {
return nil
}
return NostrEvent(content: enc_content, keypair: keypair.to_keypair(), kind: kind, tags: tags, createdAt: created_at)
}
func create_dm(_ message: String, to_pk: Pubkey, tags: [[String]], keypair: Keypair, created_at: UInt32? = nil) -> NostrEvent?
{
let created = created_at ?? UInt32(Date().timeIntervalSince1970)
guard let keypair = keypair.to_full() else {
return nil
}
return create_encrypted_event(message, to_pk: to_pk, tags: tags, keypair: keypair, created_at: created, kind: 4)
}
extension View {
/// Layers the given views behind this ``TextEditor``.
func textEditorBackground<V>(@ViewBuilder _ content: () -> V) -> some View where V : View {
-119
View File
@@ -1,119 +0,0 @@
//
// ErrorView.swift
// damus
//
// Created by Daniel D'Aquino on 2025-01-08.
//
import SwiftUI
/// A generic user-presentable error view
///
/// Use this to handle and display errors to the user when it does not make sense to create a custom error view.
/// This includes good error handling UX practices, such as:
/// - Clear description
/// - Actionable advice for the user on what to do next.
/// - One-click support contact options
struct ErrorView: View {
let damus_state: DamusState?
let error: UserPresentableError
@Environment(\.dismiss) var dismiss
var body: some View {
VStack(spacing: 6) {
Image(systemName: "exclamationmark.circle")
.resizable()
.frame(width: 30, height: 30)
.foregroundStyle(.red)
.accessibilityHidden(true)
Text("Oops!", comment: "Heading for an error screen")
.font(.title)
.bold()
.padding(.bottom, 10)
.accessibilityHeading(.h1)
Text(error.user_visible_description)
.foregroundStyle(.secondary)
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 5) {
Image(systemName: "sparkles")
.accessibilityHidden(true)
Text("Advice", comment: "Heading for some advice text to help the user with an error")
.font(.headline)
.accessibilityHeading(.h3)
}
Text(error.tip)
}
.padding()
.background(Color.secondary.opacity(0.2))
.cornerRadius(10)
.padding(.vertical, 30)
Spacer()
if let damus_state, damus_state.is_privkey_user {
Button(action: {
damus_state.nav.push(route: .DMChat(dms: .init(our_pubkey: damus_state.keypair.pubkey, pubkey: Constants.SUPPORT_PUBKEY)))
dismiss()
}, label: {
Text("Contact support via DMs", comment: "Button label to contact support from an error screen")
})
.padding(.vertical, 20)
}
Text("Contact support via email at [support@damus.io](mailto:support@damus.io)", comment: "Text to contact support via email")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding(20)
.padding(.top, 20)
}
/// An error that is displayed to the user, and can be sent to the Developers as well.
struct UserPresentableError {
/// The description of the error to be shown to the user
///
/// **Requirements:**
/// - This should not be technical. It should use accessible language
/// - Should be localized
/// - It should try to explain the user what happened, and if possible why.
let user_visible_description: String
/// Helpful tip/advice to the user, to help them overcome the error
///
/// **Requirements:**
/// - Should provide actionable advice to the user
/// - This should not be overly technical
/// - Should be localized
/// - Should NOT include support contact (The view that will display this will already include support contact options)
///
/// **Implementation notes:**
/// - This is NOT an optional value, because part of good UX is making sure error messages are actionable, which is something that is often forgotten. It's not uncommon for error messages to be written in vague, technical, and/or unactionable terms, but this is when the user needs help the most. And so this field is made mandatory to force developers to write actionable content to the user
let tip: String
/// Technical information about the error, which will be sendable to developers
///
/// Note: This is still unutilized, but this will be used in the future.
///
/// **Requirements**
/// - Should never include any sensitive info
/// - Should be in English. The developers are the main audience.
/// - Should include helping info, such as context in which the error happens.
/// - Should be technical
let technical_info: String?
}
}
#Preview {
ErrorView(
damus_state: test_damus_state,
error: .init(
user_visible_description: "We are still too early",
tip: "Stay humble, keep building, stack sats",
technical_info: nil
)
)
}
-4
View File
@@ -57,10 +57,6 @@ struct EventView: View {
// blame the porn bots for this code
func should_blur_images(settings: UserSettingsStore, contacts: Contacts, ev: NostrEvent, our_pubkey: Pubkey, booster_pubkey: Pubkey? = nil) -> Bool {
if settings.undistractMode {
return true
}
if !settings.blur_images {
return false
}
+1 -1
View File
@@ -39,7 +39,7 @@ struct EventBody: View {
HighlightBodyView(state: damus_state, ev: event, options: options)
.onTapGesture {
if let highlighted_note = event.highlighted_note_id().flatMap({ damus_state.events.lookup($0) }) {
let thread = ThreadModel(event: highlighted_note, damus_state: damus_state)
let thread = ThreadModel(event: highlighted_note, damus_state: damus_state, highlight: event.content)
damus_state.nav.push(route: Route.Thread(thread: thread))
}
}
+1 -1
View File
@@ -135,7 +135,7 @@ struct MenuItems: View {
MuteDurationMenu { duration in
notify(.mute(.user(target_pubkey, duration?.date_from_now)))
} label: {
Label(NSLocalizedString("Mute/Block user", comment: "Context menu option for muting/blocking users."), image: "mute")
Label(NSLocalizedString("Mute user", comment: "Context menu option for muting users."), image: "mute")
}
}
}
-275
View File
@@ -1,275 +0,0 @@
//
// LoadableNostrEventView.swift
// damus
//
// Created by Daniel D'Aquino on 2025-01-08.
//
import SwiftUI
/// A view model for `LoadableNostrEventView`
///
/// This takes a nostr event reference, automatically tries to load it, and updates itself to reflect its current state
///
/// ## Implementation notes
///
/// - This is on the main actor because `ObservableObjects` with `Published` properties should be on the main actor for thread-safety.
///
@MainActor
class LoadableNostrEventViewModel: ObservableObject {
let damus_state: DamusState
let note_reference: NoteReference
@Published var state: ThreadModelLoadingState = .loading
/// The time period after which it will give up loading the view.
/// Written in nanoseconds
let TIMEOUT: UInt64 = 10 * 1_000_000_000 // 10 seconds
init(damus_state: DamusState, note_reference: NoteReference) {
self.damus_state = damus_state
self.note_reference = note_reference
Task { await self.load() }
}
func load() async {
// Start the loading process in a separate task to manage the timeout independently.
let loadTask = Task { @MainActor in
self.state = await executeLoadingLogic(note_reference: self.note_reference)
}
// Setup a timer to cancel the load after the timeout period
let timeoutTask = Task { @MainActor in
try await Task.sleep(nanoseconds: TIMEOUT)
loadTask.cancel() // This sends a cancellation signal to the load task.
self.state = .not_found
}
await loadTask.value
timeoutTask.cancel() // Cancel the timeout task if loading finishes earlier.
}
/// Asynchronously find an event from NostrDB or from the network (if not available on NostrDB)
private func loadEvent(noteId: NoteId) async -> NostrEvent? {
let res = await find_event(state: damus_state, query: .event(evid: noteId))
guard let res, case .event(let ev) = res else { return nil }
return ev
}
/// Gets the note reference and tries to load it, outputting a new state for this view model.
private func executeLoadingLogic(note_reference: NoteReference) async -> ThreadModelLoadingState {
switch note_reference {
case .note_id(let note_id):
guard let ev = await self.loadEvent(noteId: note_id) else { return .not_found }
guard let known_kind = ev.known_kind else { return .unknown_or_unsupported_kind }
switch known_kind {
case .text, .highlight:
return .loaded(route: Route.Thread(thread: ThreadModel(event: ev, damus_state: damus_state)))
case .dm:
let dm_model = damus_state.dms.lookup_or_create(ev.pubkey)
return .loaded(route: Route.DMChat(dms: dm_model))
case .like:
// Load the event that this reaction refers to.
guard let first_referenced_note_id = ev.referenced_ids.first else { return .not_found }
return await self.executeLoadingLogic(note_reference: .note_id(first_referenced_note_id))
case .zap, .zap_request:
guard let zap = await get_zap(from: ev, state: damus_state) else { return .not_found }
return .loaded(route: Route.Zaps(target: zap.target))
case .contacts, .metadata, .delete, .boost, .chat, .mute_list, .list_deprecated, .draft, .longform, .zap, .zap_request, .nwc_request, .nwc_response, .http_auth, .status:
return .unknown_or_unsupported_kind
}
case .naddr(let naddr):
guard let event = await naddrLookup(damus_state: damus_state, naddr: naddr) else { return .not_found }
return .loaded(route: Route.Thread(thread: ThreadModel(event: event, damus_state: damus_state)))
}
}
enum ThreadModelLoadingState {
case loading
case loaded(route: Route)
case not_found
case unknown_or_unsupported_kind
}
enum NoteReference: Hashable {
case note_id(NoteId)
case naddr(NAddr)
}
}
/// A view for a Nostr event that has not been loaded yet.
/// This takes a Nostr event reference and loads it, while providing nice loading UX and graceful error handling.
struct LoadableNostrEventView: View {
let state: DamusState
@StateObject var loadableModel: LoadableNostrEventViewModel
var loading: Bool {
switch loadableModel.state {
case .loading:
return true
case .loaded, .not_found, .unknown_or_unsupported_kind:
return false
}
}
init(state: DamusState, note_reference: LoadableNostrEventViewModel.NoteReference) {
self.state = state
self._loadableModel = StateObject.init(wrappedValue: LoadableNostrEventViewModel(damus_state: state, note_reference: note_reference))
}
var body: some View {
switch self.loadableModel.state {
case .loading:
ScrollView(.vertical) {
self.skeleton
.redacted(reason: loading ? .placeholder : [])
.shimmer(loading)
.accessibilityElement(children: .ignore)
.accessibilityLabel(NSLocalizedString("Loading thread", comment: "Accessibility label for the thread view when it is loading"))
}
case .loaded(route: let route):
route.view(navigationCoordinator: state.nav, damusState: state)
case .not_found:
self.not_found
case .unknown_or_unsupported_kind:
self.unknown_or_unsupported_kind
}
}
var not_found: some View {
SomethingWrong(
imageSystemName: "questionmark.app",
heading: NSLocalizedString("Note not found", comment: "Heading for the thread view in a not found error state."),
description: NSLocalizedString("We were unable to find the note you were looking for.", comment: "Text for the thread view when it is unable to find the note the user is looking for"),
advice: NSLocalizedString("Try checking the link again, your internet connection, or contact the person who provided you the link for help.", comment: "Tips on what to do if a note cannot be found.")
)
}
var unknown_or_unsupported_kind: some View {
SomethingWrong(
imageSystemName: "questionmark.app",
heading: NSLocalizedString("Cant display note", comment: "User-visible heading for an error message indicating a note has an unknown kind or is unsupported for viewing."),
description: NSLocalizedString("We do not yet support viewing this type of content.", comment: "User-visible description of an error indicating a note has an unknown kind or is unsupported for viewing."),
advice: NSLocalizedString("Please try opening this content on another Nostr app that supports this type of content.", comment: "User-visible advice on what to do if they see the error indicating a note has an unknown kind or is unsupported for viewing.")
)
}
// MARK: Skeleton views
// Implementation notes
// - No localization is needed because the text will be redacted
// - No accessibility label is needed because these will be summarized into a single accessibility label at the top-level view. See `body` in this struct
var skeleton: some View {
VStack(alignment: .leading, spacing: 40) {
Self.skeleton_selected_event
Self.skeleton_chat_event(message: "Nice! Have you tried Damus?", right: false)
Self.skeleton_chat_event(message: "Yes, it's awesome.", right: true)
Spacer()
}
.padding()
}
static func skeleton_chat_event(message: String, right: Bool) -> some View {
HStack(alignment: .center) {
if !right {
self.skeleton_chat_user_avatar
}
else {
Spacer()
}
ChatBubble(
direction: right ? .right : .left,
stroke_content: Color.accentColor.opacity(0),
stroke_style: .init(lineWidth: 4),
background_style: Color.secondary.opacity(0.5),
content: {
Text(verbatim: message)
.padding()
}
)
if right {
self.skeleton_chat_user_avatar
}
else {
Spacer()
}
}
}
static var skeleton_selected_event: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Circle()
.frame(width: 50, height: 50)
.foregroundStyle(.secondary.opacity(0.5))
Text(verbatim: "Satoshi Nakamoto")
.bold()
}
Text(verbatim: "Nostr is the super app. Because its actually an ecosystem of apps, all of which make each other better. People havent grasped that yet. They will when its more accessible and onboarding is more straightforward and intuitive.")
HStack {
self.skeleton_action_item
Spacer()
self.skeleton_action_item
Spacer()
self.skeleton_action_item
Spacer()
self.skeleton_action_item
}
}
}
static var skeleton_chat_user_avatar: some View {
Circle()
.fill(.secondary.opacity(0.5))
.frame(width: 35, height: 35)
.padding(.bottom, -21)
}
static var skeleton_action_item: some View {
Circle()
.fill(Color.secondary.opacity(0.5))
.frame(width: 25, height: 25)
}
}
extension LoadableNostrEventView {
struct SomethingWrong: View {
let imageSystemName: String
let heading: String
let description: String
let advice: String
var body: some View {
VStack(spacing: 6) {
Image(systemName: imageSystemName)
.resizable()
.frame(width: 30, height: 30)
.accessibilityHidden(true)
Text(heading)
.font(.title)
.bold()
.padding(.bottom, 10)
Text(description)
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 5) {
Image(systemName: "sparkles")
.accessibilityHidden(true)
Text("Advice", comment: "Heading for some advice text to help the user with an error")
.font(.headline)
}
Text(advice)
}
.padding()
.background(Color.secondary.opacity(0.2))
.cornerRadius(10)
.padding(.vertical, 30)
}
.padding()
}
}
}
#Preview("Loadable") {
LoadableNostrEventView(state: test_damus_state, note_reference: .note_id(test_thread_note_1.id))
}
-3
View File
@@ -40,9 +40,6 @@ struct NoteContentView: View {
@ObservedObject var settings: UserSettingsStore
var note_artifacts: NoteArtifacts {
if damus_state.settings.undistractMode {
return .separated(.just_content(Undistractor.makeGibberish(text: event.get_content(damus_state.keypair))))
}
return self.artifacts_model.state.artifacts ?? .separated(.just_content(event.get_content(damus_state.keypair)))
}
@@ -60,8 +60,21 @@ struct NotificationsView: View {
@Environment(\.colorScheme) var colorScheme
var mystery: some View {
let profile_txn = state.profiles.lookup(id: state.pubkey)
let profile = profile_txn?.unsafeUnownedValue
return VStack(spacing: 20) {
Text("Wake up, \(Profile.displayName(profile: profile, pubkey: state.pubkey).displayName.truncate(maxLength: 50))", comment: "Text telling the user to wake up, where the argument is their display name.")
Text("You are dreaming...", comment: "Text telling the user that they are dreaming.")
}
.id("what")
}
var body: some View {
TabView(selection: $filter_state) {
// This is needed or else there is a bug when switching from the 3rd or 2nd tab to first. no idea why.
mystery
NotificationTab(
NotificationFilter(
state: .all,
+65 -122
View File
@@ -51,32 +51,21 @@ enum PostAction {
}
struct PostView: View {
@State var post: NSMutableAttributedString = NSMutableAttributedString()
@State var uploadedMedias: [UploadedMedia] = []
@State var references: [RefId] = []
/// Pubkeys that should be filtered out from the references
///
/// For example, when replying to an event, the user can select which pubkey mentions they want to keep, and which ones to remove.
@State var filtered_pubkeys: Set<Pubkey> = []
@FocusState var focus: Bool
@State var attach_media: Bool = false
@State var attach_camera: Bool = false
@State var error: String? = nil
@State var uploadedMedias: [UploadedMedia] = []
@State var image_upload_confirm: Bool = false
@State var imagePastedFromPasteboard: PreUploadedMedia? = nil
@State var imageUploadConfirmPasteboard: Bool = false
@State var references: [RefId] = []
@State var imageUploadConfirmDamusShare: Bool = false
@State var filtered_pubkeys: Set<Pubkey> = []
@State var focusWordAttributes: (String?, NSRange?) = (nil, nil)
@State var newCursorIndex: Int?
@State var textHeight: CGFloat? = nil
/// Manages the auto-save logic for drafts.
///
/// ## Implementation notes
///
/// - This intentionally does _not_ use `@ObservedObject` or `@StateObject` because observing changes causes unwanted automatic scrolling to the text cursor on each save state update.
var autoSaveModel: AutoSaveIndicatorView.AutoSaveViewModel
@State var preUploadedMedia: [PreUploadedMedia] = []
@@ -104,7 +93,6 @@ struct PostView: View {
self.prompt_view = prompt_view
self.placeholder_messages = placeholder_messages ?? [POST_PLACEHOLDER]
self.initial_text_suffix = initial_text_suffix
self.autoSaveModel = AutoSaveIndicatorView.AutoSaveViewModel(save: { damus_state.drafts.save(damus_state: damus_state) })
}
@Environment(\.dismiss) var dismiss
@@ -121,7 +109,24 @@ struct PostView: View {
}
func send_post() {
let new_post = build_post(state: self.damus_state, post: self.post, action: action, uploadedMedias: uploadedMedias, references: self.references, filtered_pubkeys: filtered_pubkeys)
// don't add duplicate pubkeys but retain order
var pkset = Set<Pubkey>()
// we only want pubkeys really
let pks = references.reduce(into: Array<Pubkey>()) { acc, ref in
guard case .pubkey(let pk) = ref else {
return
}
if pkset.contains(pk) || filtered_pubkeys.contains(pk) {
return
}
pkset.insert(pk)
acc.append(pk)
}
let new_post = build_post(state: damus_state, post: self.post, action: action, uploadedMedias: uploadedMedias, pubkeys: pks)
notify(.post(.post(new_post)))
@@ -181,8 +186,6 @@ struct PostView: View {
HStack(alignment: .center, spacing: 15) {
ImageButton
CameraButton
Spacer()
AutoSaveIndicatorView(saveViewModel: self.autoSaveModel)
}
.disabled(uploading_disabled)
}
@@ -219,49 +222,40 @@ struct PostView: View {
func clear_draft() {
switch action {
case .replying_to(let replying_to):
damus_state.drafts.replies.removeValue(forKey: replying_to.id)
damus_state.drafts.replies.removeValue(forKey: replying_to)
case .quoting(let quoting):
damus_state.drafts.quotes.removeValue(forKey: quoting.id)
damus_state.drafts.quotes.removeValue(forKey: quoting)
case .posting:
damus_state.drafts.post = nil
case .highlighting(let draft):
damus_state.drafts.highlights.removeValue(forKey: draft)
damus_state.drafts.highlights.removeValue(forKey: draft.source)
case .sharing(_):
damus_state.drafts.post = nil
}
damus_state.drafts.save(damus_state: damus_state)
}
func load_draft() -> Bool {
guard let draft = load_draft_for_post(drafts: self.damus_state.drafts, action: self.action) else {
self.post = NSMutableAttributedString("")
self.uploadedMedias = []
self.autoSaveModel.markNothingToSave() // We should not save empty drafts.
return false
}
self.uploadedMedias = draft.media
self.post = draft.content
self.autoSaveModel.markSaved() // The draft we just loaded is saved to memory. Mark it as such.
return true
}
/// Use this to signal that the post contents have changed. This will do two things:
///
/// 1. Save the new contents into our in-memory drafts
/// 2. Signal that we need to save drafts persistently, which will happen after a certain wait period
func post_changed(post: NSMutableAttributedString, media: [UploadedMedia]) {
if let draft = load_draft_for_post(drafts: damus_state.drafts, action: action) {
draft.content = post
draft.media = uploadedMedias
draft.references = references
draft.filtered_pubkeys = filtered_pubkeys
draft.media = media
} else {
let artifacts = DraftArtifacts(content: post, media: uploadedMedias, references: references, id: UUID().uuidString)
let artifacts = DraftArtifacts(content: post, media: media)
set_draft_for_post(drafts: damus_state.drafts, action: action, artifacts: artifacts)
}
self.autoSaveModel.needsSaving()
}
var TextEntry: some View {
@@ -362,7 +356,7 @@ struct PostView: View {
}
let blurhash = await blurhash
let meta = blurhash.map { bh in calculate_image_metadata(url: url, img: img, blurhash: bh) }
let uploadedMedia = UploadedMedia(localURL: media.localURL, uploadedURL: url, metadata: meta)
let uploadedMedia = UploadedMedia(localURL: media.localURL, uploadedURL: url, representingImage: img, metadata: meta)
uploadedMedias.append(uploadedMedia)
return true
@@ -634,7 +628,7 @@ struct PVImageCarouselView: View {
.cornerRadius(10)
.padding()
.contextMenu { contextMenuContent(for: media[index]) }
} else {
} else if is_animated_image(url: media[index].uploadedURL) {
KFAnimatedImage(media[index].uploadedURL)
.imageContext(.note, disable_animation: false)
.configure { view in
@@ -644,6 +638,14 @@ struct PVImageCarouselView: View {
.cornerRadius(10)
.padding()
.contextMenu { contextMenuContent(for: media[index]) }
} else {
Image(uiImage: media[index].representingImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: media.count == 1 ? deviceWidth * 0.8 : 250, height: media.count == 1 ? 400 : 250)
.cornerRadius(10)
.padding()
.contextMenu { contextMenuContent(for: media[index]) }
}
VStack { // Set spacing to 0 to remove the gap between items
@@ -730,6 +732,7 @@ fileprivate func getImage(media: MediaUpload) -> UIImage {
struct UploadedMedia: Equatable {
let localURL: URL
let uploadedURL: URL
let representingImage: UIImage
let metadata: ImageMetadata?
}
@@ -737,13 +740,13 @@ struct UploadedMedia: Equatable {
func set_draft_for_post(drafts: Drafts, action: PostAction, artifacts: DraftArtifacts) {
switch action {
case .replying_to(let ev):
drafts.replies[ev.id] = artifacts
drafts.replies[ev] = artifacts
case .quoting(let ev):
drafts.quotes[ev.id] = artifacts
drafts.quotes[ev] = artifacts
case .posting:
drafts.post = artifacts
case .highlighting(let draft):
drafts.highlights[draft] = artifacts
drafts.highlights[draft.source] = artifacts
case .sharing(_):
drafts.post = artifacts
}
@@ -752,21 +755,13 @@ func set_draft_for_post(drafts: Drafts, action: PostAction, artifacts: DraftArti
func load_draft_for_post(drafts: Drafts, action: PostAction) -> DraftArtifacts? {
switch action {
case .replying_to(let ev):
return drafts.replies[ev.id]
return drafts.replies[ev]
case .quoting(let ev):
return drafts.quotes[ev.id]
return drafts.quotes[ev]
case .posting:
return drafts.post
case .highlighting(let highlight):
if let exact_match = drafts.highlights[highlight] {
return exact_match // Always prefer to return the draft for that exact same highlight
}
// If there are no exact matches to the highlight, try to load a draft for the same highlight source
// We do this to improve UX, because we don't want to leave the post view blank if they only selected a slightly different piece of text from before.
var other_matches = drafts.highlights
.filter { $0.key.source == highlight.source }
// It's not an exact match, so there is no way of telling which one is the preferred draft. So just load the first one we found.
return other_matches.first?.value
case .highlighting(let draft):
return drafts.highlights[draft.source]
case .sharing(_):
return drafts.post
}
@@ -793,53 +788,7 @@ func nip10_reply_tags(replying_to: NostrEvent, keypair: Keypair) -> [[String]] {
return tags
}
func build_post(state: DamusState, action: PostAction, draft: DraftArtifacts) -> NostrPost {
return build_post(
state: state,
post: draft.content,
action: action,
uploadedMedias: draft.media,
references: draft.references,
filtered_pubkeys: draft.filtered_pubkeys
)
}
func build_post(state: DamusState, post: NSAttributedString, action: PostAction, uploadedMedias: [UploadedMedia], references: [RefId], filtered_pubkeys: Set<Pubkey>) -> NostrPost {
// don't add duplicate pubkeys but retain order
var pkset = Set<Pubkey>()
// we only want pubkeys really
let pks = references.reduce(into: Array<Pubkey>()) { acc, ref in
guard case .pubkey(let pk) = ref else {
return
}
if pkset.contains(pk) || filtered_pubkeys.contains(pk) {
return
}
pkset.insert(pk)
acc.append(pk)
}
return build_post(state: state, post: post, action: action, uploadedMedias: uploadedMedias, pubkeys: pks)
}
/// This builds a Nostr post from draft data from `PostView` or other draft-related classes
///
/// ## Implementation notes
///
/// - This function _likely_ causes no side-effects, and _should not_ cause side-effects to any of the inputs.
///
/// - Parameters:
/// - state: The damus state, needed to fetch more Nostr data to form this event
/// - post: The text content from `PostView`.
/// - action: The intended action of the post (highlighting? replying?)
/// - uploadedMedias: The medias attached to this post
/// - pubkeys: The referenced pubkeys
/// - Returns: A NostrPost, which can then be signed into an event.
func build_post(state: DamusState, post: NSAttributedString, action: PostAction, uploadedMedias: [UploadedMedia], pubkeys: [Pubkey]) -> NostrPost {
let post = NSMutableAttributedString(attributedString: post)
func build_post(state: DamusState, post: NSMutableAttributedString, action: PostAction, uploadedMedias: [UploadedMedia], pubkeys: [Pubkey]) -> NostrPost {
post.enumerateAttributes(in: NSRange(location: 0, length: post.length), options: []) { attributes, range, stop in
if let link = attributes[.link] as? String {
let nextCharIndex = range.upperBound
@@ -865,31 +814,33 @@ func build_post(state: DamusState, post: NSAttributedString, action: PostAction,
var content = post.string
.trimmingCharacters(in: .whitespacesAndNewlines)
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let imagesString = uploadedMedias.map { $0.uploadedURL.absoluteString }.joined(separator: "\n")
let imagesString = uploadedMedias.map { $0.uploadedURL.absoluteString }.joined(separator: " ")
if !imagesString.isEmpty {
content.append("\n\n" + imagesString)
content.append(" " + imagesString + " ")
}
var tags: [[String]] = []
switch action {
case .replying_to(let replying_to):
// start off with the reply tags
tags = nip10_reply_tags(replying_to: replying_to, keypair: state.keypair)
case .replying_to(let replying_to):
// start off with the reply tags
tags = nip10_reply_tags(replying_to: replying_to, keypair: state.keypair)
case .quoting(let ev):
content.append("\n\nnostr:" + bech32_note_id(ev.id))
case .quoting(let ev):
content.append(" nostr:" + bech32_note_id(ev.id))
tags.append(["q", ev.id.hex()]);
if let quoted_ev = state.events.lookup(ev.id) {
tags.append(["p", quoted_ev.pubkey.hex()])
}
case .posting, .highlighting, .sharing:
break
if let quoted_ev = state.events.lookup(ev.id) {
tags.append(["p", quoted_ev.pubkey.hex()])
}
case .posting(let postTarget):
break
case .highlighting(let draft):
break
case .sharing(_):
break
}
// append additional tags
@@ -911,7 +862,7 @@ func build_post(state: DamusState, post: NSAttributedString, action: PostAction,
}
}
return NostrPost(content: content.trimmingCharacters(in: .whitespacesAndNewlines), kind: .text, tags: tags)
return NostrPost(content: content, kind: .text, tags: tags)
}
func isSupportedVideo(url: URL?) -> Bool {
@@ -925,11 +876,3 @@ func isSupportedVideo(url: URL?) -> Bool {
return false
}
}
func isSupportedImage(url: URL) -> Bool {
let fileExtension = url.pathExtension.lowercased()
// It would be better to pull this programmatically from Apple's APIs, but there seems to be no such call
let supportedTypes = ["jpg", "png", "gif"]
return supportedTypes.contains(fileExtension)
}
@@ -1,136 +0,0 @@
//
// AutoSaveIndicatorView.swift
// damus
//
// Created by Daniel DAquino on 2025-02-12.
//
import SwiftUI
/// A small indicator view to indicate whether an item has been saved or not.
///
/// This view uses and observes an `AutoSaveViewModel`.
struct AutoSaveIndicatorView: View {
@ObservedObject var saveViewModel: AutoSaveViewModel
var body: some View {
HStack {
switch saveViewModel.savedState {
case .needsSaving, .nothingToSave:
EmptyView()
.accessibilityHidden(true) // Probably no need to show this to users with visual impairment, might be too noisy.
case .saving:
ProgressView()
.accessibilityHidden(true) // Probably no need to show this to users with visual impairment, might be too noisy.
case .saved:
Image(systemName: "checkmark")
.accessibilityHidden(true)
Text("Saved", comment: "Small label indicating that the user's draft has been saved to storage.")
.accessibilityLabel(NSLocalizedString("Your draft has been saved to storage.", comment: "Accessibility label indicating that a user's post draft has been saved, meant to be read by screen reading technology."))
.font(.caption)
}
}
.padding(6)
.foregroundStyle(.secondary)
}
}
extension AutoSaveIndicatorView {
/// A simple data structure to model the saving state of an item that can be auto-saved every few seconds.
enum SaveState: Equatable {
/// There is nothing to save (e.g. A new empty item was just created, an item was just loaded)
case nothingToSave
/// The item has been modified and needs saving.
/// Saving should occur in N seconds.
case needsSaving(secondsRemaining: Int)
/// A saving operation is in progress.
case saving
/// The item has been saved to disk.
case saved
}
/// Models an auto-save mechanism, which automatically saves an item after N seconds.
///
/// # Implementation notes
///
/// - This runs on the main actor because running this on other actors causes issues with published properties.
/// - Running on one actor helps ensure thread safety.
@MainActor
class AutoSaveViewModel: ObservableObject {
/// The delay between the time something is marked as needing to save, and the actual saving operation.
///
/// Should be low enough that the user does not lose significant progress, and should be high enough to avoid unnecessary disk writes and jittery, stress-inducing behavior
let saveDelay: Int
/// The current state of this model
@Published private(set) var savedState: SaveState
/// A timer which counts down the time to save the item
private var timer: Timer?
/// The function that performs the actual save operation
var save: () async -> Void
// MARK: Init/de-init
/// Initializes a new auto-save model
/// - Parameters:
/// - save: The function that performs the save operation
/// - initialState: Optional initial state
/// - saveDelay: The time delay between the item is marked as needing to be saved, and the actual save operation denoted in seconds.
init(save: @escaping () async -> Void, initialState: SaveState = .nothingToSave, saveDelay: Int = 3) {
self.saveDelay = saveDelay
self.savedState = initialState
self.save = save
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in
Task { await self.tick() } // Task { await ... } ensures the function is properly run on the main actor and avoids thread-safety issues
})
self.timer = timer
}
deinit {
if let timer = self.timer {
timer.isValid ? timer.invalidate() : ()
}
}
// MARK: Internal logic
/// Runs internal countdown-to-save logic
private func tick() async {
switch self.savedState {
case .needsSaving(secondsRemaining: let secondsRemaining):
if secondsRemaining <= 0 {
self.savedState = .saving
await save()
self.savedState = .saved
}
else {
self.savedState = .needsSaving(secondsRemaining: secondsRemaining - 1)
}
case .saving, .saved, .nothingToSave:
break
}
}
// MARK: External interface
/// Marks item as needing to be saved.
/// Call this whenever your item is modified.
func needsSaving() {
self.savedState = .needsSaving(secondsRemaining: self.saveDelay)
}
/// Marks item as saved.
/// Call this when you know the item is already saved (e.g. when loading a saved item from memory).
func markSaved() {
self.savedState = .saved
}
/// Tells the auto-save logic that there is nothing to be saved.
/// Call this when there is nothing to be saved (e.g. when opening a new empty item).
func markNothingToSave() {
self.savedState = .nothingToSave
}
}
}
@@ -170,9 +170,6 @@ struct EditMetadataView: View {
TextField(NSLocalizedString("Lightning Address or LNURL", comment: "Placeholder text for entry of Lightning Address or LNURL."), text: $ln)
.autocorrectionDisabled(true)
.textInputAutocapitalization(.never)
.onReceive(Just(ln)) { newValue in
self.ln = newValue.trimmingCharacters(in: .whitespaces)
}
}
Section(content: {
+4 -21
View File
@@ -122,12 +122,6 @@ struct ProfileView: View {
func content_filter(_ fstate: FilterState) -> ((NostrEvent) -> Bool) {
var filters = ContentFilters.defaults(damus_state: damus_state)
filters.append(fstate.filter)
switch fstate {
case .posts, .posts_and_replies:
filters.append({ profile.pubkey == $0.pubkey })
case .conversations:
filters.append({ profile.conversation_events.contains($0.id) } )
}
return ContentFilters(filters: filters).filter
}
@@ -435,17 +429,6 @@ struct ProfileView: View {
.padding(.horizontal)
}
var tabs: [(String, FilterState)] {
var tabs = [
(NSLocalizedString("Notes", comment: "Label for filter for seeing only notes (instead of notes and replies)."), FilterState.posts),
(NSLocalizedString("Notes & Replies", comment: "Label for filter for seeing notes and replies (instead of only notes)."), FilterState.posts_and_replies)
]
if profile.pubkey != damus_state.pubkey && !profile.conversation_events.isEmpty {
tabs.append((NSLocalizedString("Conversations", comment: "Label for filter for seeing notes and replies that involve conversations between the signed in user and the current profile."), FilterState.conversations))
}
return tabs
}
var body: some View {
ZStack {
ScrollView(.vertical) {
@@ -457,7 +440,10 @@ struct ProfileView: View {
aboutSection
VStack(spacing: 0) {
CustomPicker(tabs: tabs, selection: $filter_state)
CustomPicker(tabs: [
(NSLocalizedString("Notes", comment: "Label for filter for seeing only notes (instead of notes and replies)."), FilterState.posts),
(NSLocalizedString("Notes & Replies", comment: "Label for filter for seeing notes and replies (instead of only notes)."), FilterState.posts_and_replies)
], selection: $filter_state)
Divider()
.frame(height: 1)
}
@@ -469,9 +455,6 @@ struct ProfileView: View {
if filter_state == FilterState.posts_and_replies {
InnerTimelineView(events: profile.events, damus: damus_state, filter: content_filter(FilterState.posts_and_replies))
}
if filter_state == FilterState.conversations && !profile.conversation_events.isEmpty {
InnerTimelineView(events: profile.events, damus: damus_state, filter: content_filter(FilterState.conversations))
}
}
.padding(.horizontal, Theme.safeAreaInsets?.left)
.zIndex(-yOffset > navbarHeight ? 0 : 1)
@@ -123,7 +123,7 @@ struct DamusPurpleAccountView: View {
func profile_display_name() -> String {
let profile_txn: NdbTxn<ProfileRecord?>? = damus_state.profiles.lookup_with_timestamp(account.pubkey)
let profile: NdbProfile? = profile_txn?.unsafeUnownedValue?.profile
let display_name = DisplayName(profile: profile, pubkey: account.pubkey).displayName
let display_name = parse_display_name(profile: profile, pubkey: account.pubkey).displayName
return display_name
}
}
@@ -136,8 +136,7 @@ struct DamusPurpleAccountView: View {
created_at: Date.now,
expiry: Date.init(timeIntervalSinceNow: 60 * 60 * 24 * 30),
subscriber_number: 7,
active: true,
attributes: []
active: true
)
)
}
@@ -150,8 +149,7 @@ struct DamusPurpleAccountView: View {
created_at: Date.init(timeIntervalSinceNow: -60 * 60 * 24 * 37),
expiry: Date.init(timeIntervalSinceNow: -60 * 60 * 24 * 7),
subscriber_number: 7,
active: false,
attributes: []
active: false
)
)
}
+1 -1
View File
@@ -16,7 +16,7 @@ struct RepostedEvent: View {
var body: some View {
VStack(alignment: .leading) {
NavigationLink(value: Route.ProfileByKey(pubkey: event.pubkey)) {
Reposted(damus: damus, pubkey: event.pubkey, target: inner_ev)
Reposted(damus: damus, pubkey: event.pubkey)
.padding(.horizontal)
}
.buttonStyle(PlainButtonStyle())
@@ -17,7 +17,6 @@ struct DeveloperSettingsView: View {
Toggle(NSLocalizedString("Developer Mode", comment: "Setting to enable developer mode"), isOn: $settings.developer_mode)
.toggleStyle(.switch)
if settings.developer_mode {
Toggle(NSLocalizedString("Undistract mode", comment: "Developer mode setting to scramble text and images to avoid distractions during development."), isOn: $settings.undistractMode)
Toggle(NSLocalizedString("Always show onboarding", comment: "Developer mode setting to always show onboarding suggestions."), isOn: $settings.always_show_onboarding_suggestions)
Picker(NSLocalizedString("Push notification environment", comment: "Prompt selection of the Push notification environment (Developer feature to switch between real/production mode to test modes)."),
selection: Binding(
-3
View File
@@ -162,9 +162,6 @@ struct SideMenuView: View {
PubkeyView(pubkey: damus_state.pubkey, sidemenu: true)
.pubkey_context_menu(pubkey: damus_state.pubkey)
.simultaneousGesture(TapGesture().onEnded{
isSidebarVisible = true
})
}
}
}
+130
View File
@@ -0,0 +1,130 @@
//
// ThreadV2View.swift
// damus
//
// Created by Thomas Tastet on 25/12/2022.
//
import SwiftUI
struct ThreadView: View {
let state: DamusState
@ObservedObject var thread: ThreadModel
@Environment(\.dismiss) var dismiss
var parent_events: [NostrEvent] {
state.events.parent_events(event: thread.event, keypair: state.keypair)
}
var sorted_child_events: [NostrEvent] {
state.events.child_events(event: thread.event).sorted(by: { a, b in
let a_is_muted = !should_show_event(event: a, damus_state: state)
let b_is_muted = !should_show_event(event: b, damus_state: state)
if a_is_muted == b_is_muted {
// If both are muted or unmuted, sort them based on their creation date.
return a.created_at < b.created_at
}
else {
// Muting status is different
// Prioritize the replies that are not muted
return !a_is_muted && b_is_muted
}
})
}
var body: some View {
//let top_zap = get_top_zap(events: state.events, evid: thread.event.id)
ScrollViewReader { reader in
ScrollView {
LazyVStack {
// MARK: - Parents events view
ForEach(parent_events, id: \.id) { parent_event in
EventMutingContainerView(damus_state: state, event: parent_event) {
EventView(damus: state, event: parent_event)
}
.padding(.horizontal)
.onTapGesture {
thread.set_active_event(parent_event, keypair: self.state.keypair)
scroll_to_event(scroller: reader, id: parent_event.id, delay: 0.1, animate: false)
}
Divider()
.padding(.top, 4)
.padding(.leading, 25 * 2)
}.background(GeometryReader { geometry in
// get the height and width of the EventView view
let eventHeight = geometry.frame(in: .global).height
// let eventWidth = geometry.frame(in: .global).width
// vertical gray line in the background
Rectangle()
.fill(Color.gray.opacity(0.25))
.frame(width: 2, height: eventHeight)
.offset(x: 40, y: 40)
})
// MARK: - Actual event view
EventMutingContainerView(
damus_state: state,
event: self.thread.event,
muteBox: { event_shown, muted_reason in
AnyView(
EventMutedBoxView(shown: event_shown, reason: muted_reason)
.padding(5)
)
}
) {
SelectedEventView(damus: state, event: self.thread.event, size: .selected)
}
.id(self.thread.event.id)
/*
if let top_zap {
ZapEvent(damus: state, zap: top_zap, is_top_zap: true)
.padding(.horizontal)
}
*/
ForEach(sorted_child_events, id: \.id) { child_event in
EventMutingContainerView(
damus_state: state,
event: child_event
) {
EventView(damus: state, event: child_event)
}
.padding(.horizontal)
.onTapGesture {
thread.set_active_event(child_event, keypair: state.keypair)
scroll_to_event(scroller: reader, id: child_event.id, delay: 0.1, animate: false)
}
Divider()
.padding([.top], 4)
}
}
}.navigationBarTitle(NSLocalizedString("Thread", comment: "Navigation bar title for note thread."))
.onAppear {
thread.subscribe()
let anchor: UnitPoint = self.thread.event.known_kind == .longform ? .top : .bottom
scroll_to_event(scroller: reader, id: self.thread.event.id, delay: 0.0, animate: false, anchor: anchor)
}
.onDisappear {
thread.unsubscribe()
}
.onReceive(handle_notify(.switched_timeline)) { notif in
dismiss()
}
}
}
}
struct ThreadView_Previews: PreviewProvider {
static var previews: some View {
let state = test_damus_state
let thread = ThreadModel(event: test_note, damus_state: state)
ThreadView(state: state, thread: thread)
}
}
@@ -25,6 +25,11 @@ struct PostingTimelineView: View {
@State var headerHeight: CGFloat = 0
@Binding var headerOffset: CGFloat
@SceneStorage("PostingTimelineView.filter_state") var filter_state : FilterState = .posts_and_replies
var mystery: some View {
Text("Are you lost?", comment: "Text asking the user if they are lost in the app.")
.id("what")
}
func content_filter(_ fstate: FilterState) -> ((NostrEvent) -> Bool) {
var filters = ContentFilters.defaults(damus_state: damus_state)
@@ -90,6 +95,9 @@ struct PostingTimelineView: View {
VStack {
ZStack {
TabView(selection: $filter_state) {
// This is needed or else there is a bug when switching from the 3rd or 2nd tab to first. no idea why.
mystery
contentTimelineView(filter: content_filter(.posts))
.tag(FilterState.posts)
.id(FilterState.posts)
-56
View File
@@ -1,56 +0,0 @@
//
// BalanceView.swift
// damus
//
// Created by eric on 1/23/25.
//
import SwiftUI
struct BalanceView: View {
var balance: Int64?
var body: some View {
VStack(spacing: 5) {
Text("Current balance", comment: "Label for displaying current wallet balance")
.foregroundStyle(DamusColors.neutral6)
if let balance {
self.numericalBalanceView(text: NumberFormatter.localizedString(from: NSNumber(integerLiteral: Int(balance)), number: .decimal))
}
else {
// Make sure we do not show any numeric value to the user when still loading (or when failed to load)
// This is important because if we show a numeric value like "zero" when things are not loaded properly, we risk scaring the user into thinking that they have lost funds.
self.numericalBalanceView(text: "??")
.redacted(reason: .placeholder)
.shimmer(true)
}
}
}
func numericalBalanceView(text: String) -> some View {
HStack {
Text(verbatim: text)
.lineLimit(1)
.minimumScaleFactor(0.70)
.font(.veryVeryLargeTitle)
.fontWeight(.heavy)
.foregroundStyle(PinkGradient)
HStack(alignment: .top) {
Text("SATS", comment: "Abbreviation for Satoshis, smallest bitcoin unit")
.font(.caption)
.fontWeight(.heavy)
.foregroundStyle(PinkGradient)
}
}
.padding(.bottom)
}
}
struct BalanceView_Previews: PreviewProvider {
static var previews: some View {
BalanceView(balance: 100000000)
BalanceView(balance: nil)
}
}
+87 -174
View File
@@ -15,13 +15,13 @@ struct ConnectWalletView: View {
@State private var showAlert = false
@State var error: String? = nil
@State var wallet_scan_result: WalletScanResult = .scanning
@State var show_introduction: Bool = true
var nav: NavigationCoordinator
var body: some View {
MainContent
.navigationTitle(NSLocalizedString("Wallet", comment: "Navigation title for attaching Nostr Wallet Connect lightning wallet."))
.navigationBarTitleDisplayMode(.inline)
.padding()
.onChange(of: wallet_scan_result) { res in
scanning = false
@@ -48,137 +48,57 @@ struct ConnectWalletView: View {
}
}
struct AreYouSure: View {
let nwc: WalletConnectURL
@Binding var show_introduction: Bool
@ObservedObject var model: WalletModel
var body: some View {
ScrollView {
VStack(spacing: 25) {
Text("Setup Wallet", comment: "Heading for wallet setup confirmation screen")
.font(.veryLargeTitle)
.fontWeight(.bold)
.multilineTextAlignment(.center)
Spacer()
ConnectGraphic
Spacer()
NWCSettings.AccountDetailsView(nwc: nwc)
Spacer()
Button(action: {
model.connect(nwc)
show_introduction = false
}) {
HStack {
Text("Connect", comment: "Text for button to conect to Nostr Wallet Connect lightning wallet.")
.fontWeight(.semibold)
}
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
.buttonStyle(GradientButtonStyle())
Button(action: {
model.cancel()
show_introduction = true
}) {
HStack {
Text("Cancel", comment: "Text for button to cancel out of connecting Nostr Wallet Connect lightning wallet.")
.padding()
}
.frame(minWidth: 300, maxWidth: .infinity, alignment: .center)
}
.buttonStyle(NeutralButtonStyle())
func AreYouSure(nwc: WalletConnectURL) -> some View {
VStack(spacing: 25) {
Text("Are you sure you want to connect this wallet?", comment: "Prompt to ask user if they want to attach their Nostr Wallet Connect lightning wallet.")
.fontWeight(.bold)
.multilineTextAlignment(.center)
Text(nwc.relay.absoluteString)
.font(.body)
.foregroundColor(.gray)
if let lud16 = nwc.lud16 {
Text(lud16)
.font(.body)
.foregroundColor(.gray)
}
Button(action: {
model.connect(nwc)
}) {
HStack {
Text("Connect", comment: "Text for button to conect to Nostr Wallet Connect lightning wallet.")
.fontWeight(.semibold)
}
.padding(.bottom, 50)
.padding()
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
}
var ConnectGraphic: some View {
HStack(spacing: 0) {
Button(action: {}, label: {
Image("damus-home")
.resizable()
.frame(width: 30, height: 30)
})
.buttonStyle(NeutralButtonStyle(padding: EdgeInsets(top: 15, leading: 15, bottom: 15, trailing: 15), cornerRadius: 9999))
.disabled(true)
.padding(.horizontal, 30)
Image("chevron-double-right")
.resizable()
.frame(width: 25, height: 25)
Button(action: {}, label: {
Image("wallet")
.resizable()
.frame(width: 30, height: 30)
.foregroundStyle(LINEAR_GRADIENT)
})
.buttonStyle(NeutralButtonStyle(padding: EdgeInsets(top: 15, leading: 15, bottom: 15, trailing: 15), cornerRadius: 9999))
.disabled(true)
.padding(.horizontal, 30)
.buttonStyle(GradientButtonStyle())
Button(action: {
model.cancel()
}) {
HStack {
Text("Cancel", comment: "Text for button to cancel out of connecting Nostr Wallet Connect lightning wallet.")
.padding()
}
.frame(minWidth: 300, maxWidth: .infinity, alignment: .center)
}
.buttonStyle(NeutralButtonStyle())
}
}
var AutomaticSetup: some View {
VStack(spacing: 10) {
Text("AUTOMATIC SETUP", comment: "Heading for the section that performs an automatic wallet connection setup.")
.font(.caption)
.padding(.top)
.foregroundStyle(PinkGradient)
var ConnectWallet: some View {
VStack(spacing: 25) {
Text("Create new wallet", comment: "Button text for creating a new wallet.")
.font(.title)
.fontWeight(.bold)
Text("Easily create a new wallet and attach it to your account.", comment: "Description for the create new wallet feature.")
.font(.body)
.multilineTextAlignment(.center)
Spacer()
AlbyButton() {
openURL(URL(string:"https://nwc.getalby.com/apps/new?c=Damus")!)
}
CoinosButton() {
show_introduction = false
openURL(URL(string:"https://coinos.io/settings/nostr")!)
}
.padding()
}
.frame(minHeight: 250)
.padding(10)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 25)
.stroke(DamusColors.neutral3, lineWidth: 2)
.padding(2) // Avoids border clipping on the sides
)
.padding(.top, 20)
}
var ManualSetup: some View {
VStack(spacing: 10) {
Text("MANUAL SETUP", comment: "Label for manual wallet setup.")
.font(.caption)
.padding(.top)
.foregroundStyle(PinkGradient)
Text("Use existing", comment: "Button text to use an existing wallet.")
.font(.title)
.fontWeight(.bold)
Text("Attach to any third party provider you already use.", comment: "Information text guiding users on attaching existing provider.")
.font(.body)
.multilineTextAlignment(.center)
Spacer()
Button(action: {
if let pasted_nwc = UIPasteboard.general.string {
@@ -195,10 +115,9 @@ struct ConnectWalletView: View {
Text("Paste NWC Address", comment: "Text for button to connect a lightning wallet.")
.fontWeight(.semibold)
}
.frame(minWidth: 250, maxWidth: .infinity, maxHeight: 15, alignment: .center)
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
.buttonStyle(GradientButtonStyle())
.padding(.horizontal)
Button(action: {
nav.push(route: Route.WalletScanner(result: $wallet_scan_result))
@@ -208,80 +127,74 @@ struct ConnectWalletView: View {
Text("Scan NWC Address", comment: "Text for button to connect a lightning wallet.")
.fontWeight(.semibold)
}
.frame(minWidth: 250, maxWidth: .infinity, maxHeight: 15, alignment: .center)
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
.buttonStyle(GradientButtonStyle())
.padding(.horizontal)
.padding(.bottom)
if let err = self.error {
Text(err)
.foregroundColor(.red)
}
}
.frame(minHeight: 300)
.padding(10)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 25)
.stroke(DamusColors.neutral3, lineWidth: 2)
.padding(2) // Avoids border clipping on the sides
)
.padding(.top, 20)
}
var ConnectWallet: some View {
ScrollView {
VStack(spacing: 25) {
Text("Setup Wallet", comment: "Heading for Nostr Wallet Connect setup screen")
.font(.veryLargeTitle)
.fontWeight(.bold)
.multilineTextAlignment(.center)
AutomaticSetup
ManualSetup
if let err = self.error {
Text(err)
.foregroundColor(.red)
}
}
.padding(.bottom, 50)
.padding()
var TopSection: some View {
HStack(spacing: 0) {
Button(action: {}, label: {
Image("damus-home")
.resizable()
.frame(width: 30, height: 30)
})
.buttonStyle(NeutralButtonStyle(padding: EdgeInsets(top: 15, leading: 15, bottom: 15, trailing: 15), cornerRadius: 9999))
.disabled(true)
.padding(.horizontal, 30)
Image("chevron-double-right")
.resizable()
.frame(width: 25, height: 25)
Button(action: {}, label: {
Image("wallet")
.resizable()
.frame(width: 30, height: 30)
.foregroundStyle(LINEAR_GRADIENT)
})
.buttonStyle(NeutralButtonStyle(padding: EdgeInsets(top: 15, leading: 15, bottom: 15, trailing: 15), cornerRadius: 9999))
.disabled(true)
.padding(.horizontal, 30)
}
}
var TitleSection: some View {
VStack(spacing: 25) {
Text("Damus Wallet", comment: "Title text for Damus Wallet view.")
.fontWeight(.bold)
Text("Securely connect your Damus app to your wallet using Nostr Wallet Connect", comment: "Text to prompt user to connect their wallet using 'Nostr Wallet Connect'.")
.font(.caption)
.multilineTextAlignment(.center)
}
}
var MainContent: some View {
Group {
TopSection
switch model.connect_state {
case .new(let nwc):
AreYouSure(nwc: nwc, show_introduction: $show_introduction, model: self.model)
.onAppear() {
show_introduction = false
}
AreYouSure(nwc: nwc)
case .existing:
Text(verbatim: "Shouldn't happen")
case .none:
TitleSection
ConnectWallet
}
}
.fullScreenCover(isPresented: $show_introduction, content: {
ZapExplainerView(show_introduction: $show_introduction, nav: nav)
})
}
}
struct ConnectWalletView_Previews: PreviewProvider {
static var previews: some View {
ConnectWalletView(model: WalletModel(settings: UserSettingsStore()), nav: .init())
.previewDisplayName("Main Wallet Connect View")
ConnectWalletView.AreYouSure(nwc: get_test_nwc(), show_introduction: .constant(false), model: WalletModel(settings: test_damus_state.settings))
.previewDisplayName("Are you sure screen")
}
static func get_test_nwc() -> WalletConnectURL {
let pk = "9d088f4760422443d4699b485e2ac66e565a2f5da1198c55ddc5679458e3f67a"
let sec = "ff2eefd57196d42089e1b42acc39916d7ecac52e0625bd70597bbd5be14aff18"
let relay = "wss://relay.getalby.com/v1"
let str = "nostrwalletconnect://\(pk)?relay=\(relay)&secret=\(sec)"
return WalletConnectURL(str: str)!
}
}
-227
View File
@@ -1,227 +0,0 @@
//
// NWCSettings.swift
// damus
//
// Created by eric on 1/24/25.
//
import SwiftUI
struct NWCSettings: View {
let damus_state: DamusState
let nwc: WalletConnectURL
@ObservedObject var model: WalletModel
@ObservedObject var settings: UserSettingsStore
func donation_binding() -> Binding<Double> {
return Binding(get: {
return Double(model.settings.donation_percent)
}, set: { v in
model.settings.donation_percent = Int(v)
})
}
static let min_donation: Double = 0.0
static let max_donation: Double = 100.0
var percent: Double {
Double(model.settings.donation_percent) / 100.0
}
var tip_msats: String {
let msats = Int64(percent * Double(model.settings.default_zap_amount * 1000))
let s = format_msats_abbrev(msats)
// TODO: fix formatting and remove this hack
let parts = s.split(separator: ".")
if parts.count == 1 {
return s
}
if let end = parts[safe: 1] {
if end.allSatisfy({ c in c.isNumber }) {
return String(parts[0])
} else {
return s
}
}
return s
}
var SupportDamus: some View {
ZStack(alignment: .topLeading) {
RoundedRectangle(cornerRadius: 20)
.fill(DamusGradient.gradient.opacity(0.5))
VStack(alignment: .leading, spacing: 20) {
HStack {
Image("logo-nobg")
.resizable()
.frame(width: 50, height: 50)
Text("Support Damus", comment: "Text calling for the user to support Damus through zaps")
.font(.title.bold())
.foregroundColor(.white)
}
Text("Help build the future of decentralized communication on the web.", comment: "Text indicating the goal of developing Damus which the user can help with.")
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(.white)
Text("An additional percentage of each zap will be sent to support Damus development", comment: "Text indicating that they can contribute zaps to support Damus development.")
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(.white)
let binding = donation_binding()
HStack {
Slider(value: binding,
in: NWCSettings.min_donation...NWCSettings.max_donation,
label: { })
Text("\(Int(binding.wrappedValue))%", comment: "Percentage of additional zap that should be sent to support Damus development.")
.font(.title.bold())
.foregroundColor(.white)
.frame(width: 80)
}
HStack{
Spacer()
VStack {
HStack {
Text("\(Image("zap.fill")) \(format_msats_abbrev(Int64(model.settings.default_zap_amount) * 1000))")
.font(.title)
.foregroundColor(percent == 0 ? .gray : .yellow)
.frame(width: 120)
}
Text("Zap", comment: "Text underneath the number of sats indicating that it's the amount used for zaps.")
.foregroundColor(.white)
}
Spacer()
Text(verbatim: "+")
.font(.title)
.foregroundColor(.white)
Spacer()
VStack {
HStack {
Text("\(Image("zap.fill")) \(tip_msats)")
.font(.title)
.foregroundColor(percent == 0 ? .gray : Color.yellow)
.frame(width: 120)
}
Text(verbatim: percent == 0 ? "🩶" : "💜")
.foregroundColor(.white)
}
Spacer()
}
EventProfile(damus_state: damus_state, pubkey: damus_state.pubkey, size: .small)
}
.padding(25)
}
.frame(height: 370)
}
var body: some View {
VStack(alignment: .leading, spacing: 20) {
SupportDamus
.padding(.bottom)
AccountDetailsView(nwc: nwc)
Button(action: {
self.model.disconnect()
}) {
HStack {
Text("Disconnect Wallet", comment: "Text for button to disconnect from Nostr Wallet Connect lightning wallet.")
}
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
.buttonStyle(GradientButtonStyle())
}
.padding()
.onAppear() {
model.initial_percent = model.settings.donation_percent
}
.onChange(of: model.settings.donation_percent) { p in
let profile_txn = damus_state.profiles.lookup(id: damus_state.pubkey)
guard let profile = profile_txn?.unsafeUnownedValue else {
return
}
let prof = Profile(name: profile.name, display_name: profile.display_name, about: profile.about, picture: profile.picture, banner: profile.banner, website: profile.website, lud06: profile.lud06, lud16: profile.lud16, nip05: profile.nip05, damus_donation: p, reactions: profile.reactions)
notify(.profile_updated(.manual(pubkey: self.damus_state.pubkey, profile: prof)))
}
.onDisappear {
let profile_txn = damus_state.profiles.lookup(id: damus_state.pubkey)
guard let keypair = damus_state.keypair.to_full(),
let profile = profile_txn?.unsafeUnownedValue,
model.initial_percent != profile.damus_donation
else {
return
}
let prof = Profile(name: profile.name, display_name: profile.display_name, about: profile.about, picture: profile.picture, banner: profile.banner, website: profile.website, lud06: profile.lud06, lud16: profile.lud16, nip05: profile.nip05, damus_donation: model.settings.donation_percent, reactions: profile.reactions)
guard let meta = make_metadata_event(keypair: keypair, metadata: prof) else {
return
}
damus_state.postbox.send(meta)
}
}
struct AccountDetailsView: View {
let nwc: WalletConnect.ConnectURL
var body: some View {
VStack(alignment: .leading) {
Text("Account details", comment: "Prompt to ask user if they want to attach their Nostr Wallet Connect lightning wallet.")
.font(.title2)
.fontWeight(.bold)
.multilineTextAlignment(.center)
.padding(.bottom)
Text("Routing", comment: "Label indicating the routing address for Nostr Wallet Connect payments. In other words, the relay used by the NWC wallet provider")
.font(.headline)
Text(nwc.relay.absoluteString)
.font(.body)
.fontWeight(.bold)
.foregroundColor(.gray)
.padding(.bottom)
if let lud16 = nwc.lud16 {
Text("Account", comment: "Label for the user account information with the Nostr Wallet Connect wallet provider.")
.font(.headline)
Text(lud16)
.font(.body)
.fontWeight(.bold)
.foregroundColor(.gray)
}
}
.frame(maxWidth: .infinity, minHeight: 250, alignment: .leading)
.padding(.horizontal, 20)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 25)
.stroke(DamusColors.neutral3, lineWidth: 2)
)
}
}
}
struct NWCSettings_Previews: PreviewProvider {
static let tds = test_damus_state
static var previews: some View {
NWCSettings(damus_state: tds, nwc: test_wallet_connect_url, model: WalletModel(state: .existing(test_wallet_connect_url), settings: tds.settings), settings: tds.settings)
}
}
-148
View File
@@ -1,148 +0,0 @@
//
// TransactionsView.swift
// damus
//
// Created by eric on 1/23/25.
//
import SwiftUI
struct TransactionView: View {
let damus_state: DamusState
var transaction: WalletConnect.Transaction
var body: some View {
let isIncomingTransaction = transaction.type == "incoming"
let txType = isIncomingTransaction ? "arrow-bottom-left" : "arrow-top-right"
let txColor = isIncomingTransaction ? DamusColors.success : Color.gray
let txOp = isIncomingTransaction ? "+" : "-"
let created_at = Date.init(timeIntervalSince1970: TimeInterval(transaction.created_at))
let formatter = RelativeDateTimeFormatter()
let relativeDate = formatter.localizedString(for: created_at, relativeTo: Date.now)
let event = decode_nostr_event_json(transaction.description ?? "")
let pubkey = (event?.pubkey ?? ANON_PUBKEY)
VStack(alignment: .leading) {
HStack(alignment: .center) {
ZStack {
ProfilePicView(pubkey: pubkey, size: 45, highlight: .custom(.damusAdaptableBlack, 0.1), profiles: damus_state.profiles, disable_animation: damus_state.settings.disable_animation)
Image(txType)
.resizable()
.frame(width: 18, height: 18)
.foregroundColor(.white)
.padding(2)
.background(txColor)
.clipShape(Circle())
.overlay(Circle().stroke(Color.damusAdaptableWhite, lineWidth: 1.0))
.padding(.top, 25)
.padding(.leading, 35)
}
VStack(alignment: .leading, spacing: 10) {
Text(self.userDisplayName(pubkey: pubkey))
.font(.headline)
.bold()
.foregroundColor(DamusColors.adaptableBlack)
Text(relativeDate)
.font(.caption)
.foregroundColor(Color.gray)
}
.padding(.horizontal, 10)
Spacer()
Text(verbatim: "\(txOp) \(format_msats(transaction.amount))")
.font(.headline)
.foregroundColor(txColor)
.bold()
}
.frame(maxWidth: .infinity, minHeight: 75, alignment: .center)
.padding(.horizontal, 10)
.background(DamusColors.neutral1)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(DamusColors.neutral3, lineWidth: 1)
)
}
}
func userDisplayName(pubkey: Pubkey) -> String {
let profile_txn = damus_state.profiles.lookup(id: pubkey, txn_name: "txview-profile")
let profile = profile_txn?.unsafeUnownedValue
if let display_name = profile?.display_name {
return display_name
} else if let name = profile?.name {
return "@" + name
} else {
return NSLocalizedString("Unknown", comment: "A name label for an unknown user")
}
}
}
struct TransactionsView: View {
let damus_state: DamusState
let transactions: [WalletConnect.Transaction]?
var sortedTransactions: [WalletConnect.Transaction]? {
transactions?.sorted(by: { $0.created_at > $1.created_at })
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Latest transactions", comment: "Heading for latest wallet transactions list")
.foregroundStyle(DamusColors.neutral6)
if let sortedTransactions {
if sortedTransactions.isEmpty {
emptyTransactions
} else {
ForEach(sortedTransactions, id: \.self) { transaction in
TransactionView(damus_state: damus_state, transaction: transaction)
}
}
}
else {
// Make sure we do not show "No transactions yet" to the user when still loading (or when failed to load)
// This is important because if we show that when things are not loaded properly, we risk scaring the user into thinking that they have lost funds.
emptyTransactions
.redacted(reason: .placeholder)
.shimmer(true)
}
}
}
var emptyTransactions: some View {
HStack {
Text("No transactions yet", comment: "Message shown when no transactions are available")
.foregroundStyle(DamusColors.neutral6)
}
.frame(maxWidth: .infinity, minHeight: 75, alignment: .center)
.padding(.horizontal, 10)
.background(DamusColors.neutral1)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(DamusColors.neutral3, lineWidth: 1)
)
}
}
struct TransactionsView_Previews: PreviewProvider {
static let tds = test_damus_state
static let transaction1: WalletConnect.Transaction = WalletConnect.Transaction(type: "incoming", invoice: "", description: "{\"id\":\"7c0999a5870ca3ba0186a29a8650152b555cee29b53b5b8747d8a3798042d01c\",\"pubkey\":\"b8851a06dfd79d48fc325234a15e9a46a32a0982a823b54cdf82514b9b120ba1\",\"created_at\":1736383715,\"kind\":9734,\"tags\":[[\"p\",\"520830c334a3f79f88cac934580d26f91a7832c6b21fb9625690ea2ed81b5626\"],[\"amount\",\"21000\"],[\"e\",\"a25e152a4cd1b3bbc3d22e8e9315d8ea1f35c227b2f212c7cff18abff36fa208\"],[\"relays\",\"wss://nos.lol\",\"wss://nostr.wine\",\"wss://premium.primal.net\",\"wss://relay.damus.io\",\"wss://relay.nostr.band\",\"wss://relay.nostrarabia.com\"]],\"content\":\"🫡 Onward!\",\"sig\":\"e77d16822fa21b9c2e6b580b51c470588052c14aeb222f08f0e735027e366157c8742a6d5cb850780c2bf44ac63d89b048e5cc56dd47a1bfc740a3173e578f4e\"}", description_hash: "", preimage: "", payment_hash: "1234567890", amount: 21000, fees_paid: 0, created_at: 1737736866, expires_at: 0, settled_at: 0)
static let transaction2: WalletConnect.Transaction = WalletConnect.Transaction(type: "incoming", invoice: "", description: "", description_hash: "", preimage: "", payment_hash: "123456789033", amount: 100000000, fees_paid: 0, created_at: 1737690090, expires_at: 0, settled_at: 0)
static let transaction3: WalletConnect.Transaction = WalletConnect.Transaction(type: "outgoing", invoice: "", description: "", description_hash: "", preimage: "", payment_hash: "123456789042", amount: 303000, fees_paid: 0, created_at: 1737590101, expires_at: 0, settled_at: 0)
static let transaction4: WalletConnect.Transaction = WalletConnect.Transaction(type: "incoming", invoice: "", description: "", description_hash: "", preimage: "", payment_hash: "1234567890662", amount: 720000, fees_paid: 0, created_at: 1737090300, expires_at: 0, settled_at: 0)
static var test_transactions: [WalletConnect.Transaction] = [transaction1, transaction2, transaction3, transaction4]
static var previews: some View {
TransactionsView(damus_state: tds, transactions: test_transactions)
}
}
+191 -46
View File
@@ -9,7 +9,6 @@ import SwiftUI
struct WalletView: View {
let damus_state: DamusState
@State var show_settings: Bool = false
@ObservedObject var model: WalletModel
@ObservedObject var settings: UserSettingsStore
@@ -22,20 +21,178 @@ struct WalletView: View {
func MainWalletView(nwc: WalletConnectURL) -> some View {
ScrollView {
VStack(spacing: 35) {
VStack(spacing: 5) {
BalanceView(balance: model.balance)
TransactionsView(damus_state: damus_state, transactions: model.transactions)
if !damus_state.settings.nozaps {
SupportDamus
.padding(.vertical, 20)
}
VStack(spacing: 5) {
VStack(spacing: 10) {
Text("Wallet Relay", comment: "Label text indicating that below it is the information about the wallet relay.")
.fontWeight(.semibold)
.padding(.top)
Divider()
RelayView(state: damus_state, relay: nwc.relay, showActionButtons: .constant(false), recommended: false)
}
.frame(maxWidth: .infinity, minHeight: 125, alignment: .top)
.padding(.horizontal, 10)
.background(DamusColors.neutral1)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(DamusColors.neutral3, lineWidth: 1)
)
if let lud16 = nwc.lud16 {
VStack(spacing: 10) {
Text("Wallet Address", comment: "Label text indicating that below it is the wallet address.")
.fontWeight(.semibold)
Divider()
Text(lud16)
}
.frame(maxWidth: .infinity, minHeight: 75, alignment: .center)
.padding(.horizontal, 10)
.background(DamusColors.neutral1)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(DamusColors.neutral3, lineWidth: 1)
)
}
}
Button(action: {
self.model.disconnect()
}) {
HStack {
Text("Disconnect Wallet", comment: "Text for button to disconnect from Nostr Wallet Connect lightning wallet.")
}
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
.buttonStyle(GradientButtonStyle())
.padding(.bottom, 50) // Bottom padding while Scrolling
}
.navigationTitle(NSLocalizedString("Wallet", comment: "Navigation title for Wallet view"))
.navigationBarTitleDisplayMode(.inline)
.padding()
.padding(.bottom, 50)
}
}
func donation_binding() -> Binding<Double> {
return Binding(get: {
return Double(model.settings.donation_percent)
}, set: { v in
model.settings.donation_percent = Int(v)
})
}
static let min_donation: Double = 0.0
static let max_donation: Double = 100.0
var percent: Double {
Double(model.settings.donation_percent) / 100.0
}
var tip_msats: String {
let msats = Int64(percent * Double(model.settings.default_zap_amount * 1000))
let s = format_msats_abbrev(msats)
// TODO: fix formatting and remove this hack
let parts = s.split(separator: ".")
if parts.count == 1 {
return s
}
if let end = parts[safe: 1] {
if end.allSatisfy({ c in c.isNumber }) {
return String(parts[0])
} else {
return s
}
}
return s
}
var SupportDamus: some View {
ZStack(alignment: .topLeading) {
RoundedRectangle(cornerRadius: 20)
.fill(DamusGradient.gradient.opacity(0.5))
VStack(alignment: .leading, spacing: 20) {
HStack {
Image("logo-nobg")
.resizable()
.frame(width: 50, height: 50)
Text("Support Damus", comment: "Text calling for the user to support Damus through zaps")
.font(.title.bold())
.foregroundColor(.white)
}
Text("Help build the future of decentralized communication on the web.", comment: "Text indicating the goal of developing Damus which the user can help with.")
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(.white)
Text("An additional percentage of each zap will be sent to support Damus development", comment: "Text indicating that they can contribute zaps to support Damus development.")
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(.white)
let binding = donation_binding()
HStack {
Slider(value: binding,
in: WalletView.min_donation...WalletView.max_donation,
label: { })
Text("\(Int(binding.wrappedValue))%", comment: "Percentage of additional zap that should be sent to support Damus development.")
.font(.title.bold())
.foregroundColor(.white)
.frame(width: 80)
}
HStack{
Spacer()
VStack {
HStack {
Text("\(Image("zap.fill")) \(format_msats_abbrev(Int64(model.settings.default_zap_amount) * 1000))")
.font(.title)
.foregroundColor(percent == 0 ? .gray : .yellow)
.frame(width: 120)
}
Text("Zap", comment: "Text underneath the number of sats indicating that it's the amount used for zaps.")
.foregroundColor(.white)
}
Spacer()
Text(verbatim: "+")
.font(.title)
.foregroundColor(.white)
Spacer()
VStack {
HStack {
Text("\(Image("zap.fill")) \(tip_msats)")
.font(.title)
.foregroundColor(percent == 0 ? .gray : Color.yellow)
.frame(width: 120)
}
Text(verbatim: percent == 0 ? "🩶" : "💜")
.foregroundColor(.white)
}
Spacer()
}
EventProfile(damus_state: damus_state, pubkey: damus_state.pubkey, size: .small)
}
.padding(25)
}
.frame(height: 370)
}
var body: some View {
switch model.connect_state {
case .new:
@@ -44,50 +201,38 @@ struct WalletView: View {
ConnectWalletView(model: model, nav: damus_state.nav)
case .existing(let nwc):
MainWalletView(nwc: nwc)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(
action: { show_settings = true },
label: {
Image("settings")
.foregroundColor(.gray)
}
)
}
}
.onAppear() {
Task { await self.updateWalletInformation() }
model.initial_percent = settings.donation_percent
}
.refreshable {
model.resetWalletStateInformation()
await self.updateWalletInformation()
}
.sheet(isPresented: $show_settings, onDismiss: { self.show_settings = false }) {
ScrollView {
NWCSettings(damus_state: damus_state, nwc: nwc, model: model, settings: settings)
.padding(.top, 30)
.onChange(of: settings.donation_percent) { p in
let profile_txn = damus_state.profiles.lookup(id: damus_state.pubkey)
guard let profile = profile_txn?.unsafeUnownedValue else {
return
}
.presentationDragIndicator(.visible)
.presentationDetents([.large])
let prof = Profile(name: profile.name, display_name: profile.display_name, about: profile.about, picture: profile.picture, banner: profile.banner, website: profile.website, lud06: profile.lud06, lud16: profile.lud16, nip05: profile.nip05, damus_donation: p, reactions: profile.reactions)
notify(.profile_updated(.manual(pubkey: self.damus_state.pubkey, profile: prof)))
}
.onDisappear {
let profile_txn = damus_state.profiles.lookup(id: damus_state.pubkey)
guard let keypair = damus_state.keypair.to_full(),
let profile = profile_txn?.unsafeUnownedValue,
model.initial_percent != profile.damus_donation
else {
return
}
let prof = Profile(name: profile.name, display_name: profile.display_name, about: profile.about, picture: profile.picture, banner: profile.banner, website: profile.website, lud06: profile.lud06, lud16: profile.lud16, nip05: profile.nip05, damus_donation: settings.donation_percent, reactions: profile.reactions)
guard let meta = make_metadata_event(keypair: keypair, metadata: prof) else {
return
}
damus_state.postbox.send(meta)
}
}
}
@MainActor
func updateWalletInformation() async {
guard let url = damus_state.settings.nostr_wallet_connect,
let nwc = WalletConnectURL(str: url) else {
return
}
let flusher: OnFlush? = nil
let delay = 0.0 // We don't need a delay when fetching a transaction list or balance
WalletConnect.request_transaction_list(url: nwc, pool: damus_state.pool, post: damus_state.postbox, delay: delay, on_flush: flusher)
WalletConnect.request_balance_information(url: nwc, pool: damus_state.pool, post: damus_state.postbox, delay: delay, on_flush: flusher)
return
}
}
let test_wallet_connect_url = WalletConnectURL(pubkey: test_pubkey, relay: .init("wss://relay.damus.io")!, keypair: test_damus_state.keypair.to_full()!, lud16: "jb55@sendsats.com")
-203
View File
@@ -1,203 +0,0 @@
//
// ZapExplainer.swift
// damus
//
// Created by eric on 2/12/25.
//
import SwiftUI
struct ZapExplainerView: View {
@Binding var show_introduction: Bool
var nav: NavigationCoordinator
@Environment(\.colorScheme) var colorScheme
var body: some View {
ScrollView {
VStack {
Text("Get cash instantly from your followers", comment: "Feature description for receiving money instantly.")
.font(.veryLargeTitle)
.multilineTextAlignment(.center)
.padding(.top)
VStack(alignment: .leading) {
GetPaid
Gift
GiveThanks
}
WhyZaps
ScrollView(.horizontal) {
HStack(spacing: 20) {
FindWallet
LinkAccount
StartReceiving
}
.padding(5)
}
.scrollIndicators(.hidden)
Button(action: {
show_introduction = false
}) {
HStack {
Text("Set up wallet", comment: "Text for button to disconnect from Nostr Wallet Connect lightning wallet.")
}
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
}
.buttonStyle(GradientButtonStyle())
.padding(.top, 30)
Button(action: {
nav.popToRoot()
}) {
HStack {
Text("Maybe later", comment: "Text for button to disconnect from Nostr Wallet Connect lightning wallet.")
}
.frame(minWidth: 300, maxWidth: .infinity, maxHeight: 18, alignment: .center)
.padding()
}
.buttonStyle(NeutralButtonStyle())
}
.padding(.bottom)
.padding(.horizontal)
}
.scrollIndicators(.never)
.background(
Image("eula-bg")
.resizable()
.blur(radius: 70)
.opacity(colorScheme == .light ? 0.6 : 1.0)
.ignoresSafeArea(),
alignment: .top
)
}
var GetPaid: some View {
self.benefitPoint(
imageName: "zap.fill",
heading: NSLocalizedString("Get paid for being you", comment: "Description for monetizing one's presence."),
description: NSLocalizedString("Setting up Zaps lets people know you're ready to start receiving money.", comment: "Information about enabling payments.")
)
}
var Gift: some View {
self.benefitPoint(
imageName: "gift",
heading: NSLocalizedString("Let your fans show their support", comment: "Heading pointing out a benefit of connecting a lightning wallet."),
description: NSLocalizedString("You drive the conversation and we want to make it easier for people to support your work beyond follows, reposts, and likes.", comment: "Text explaining the benefit of connecting a lightning wallet for content creators.")
)
}
var GiveThanks: some View {
self.benefitPoint(
imageName: "gift",
heading: NSLocalizedString("Give thanks", comment: "Heading explaining a benefit of connecting a lightning wallet."),
description: NSLocalizedString("When supporters tip with Zaps, they can add a note and we can make it easy for you to instantly reply to show your gratitude.", comment: "Description explaining a benefit of connecting a lightning wallet.")
)
}
func benefitPoint(imageName: String, heading: String, description: String) -> some View {
VStack(alignment: .leading) {
HStack(alignment: .top, spacing: 10) {
Button(action: {}, label: {
Image(imageName)
.resizable()
.frame(width: 25, height: 25)
})
.buttonStyle(NeutralButtonStyle(padding: EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10), cornerRadius: 9999))
.disabled(true)
VStack(alignment: .leading, spacing: 10) {
Text(heading)
.font(.title2)
.fontWeight(.bold)
Text(description)
.font(.body)
}
.padding(.top, 9)
}
}
.padding(.top)
}
var WhyZaps: some View {
VStack(alignment: .leading, spacing: 15) {
Text("Why add Zaps?", comment: "Heading to explain the benefits of zaps.")
.font(.title)
.fontWeight(.bold)
Text("Zaps are an easy way to support the incredible\nvoices that make up the conversation on nostr.\nHere's how it works", comment: "Describing the functional benefits of Zaps.")
.lineLimit(4)
.font(.body)
}
.padding(.top, 30)
}
var FindWallet: some View {
self.WhyAddZapsBox(
iconName: "wallet.fill",
heading: NSLocalizedString("Find a Wallet", comment: "The heading for one of the \"Why add Zaps?\" boxes"),
description: NSLocalizedString("Choose the third-party payment provider you'd like to use.", comment: "The description for one of the \"Why add Zaps?\" boxes")
)
}
var LinkAccount: some View {
self.WhyAddZapsBox(
iconName: "link",
heading: NSLocalizedString("Link your account", comment: "The heading for one of the \"Why add Zaps?\" boxes"),
description: NSLocalizedString("Link to services that support Nostr Wallet Connect like Alby, Coinos and more.", comment: "The description for one of the \"Why add Zaps?\" boxes")
)
}
var StartReceiving: some View {
self.WhyAddZapsBox(
iconName: "bitcoin",
heading: NSLocalizedString("Start receiving money", comment: "The heading for one of the \"Why add Zaps?\" boxes"),
description: NSLocalizedString("People will be able to send you cash from your profile. No money goes to Damus.", comment: "The description for one of the \"Why add Zaps?\" boxes")
)
}
func WhyAddZapsBox(iconName: String, heading: String, description: String) -> some View {
VStack(alignment: .leading, spacing: 2) {
Button(action: {}, label: {
Image(iconName)
.resizable()
.frame(width: 25, height: 25)
})
.buttonStyle(NeutralButtonStyle(padding: EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10), cornerRadius: 9999))
.disabled(true)
Text(heading)
.font(.title2)
.fontWeight(.bold)
.padding(.bottom, 2)
Text(description)
.font(.caption)
Spacer()
}
.frame(maxWidth: 175, minHeight: 175)
.padding(10)
.background(DamusColors.neutral1)
.cornerRadius(15)
.overlay(
RoundedRectangle(cornerRadius: 15)
.stroke(DamusColors.neutral1, lineWidth: 2)
)
.padding(.top, 20)
}
}
struct ZapExplainerView_Previews: PreviewProvider {
static var previews: some View {
ZapExplainerView(show_introduction: .constant(true), nav: .init())
}
}
+8 -9
View File
@@ -24,8 +24,8 @@ struct ProfileZapLinkView<Content: View>: View {
self.label = label
self.action = action
self.reactions_enabled = reactions_enabled
self.lud16 = lud16?.trimmingCharacters(in: .whitespaces)
self.lnurl = lnurl?.trimmingCharacters(in: .whitespaces)
self.lud16 = lud16
self.lnurl = lnurl
}
init(damus_state: DamusState, pubkey: Pubkey, action: ActionFunction? = nil, @ViewBuilder label: @escaping ContentViewFunction) {
@@ -36,8 +36,8 @@ struct ProfileZapLinkView<Content: View>: View {
let profile_txn = damus_state.profiles.lookup_with_timestamp(pubkey)
let record = profile_txn?.unsafeUnownedValue
self.reactions_enabled = record?.profile?.reactions ?? true
self.lud16 = record?.profile?.lud06?.trimmingCharacters(in: .whitespaces)
self.lnurl = record?.lnurl?.trimmingCharacters(in: .whitespaces)
self.lud16 = record?.profile?.lud06
self.lnurl = record?.lnurl
}
init(unownedProfileRecord: ProfileRecord?, profileModel: ProfileModel, action: ActionFunction? = nil, @ViewBuilder label: @escaping ContentViewFunction) {
@@ -46,8 +46,8 @@ struct ProfileZapLinkView<Content: View>: View {
self.action = action
self.reactions_enabled = unownedProfileRecord?.profile?.reactions ?? true
self.lud16 = unownedProfileRecord?.profile?.lud16?.trimmingCharacters(in: .whitespaces)
self.lnurl = unownedProfileRecord?.lnurl?.trimmingCharacters(in: .whitespaces)
self.lud16 = unownedProfileRecord?.profile?.lud16
self.lnurl = unownedProfileRecord?.lnurl
}
var body: some View {
@@ -81,13 +81,12 @@ struct ProfileZapLinkView<Content: View>: View {
}
}
}
.disabled(lnurl == nil && lud16 == nil)
.disabled(lnurl == nil)
}
}
#Preview {
let profile = make_test_profile()
ProfileZapLinkView(pubkey: test_pubkey, reactions_enabled: true, lud16: profile.lud16, lnurl: profile.lud06, label: { reactions_enabled, lud16, lnurl in
ProfileZapLinkView(pubkey: test_pubkey, reactions_enabled: true, lud16: make_test_profile().lud16, lnurl: "test@sendzaps.lol", label: { reactions_enabled, lud16, lnurl in
Image("zap.fill")
})
}
-2
View File
@@ -2,8 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.usernotifications.communication</key>
<true/>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.associated-domains</key>
+2 -70
View File
@@ -5,7 +5,6 @@
// Created by William Casarin on 2022-04-01.
//
import Kingfisher
import SwiftUI
import StoreKit
@@ -60,28 +59,13 @@ struct MainView: View {
}
}
func registerNotificationCategories() {
// Define the communication category
let communicationCategory = UNNotificationCategory(
identifier: "COMMUNICATION",
actions: [],
intentIdentifiers: ["INSendMessageIntent"],
options: []
)
// Register the category with the notification center
UNUserNotificationCenter.current().setNotificationCategories([communicationCategory])
}
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var state: DamusState? = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
SKPaymentQueue.default().add(StoreObserver.standard)
registerNotificationCategories()
migrateKingfisherCacheIfNeeded()
configureKingfisherCache()
return true
}
@@ -102,65 +86,13 @@ class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDele
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
Log.info("App delegate is handling a push notification", for: .push_notifications)
let userInfo = response.notification.request.content.userInfo
guard let notification = LossyLocalNotification.from_user_info(user_info: userInfo) else {
Log.error("App delegate could not decode notification information", for: .push_notifications)
return
}
Log.info("App delegate notifying the app about the received push notification", for: .push_notifications)
Task { await QueueableNotify<LossyLocalNotification>.shared.add(item: notification) }
notify(.local_notification(notification))
completionHandler()
}
private func migrateKingfisherCacheIfNeeded() {
let fileManager = FileManager.default
let defaults = UserDefaults.standard
let migrationKey = "KingfisherCacheMigrated"
// Check if migration has already been done
guard !defaults.bool(forKey: migrationKey) else { return }
// Get the default Kingfisher cache (before we override it)
let defaultCache = ImageCache.default
let oldCachePath = defaultCache.diskStorage.directoryURL.path
// New shared cache location
guard let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: Constants.DAMUS_APP_GROUP_IDENTIFIER) else { return }
let newCachePath = groupURL.appendingPathComponent(Constants.IMAGE_CACHE_DIRNAME).path
// Check if the old cache exists
if fileManager.fileExists(atPath: oldCachePath) {
do {
// Move the old cache to the new location
try fileManager.moveItem(atPath: oldCachePath, toPath: newCachePath)
print("Successfully migrated Kingfisher cache to \(newCachePath)")
} catch {
print("Failed to migrate cache: \(error)")
// Optionally, copy instead of move if you want to preserve the old cache as a fallback
do {
try fileManager.copyItem(atPath: oldCachePath, toPath: newCachePath)
print("Copied cache instead due to error")
} catch {
print("Failed to copy cache: \(error)")
}
}
}
// Mark migration as complete
defaults.set(true, forKey: migrationKey)
}
private func configureKingfisherCache() {
guard let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.DAMUS_APP_GROUP_IDENTIFIER) else {
return
}
let cachePath = groupURL.appendingPathComponent(Constants.IMAGE_CACHE_DIRNAME)
if let cache = try? ImageCache(name: "sharedCache", cacheDirectoryURL: cachePath) {
KingfisherManager.shared.cache = cache
}
}
}
class OrientationTracker: ObservableObject {
Binary file not shown.
Binary file not shown.
+1 -17
View File
@@ -66,22 +66,6 @@
<string>Imporieren</string>
</dict>
</dict>
<key>people_reposted_count</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@REPOSTED@</string>
<key>REPOSTED</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%2$@ und %1$d weiteres Profil teilten</string>
<key>other</key>
<string>%2$@ und %1$d weitere teilten</string>
</dict>
</dict>
<key>reacted_tagged_in_3</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
@@ -191,7 +175,7 @@
<key>one</key>
<string>%2$@ und %1$d weiteres Profil teilten eine Notiz, in der du markiert warst</string>
<key>other</key>
<string>%2$@ und %1$d weitere teilten eine Notiz, in der du markiert wurdest</string>
<string>%2$@ und %1$d weitere teiten eine Notiz, in der du markiert warst</string>
</dict>
</dict>
<key>reposted_your_note_3</key>
-16
View File
@@ -66,22 +66,6 @@
<string>Imports</string>
</dict>
</dict>
<key>people_reposted_count</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@REPOSTED@</string>
<key>REPOSTED</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%2$@ and %1$d other reposted</string>
<key>other</key>
<string>%2$@ and %1$d others reposted</string>
</dict>
</dict>
<key>reacted_tagged_in_3</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
File diff suppressed because it is too large Load Diff
@@ -58,9 +58,6 @@
"%@ replied to your note" : {
"comment" : "Heading for local notification indicating a new reply"
},
"%@ reposted" : {
"comment" : "Text indicating that the note was reposted (i.e. re-shared)."
},
"%@. Creating an account doesn't require a phone number, email or name. Get started right away with zero friction." : {
"comment" : "Explanation of what is done to keep personally identifiable information private. There is a heading that precedes this explanation which is a variable to this string."
},
@@ -105,15 +102,9 @@
"Accessibility" : {
"comment" : "Section header for accessibility settings"
},
"Account" : {
"comment" : "Label for the user account information with the Nostr Wallet Connect wallet provider."
},
"Account creation" : {
"comment" : "Label for Purple account creation date"
},
"Account details" : {
"comment" : "Prompt to ask user if they want to attach their Nostr Wallet Connect lightning wallet."
},
"Account private key" : {
"comment" : "Accessibility label for the private key input field"
},
@@ -156,9 +147,6 @@
"ADMIN" : {
"comment" : "Text label indicating the profile picture underneath it is the admin of the Nostr relay."
},
"Advice" : {
"comment" : "Heading for some advice text to help the user with an error"
},
"All" : {
"comment" : "Human-readable short description of the 'friends filter' when it is set to 'all'\nLabel for filter for all notifications."
},
@@ -216,9 +204,15 @@
}
}
},
"Are you lost?" : {
"comment" : "Text asking the user if they are lost in the app."
},
"Are you sure you want to clear the cache? This will free space, but images may take longer to load again." : {
"comment" : "Message explaining what it means to clear the cache, asking if user wants to proceed."
},
"Are you sure you want to connect this wallet?" : {
"comment" : "Prompt to ask user if they want to attach their Nostr Wallet Connect lightning wallet."
},
"Are you sure you want to delete all of your bookmarks?" : {
"comment" : "Alert for deleting all of the bookmarks."
},
@@ -234,15 +228,9 @@
"As part of your Damus Purple membership, you get complimentary and automated translations. Would you like to enable Damus Purple translations?\n\nTip: You can always change this later in Settings → Translations" : {
"comment" : "Message notifying the user that they get auto-translations as part of their service"
},
"Attach to any third party provider you already use." : {
"comment" : "Information text guiding users on attaching existing provider."
},
"Authenticated" : {
"comment" : "Label to display that authentication to a server has succeeded."
},
"AUTOMATIC SETUP" : {
"comment" : "Heading for the section that performs an automatic wallet connection setup."
},
"Automatic translations" : {
"comment" : "Part 1 of 2 in message 'You unlocked automatic translations' the user gets when they sign up for Damus Purple"
},
@@ -282,9 +270,6 @@
"Camera's permission was denied. You can change this in iOS settings." : {
"comment" : "Camera's permission denied error label"
},
"Cant display note" : {
"comment" : "User-visible heading for an error message indicating a note has an unknown kind or is unsupported for viewing."
},
"Cancel" : {
"comment" : "Alert button to cancel out of alert for muting a user.\nButton to cancel a repost.\nButton to cancel any interaction with the QRCode link.\nButton to cancel out of alert that creates a new mutelist.\nButton to cancel out of posting a note.\nButton to cancel out of search text entry mode.\nButton to cancel the upload.\nCancel button text for dismissing profile status settings view.\nCancel button text for dismissing updating image url.\nCancel deleting bookmarks.\nCancel deleting the user.\nCancel out of logging out the user.\nCancel out of search view.\nCancel resetting the contact list.\nText for button to cancel out of connecting Nostr Wallet Connect lightning wallet."
},
@@ -297,9 +282,6 @@
"Choose from Library" : {
"comment" : "Option to select photo from library"
},
"Choose the third-party payment provider you'd like to use." : {
"comment" : "The description for one of the \"Why add Zaps?\" boxes"
},
"Clear All" : {
"comment" : "Button for clearing bookmarks data."
},
@@ -333,8 +315,8 @@
"Connect to Alby Wallet" : {
"comment" : "Button to attach an Alby Wallet, a service that provides a Lightning wallet for zapping sats. Alby is the name of the service and should not be translated."
},
"Connect to Coinos" : {
"comment" : "Button to attach a Coinos Wallet, a service that provides a Lightning wallet for zapping sats. Coinos is the name of the service and should not be translated."
"Connect to Mutiny Wallet" : {
"comment" : "Button to attach an Mutiny Wallet, a service that provides a Lightning wallet for zapping sats. Mutiny is the name of the service and should not be translated."
},
"Connecting" : {
"comment" : "Relay status label that indicates a relay is connecting."
@@ -348,21 +330,12 @@
"Contact list has been reset" : {
"comment" : "Message indicating that the contact list was successfully reset."
},
"Contact support via DMs" : {
"comment" : "Button label to contact support from an error screen"
},
"Contact support via email at [support@damus.io](mailto:support@damus.io)" : {
"comment" : "Text to contact support via email"
},
"Content filters" : {
"comment" : "Section title for content filtering/moderation configuration."
},
"Continue" : {
"comment" : "Button to dismiss suggested users view and continue to the main app\nContinue with bookmarks.\nContinue with deleting the user.\nContinue with resetting the contact list.\nPrompt to user to continue"
},
"Conversations" : {
"comment" : "Label for filter for seeing notes and replies that involve conversations between the signed in user and the current profile."
},
"Copied" : {
"comment" : "Label indicating that a user's key was copied."
},
@@ -414,9 +387,6 @@
"Could not find user to mute..." : {
"comment" : "Alert message to indicate that the muted user could not be found."
},
"Could not parse the URL you are trying to open." : {
"comment" : "User visible error description"
},
"Create account" : {
"comment" : "Button to navigate to create account view."
},
@@ -426,12 +396,6 @@
"Create new mutelist" : {
"comment" : "Title of alert prompting the user to create a new mutelist."
},
"Create new wallet" : {
"comment" : "Button text for creating a new wallet."
},
"Current balance" : {
"comment" : "Label for displaying current wallet balance"
},
"Custom" : {
"comment" : "Dropdown option for selecting a custom translation server."
},
@@ -450,6 +414,9 @@
"Damus Purple environment" : {
"comment" : "Prompt selection of the Damus purple environment (Developer feature to switch between real/production mode to test modes)."
},
"Damus Wallet" : {
"comment" : "Title text for Damus Wallet view."
},
"DeepL (Proprietary, Higher Accuracy)" : {
"comment" : "Dropdown option for selecting DeepL as the translation service."
},
@@ -487,7 +454,7 @@
"comment" : "Text for button to disconnect from Nostr Wallet Connect lightning wallet."
},
"Dismiss" : {
"comment" : "Button to dismiss alert\nButton to dismiss error"
"comment" : "Button to dismiss alert"
},
"DMs" : {
"comment" : "Navigation title for DMs view, where DM is the English abbreviation for Direct Message.\nNavigation title for view of DMs, where DM is an English abbreviation for Direct Message.\nPicker option for DM selector for seeing only DMs that have been responded to. DM is the English abbreviation for Direct Message.\nSetting to enable DM Local Notification\nToolbar label for DMs view, where DM is the English abbreviation for Direct Message."
@@ -504,21 +471,12 @@
"Earn Money" : {
"comment" : "Heading indicating that this application allows users to earn money."
},
"Easily create a new wallet and attach it to your account." : {
"comment" : "Description for the create new wallet feature."
},
"Edit" : {
"comment" : "Button to edit user's profile.\nButton to enter edit mode for modifying the list of relays.\nEdit Button for editing profile"
},
"Edit banner image" : {
"comment" : "Accessibility label for edit banner image button"
},
"Edit Image" : {
"comment" : "Accessibility label for a button that edits an image"
},
"Edit profile picture" : {
"comment" : "Accessibility label for a button that edits a profile picture"
},
"Enable experimental Purple API support" : {
"comment" : "Developer mode setting to enable experimental Purple API support."
},
@@ -552,12 +510,6 @@
"Error syncing up push notifications preferences with the server: %@" : {
"comment" : "Error label shown when system tries to sync up notification preferences to the push notification server but something fails"
},
"Error uploading profile image. Please check your internet connection and try again. If error persists, please contact Damus support (support@damus.io)." : {
"comment" : "Error label when uploading profile image"
},
"Error while cropping image" : {
"comment" : "Heading on cropping error page"
},
"Error, please try again" : {
"comment" : "Text on QR code camera view indicating an error"
},
@@ -582,9 +534,6 @@
"Expiry date" : {
"comment" : "Label for Purple subscription expiry date"
},
"Failed to generate media for upload. Please try again. If error persists, please contact Damus support at support@damus.io" : {
"comment" : "Error label forming media for upload after user crops the image."
},
"Failed to get push notification preferences from the server" : {
"comment" : "Error label indicating about a failure in fetching notification preferences"
},
@@ -594,9 +543,6 @@
"Failed to parse" : {
"comment" : "NostrScript error message when it fails to parse a script."
},
"Find a Wallet" : {
"comment" : "The heading for one of the \"Why add Zaps?\" boxes"
},
"First Aid" : {
"comment" : "Navigation title for first aid settings and tools\nSection header for first aid tools and settings"
},
@@ -688,15 +634,6 @@
"Get API Key with BTC/Lightning" : {
"comment" : "Button to navigate to nokyctranslate website to get a translation API key.\nButton to navigate to translate.nostr.wine to get a translation API key."
},
"Get cash instantly from your followers" : {
"comment" : "Feature description for receiving money instantly."
},
"Get paid for being you" : {
"comment" : "Description for monetizing one's presence."
},
"Give thanks" : {
"comment" : "Heading explaining a benefit of connecting a lightning wallet."
},
"Go to the app" : {
"comment" : "Button label giving the user the option to go to the app after sharing content"
},
@@ -742,14 +679,11 @@
"Illegal Content" : {
"comment" : "Description of report type for illegal content."
},
"Image is setup" : {
"comment" : "Accessibility value on image control"
},
"Image uploader" : {
"comment" : "Prompt selection of user's image uploader"
},
"Image URL" : {
"comment" : "Label for image url text field\nOption to enter a url"
"comment" : "Option to enter a url"
},
"Images" : {
"comment" : "Section title for images configuration."
@@ -778,9 +712,6 @@
"Invalid Tip Address" : {
"comment" : "Title of alerting as invalid tip address."
},
"Invalid URL" : {
"comment" : "Error label when user enters an invalid URL"
},
"It seems that you already have a translation service configured. Would you like to switch to Damus Purple as your translator?" : {
"comment" : "Confirmation dialog question asking users if they want their translation settings to be automatically switched to the Damus Purple translation service"
},
@@ -790,18 +721,12 @@
"Keys" : {
"comment" : "Navigation title for managing keys.\nSettings section for managing keys"
},
"Latest transactions" : {
"comment" : "Heading for latest wallet transactions list"
},
"Learn more about the features" : {
"comment" : "Label for a link to the Damus website, to allow the user to learn more about the features of Purple"
},
"Left Handed" : {
"comment" : "Moves the post button to the left side of the screen"
},
"Let your fans show their support" : {
"comment" : "Heading pointing out a benefit of connecting a lightning wallet."
},
"LibreTranslate (Open Source)" : {
"comment" : "Dropdown option for selecting LibreTranslate as the translation service."
},
@@ -817,21 +742,12 @@
"Likes" : {
"comment" : "Setting to enable Like Local Notification"
},
"Link to services that support Nostr Wallet Connect like Alby, Coinos and more." : {
"comment" : "The description for one of the \"Why add Zaps?\" boxes"
},
"Link your account" : {
"comment" : "The heading for one of the \"Why add Zaps?\" boxes"
},
"LIVE" : {
"comment" : "Text indicator that the video is a livestream."
},
"Load media" : {
"comment" : "Button to show media in note."
},
"Loading thread" : {
"comment" : "Accessibility label for the thread view when it is loading"
},
"Local" : {
"comment" : "Option for notification mode setting: Local notification mode"
},
@@ -865,12 +781,6 @@
"Manage subscription" : {
"comment" : "Button to take user to manage Damus Purple subscription"
},
"MANUAL SETUP" : {
"comment" : "Label for manual wallet setup."
},
"Maybe later" : {
"comment" : "Text for button to disconnect from Nostr Wallet Connect lightning wallet."
},
"Media previews" : {
"comment" : "Setting to show media"
},
@@ -901,11 +811,11 @@
"Mute Hashtag" : {
"comment" : "Label represnting a button that the user can tap to mute a given hashtag so they don't see it in their feed anymore."
},
"Mute/Block user" : {
"comment" : "Context menu option for muting/blocking users."
"Mute user" : {
"comment" : "Context menu option for muting users."
},
"Mute/Block User" : {
"comment" : "Title of alert for muting/blocking a user."
"Mute User" : {
"comment" : "Title of alert for muting a user."
},
"Muted" : {
"comment" : "Navigation title of view to see list of muted users & phrases.\nSidebar menu label for muted users view."
@@ -946,9 +856,6 @@
"No content available to share" : {
"comment" : "Title indicating that there was no available content to share"
},
"No image is currently setup" : {
"comment" : "Accessibility value on image control"
},
"No logs to display" : {
"comment" : "Label to indicate that there are no developer mode logs available to be displayed on the screen"
},
@@ -958,15 +865,9 @@
"No one will see that you zapped" : {
"comment" : "Description of anonymous zap type where the zap is sent anonymously and does not identify the user who sent it."
},
"No profile picture is currently setup" : {
"comment" : "Accessibility value on profile picture image control"
},
"No results" : {
"comment" : "A label indicating that note search resulted in no results"
},
"No transactions yet" : {
"comment" : "Message shown when no transactions are available"
},
"No zaps will be sent, only a lightning payment." : {
"comment" : "Description of non-zap type where sats are sent to the user's wallet as a regular Lightning payment, not as a zap."
},
@@ -1012,9 +913,6 @@
"Note from a %@ you've muted" : {
"comment" : "Text to indicate that what is being shown is a note which has been muted."
},
"Note not found" : {
"comment" : "Heading for the thread view in a not found error state."
},
"Note you've muted" : {
"comment" : "Label indicating note has been muted\nText to indicate that what is being shown is a note which has been muted."
},
@@ -1075,9 +973,6 @@
"OnlyZaps mode" : {
"comment" : "Setting toggle to hide reactions."
},
"Oops!" : {
"comment" : "Heading for an error screen"
},
"Open in browser" : {
"comment" : "Button to open the value found in browser."
},
@@ -1114,9 +1009,6 @@
"People" : {
"comment" : "Label for filter for seeing only people follows."
},
"People will be able to send you cash from your profile. No money goes to Damus." : {
"comment" : "The description for one of the \"Why add Zaps?\" boxes"
},
"Permanently Delete Account" : {
"comment" : "Alert for deleting the users account.\nSection title for deleting the user"
},
@@ -1126,18 +1018,6 @@
"Please choose relays from the list below to filter the current feed:" : {
"comment" : "Instructions on how to filter a specific timeline feed by choosing relay servers to filter on."
},
"Please contact the person who provided the link, and ask for another link." : {
"comment" : "User-visible tip on what to do if a link contains a deprecated \"nrelay\" reference."
},
"Please double-check the checkout web page, or go to the Side Menu → \"Purple\" to check your account status. If you have already paid, but still don't see your account active, please save the URL of the checkout page where you came from, contact our support, and give us the URL to help you with this issue." : {
"comment" : "User-facing tips on what to do if a Purple welcome link doesn't work"
},
"Please try again, check the URL for typos, or contact support for further help." : {
"comment" : "User visible error tips"
},
"Please try opening this content on another Nostr app that supports this type of content." : {
"comment" : "User-visible advice on what to do if they see the error indicating a note has an unknown kind or is unsupported for viewing."
},
"Point your camera to a QR code…" : {
"comment" : "Text on QR code camera view instructing user to point to QR code"
},
@@ -1180,9 +1060,6 @@
"Profile action sheets allow you to follow, zap, or DM profiles more quickly without having to view their full profile" : {
"comment" : "Section footer clarifying what the profile action sheet feature does"
},
"Profile picture is setup" : {
"comment" : "Accessibility value on profile picture image control"
},
"Profiles" : {
"comment" : "Section title for profile view configuration."
},
@@ -1305,6 +1182,9 @@
"Repost or quote this note" : {
"comment" : "Accessibility label for repost/quote button"
},
"Reposted" : {
"comment" : "Text indicating that the note was reposted (i.e. re-shared)."
},
"Reposted by %@" : {
"comment" : "Reposted by heading in local notification"
},
@@ -1323,9 +1203,6 @@
"Retry" : {
"comment" : "Button to retry completing account creation after an error occurred."
},
"Routing" : {
"comment" : "Label indicating the routing address for Nostr Wallet Connect payments. In other words, the relay used by the NWC wallet provider"
},
"Run" : {
"comment" : "Button that runs a NostrScript."
},
@@ -1338,9 +1215,6 @@
"Satoshi Nakamoto" : {
"comment" : "Name of Bitcoin creator(s)."
},
"SATS" : {
"comment" : "Abbreviation for Satoshis, smallest bitcoin unit"
},
"Save" : {
"comment" : "Button for saving profile.\nButton to save key, complete account creation, and start using the app."
},
@@ -1359,9 +1233,6 @@
"Save your login info?" : {
"comment" : "Ask user if they want to save their account information."
},
"Saved" : {
"comment" : "Small label indicating that the user's draft has been saved to storage."
},
"Scan a user's pubkey" : {
"comment" : "Text to prompt scanning a QR code of a user's pubkey to open their profile."
},
@@ -1398,6 +1269,9 @@
"Secret Account Login Key" : {
"comment" : "Section title for user's secret account login key."
},
"Securely connect your Damus app to your wallet using Nostr Wallet Connect" : {
"comment" : "Text to prompt user to connect their wallet using 'Nostr Wallet Connect'."
},
"Select a Lightning wallet" : {
"comment" : "Title of section for selecting a Lightning wallet to pay a Lightning invoice."
},
@@ -1422,18 +1296,9 @@
"Service" : {
"comment" : "Prompt selection of translation service provider."
},
"Set up wallet" : {
"comment" : "Text for button to disconnect from Nostr Wallet Connect lightning wallet."
},
"Setting up Zaps lets people know you're ready to start receiving money." : {
"comment" : "Information about enabling payments."
},
"Settings" : {
"comment" : "Navigation title for Settings view.\nSidebar menu label for accessing the app settings"
},
"Setup Wallet" : {
"comment" : "Heading for Nostr Wallet Connect setup screen\nHeading for wallet setup confirmation screen"
},
"Share" : {
"comment" : "Button to share a note\nButton to share an image.\nButton to share the link to a profile.\nSave button text for saving profile status settings."
},
@@ -1473,15 +1338,15 @@
"Show only from users you follow" : {
"comment" : "Setting to Show notifications only associated to users your follow"
},
"Show only preferred languages on Universe feed" : {
"comment" : "Toggle to show notes that are only in the device's preferred languages on the Universe feed and hide notes that are in other languages."
},
"Show profile action sheets" : {
"comment" : "Setting to show profile action sheets when clicking on a user's profile picture"
},
"Show wallet selector" : {
"comment" : "Toggle to show or hide selection of wallet."
},
"Shows options to edit the image" : {
"comment" : "Accessibility hint for a button that edits an image"
},
"Side menu" : {
"comment" : "Accessibility label for the side menu button at the topbar"
},
@@ -1515,9 +1380,6 @@
"Someone zapped you ⚡️" : {
"comment" : "Title label for a push notification where someone zapped the user"
},
"Sorry, but for some reason there has been an issue while trying to crop this image. Please try again later. If the error persists, please contact [Damus support](mailto:support@damus.io)" : {
"comment" : "Cropping error message"
},
"Sorry, this QR code looks incompatible with Damus. Please try another one." : {
"comment" : "Text on QR code camera view telling the user a QR is incompatible"
},
@@ -1530,9 +1392,6 @@
"Staging (for dev builds)" : {
"comment" : "Label indicating the staging environment for Push notification functionality"
},
"Start receiving money" : {
"comment" : "The heading for one of the \"Why add Zaps?\" boxes"
},
"Staying humble..." : {
"comment" : "Placeholder as an example of what the user could set as their profile status."
},
@@ -1623,6 +1482,9 @@
"This user cannot be zapped because they have not configured zaps on their account yet. Time to orange-pill?" : {
"comment" : "Comment explaining why a user cannot be zapped."
},
"Thread" : {
"comment" : "Navigation bar title for note thread."
},
"Threads" : {
"comment" : "Section header title for a list of threads that are muted."
},
@@ -1662,9 +1524,6 @@
"Truncate timeline text" : {
"comment" : "Setting to truncate text in timeline"
},
"Try checking the link again, your internet connection, or contact the person who provided you the link for help." : {
"comment" : "Tips on what to do if a note cannot be found."
},
"Type %@ to delete" : {
"comment" : "Text field prompt asking user to type DELETE in all caps to confirm that they want to proceed with deleting their account."
},
@@ -1674,9 +1533,6 @@
"Unable to find a QR Code" : {
"comment" : "Alert message letting user know a QR Code was not found."
},
"Undistract mode" : {
"comment" : "Developer mode setting to scramble text and images to avoid distractions during development."
},
"Unfollow" : {
"comment" : "Button to unfollow a user."
},
@@ -1689,9 +1545,6 @@
"Universe 🛸" : {
"comment" : "Toolbar label for the universal view where notes from all connected relay servers appear."
},
"Unknown" : {
"comment" : "A name label for an unknown user"
},
"Unmute" : {
"comment" : "Button to unmute a profile."
},
@@ -1713,9 +1566,6 @@
"URL" : {
"comment" : "Custom URL host for Damus Purple testing\nCustom URL host for Damus push notification testing\nExample URL to LibreTranslate server"
},
"Use existing" : {
"comment" : "Button text to use an existing wallet."
},
"User has been muted" : {
"comment" : "Alert message that informs a user was muted."
},
@@ -1758,9 +1608,18 @@
"Visit the Damus website on a web browser to manage billing" : {
"comment" : "Instruction on how to manage billing externally"
},
"Wake up, %@" : {
"comment" : "Text telling the user to wake up, where the argument is their display name."
},
"Wallet" : {
"comment" : "Navigation title for Wallet view\nNavigation title for attaching Nostr Wallet Connect lightning wallet.\nSidebar menu label for Wallet view.\nTitle for section in zap settings that controls the Lightning wallet selection."
},
"Wallet Address" : {
"comment" : "Label text indicating that below it is the wallet address."
},
"Wallet Relay" : {
"comment" : "Label text indicating that below it is the information about the wallet relay."
},
"WARNING:\n\nThis will reset your contact list, including the list of everyone you follow and the list of all relays you usually connect to. ONLY PROCEED IF YOU ARE SURE YOU HAVE LOST YOUR CONTACT LIST BEYOND RECOVERABILITY." : {
"comment" : "Alert for resetting the user's contact list."
},
@@ -1770,12 +1629,6 @@
"We did not detect any issues that we can automatically fix for you. If you are having issues, please contact Damus support: [support@damus.io](mailto:support@damus.io)" : {
"comment" : "Message indicating that no First Aid actions are available."
},
"We do not yet support viewing this type of content." : {
"comment" : "User-visible description of an error indicating a note has an unknown kind or is unsupported for viewing."
},
"We were unable to find the note you were looking for." : {
"comment" : "Text for the thread view when it is unable to find the note the user is looking for"
},
"We'll save your account key, so you won't need to enter it manually next time you log in." : {
"comment" : "Reminder to user that they should save their account information."
},
@@ -1803,15 +1656,9 @@
"What do you want to report?" : {
"comment" : "Header text to prompt user what issue they want to report."
},
"When supporters tip with Zaps, they can add a note and we can make it easy for you to instantly reply to show your gratitude." : {
"comment" : "Description explaining a benefit of connecting a lightning wallet."
},
"Who to Follow" : {
"comment" : "Title for a screen displaying suggestions of who to follow"
},
"Why add Zaps?" : {
"comment" : "Heading to explain the benefits of zaps."
},
"Words" : {
"comment" : "Section header title for a list of words that are muted."
},
@@ -1827,33 +1674,21 @@
"you" : {
"comment" : "You, in this context, is the person who controls their own social network. You is used in the context of a larger sentence that welcomes the reader to the social network that they control themself."
},
"You are dreaming..." : {
"comment" : "Text telling the user that they are dreaming."
},
"You cannot share content because you are not logged in. Please close this view, log in to your account, and try again." : {
"comment" : "Label explaining that sharing cannot proceed because the user is not logged in."
},
"You clicked on a Purple welcome link, but it does not look like the checkout is completed yet. This is likely a bug." : {
"comment" : "Error label upon continuing in the app from a Damus Purple purchase"
},
"You clicked on a Purple welcome link, but we could not find your checkout. This is likely a bug." : {
"comment" : "Error label upon continuing in the app from a Damus Purple purchase"
},
"You drive the conversation and we want to make it easier for people to support your work beyond follows, reposts, and likes." : {
"comment" : "Text explaining the benefit of connecting a lightning wallet for content creators."
},
"You have no bookmarks yet, add them in the context menu" : {
"comment" : "Text indicating that there are no bookmarks to be viewed"
},
"You opened an invalid link. The link you tried to open refers to \"nrelay\", which has been deprecated and is not supported." : {
"comment" : "User-visible error description for a user who tries to open a deprecated \"nrelay\" link."
},
"You unlocked" : {
"comment" : "Part 1 of 2 in message 'You unlocked automatic translations' the user gets when they sign up for Damus Purple"
},
"Your content is being broadcasted to the network. Please wait." : {
"comment" : "Label explaining that their content sharing action is in progress"
},
"Your draft has been saved to storage." : {
"comment" : "Accessibility label indicating that a user's post draft has been saved, meant to be read by screen reading technology."
},
"Your Name" : {
"comment" : "Label for Your Name section of user profile form."
},
@@ -1901,9 +1736,6 @@
},
"Zaps" : {
"comment" : "Label for filter for zap notifications.\nNavigation bar title for the Zaps view.\nNavigation title for zap settings.\nSection header for zap settings\nSetting to enable Zap Local Notification\nTitle for section in zap settings that controls general zap preferences."
},
"Zaps are an easy way to support the incredible\nvoices that make up the conversation on nostr.\nHere's how it works" : {
"comment" : "Describing the functional benefits of Zaps."
}
},
"version" : "1.0"
@@ -9,6 +9,6 @@
/* Privacy - Face ID Usage Description */
"NSFaceIDUsageDescription" = "Local authentication to access private key";
/* Privacy - Microphone Usage Description */
"NSMicrophoneUsageDescription" = "Damus needs access to your microphone to allow you to create video recordings that you can choose to post publicly on the network";
"NSMicrophoneUsageDescription" = "Damus needs access to your microphone for creating video recording posts";
/* Privacy - Photo Library Additions Usage Description */
"NSPhotoLibraryAddUsageDescription" = "Granting Damus access to your photos allows you to save images.";
@@ -66,22 +66,6 @@
<string>Imports</string>
</dict>
</dict>
<key>people_reposted_count</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@REPOSTED@</string>
<key>REPOSTED</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%2$@ and %1$d other reposted</string>
<key>other</key>
<string>%2$@ and %1$d others reposted</string>
</dict>
</dict>
<key>reacted_tagged_in_3</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
Binary file not shown.
Binary file not shown.
-16
View File
@@ -66,22 +66,6 @@
<string>Importok</string>
</dict>
</dict>
<key>people_reposted_count</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@REPOSTED@</string>
<key>REPOSTED</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>one</key>
<string>%2$@ és %1$d egyéb újraosztva</string>
<key>other</key>
<string>%2$@ és %1$d egyebek újraosztva</string>
</dict>
</dict>
<key>reacted_tagged_in_3</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
Binary file not shown.
Binary file not shown.
-14
View File
@@ -58,20 +58,6 @@
<string>インポート</string>
</dict>
</dict>
<key>people_reposted_count</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@REPOSTED@</string>
<key>REPOSTED</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>d</string>
<key>other</key>
<string>%2$@と他%1$d人がリポストしました</string>
</dict>
</dict>
<key>reacted_tagged_in_3</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More