mirror of
https://github.com/block/buzz.git
synced 2026-11-25 10:42:26 +00:00
Lets people share screenshots, screen recordings, photos, URLs and text from any iOS app into Buzz. Today Buzz doesn't appear in the share sheet at all. - **Plain Buzz icon:** opens a new Solo chat with the items in its composer. - **Suggested conversation:** iOS offers channels and DMs the person recently sent top-level messages in. Choosing one opens that conversation with the items in its composer. When the conversation is already open, the share goes to that page's composer instead of opening a second one; if another page covers it, Buzz stays where it is and shows "Go back to that conversation to finish sharing", and the items join the draft when the person goes back. - The share extension has no UI and sends nothing. It copies the items into the app group and opens Buzz, which prefills the normal composer, so drafts, attachments, mentions and failed-send handling all stay the app's (see [the ADR](https://github.com/block/buzz/blob/mobile-share-extension-design/docs/adr/0003-share-hands-off-to-the-conversation.md)). - If the conversation already has a draft, Buzz asks whether to add the shared items to it or replace it. - A share to a conversation that's no longer available (a removed community or channel, or an unreadable share) shows "That conversation isn't available". A share while signed out shows "Sign in to share". Suggestions come from an outgoing `INSendMessageIntent` the app donates after a top-level send or a new Solo chat. The notification extension no longer donates incoming messages, so receiving a message never makes a conversation a suggestion; it still turns the push into a communication notification with the sender's avatar. Both use the same conversation identifier, now the plain community and channel IDs instead of a hash, because the extension needs to hand the identifier back to the app. | Before | After | | --- | --- | | <img alt="Share sheet without Buzz" src="https://github.com/user-attachments/assets/452fac1b-7e87-44c3-a442-099f78d0e07b" width="300"> | <img alt="Share sheet with Buzz" src="https://github.com/user-attachments/assets/54b9775d-29b4-49a5-8ab9-5fda8718a02f" width="300"> | | Buzz icon: new Solo chat | Suggested DM with a draft | After Add | | --- | --- | --- | | <img alt="New Solo chat with the shared photo" src="https://github.com/user-attachments/assets/c5da4d8b-1dd8-4e30-9e92-9dba515b3623" width="250"> | <img alt="Add to your draft prompt" src="https://github.com/user-attachments/assets/2f879f8a-3b9f-48e0-b963-2828e90dc9fe" width="250"> | <img alt="Draft with the shared link and photo added" src="https://github.com/user-attachments/assets/12832006-85c5-4447-98b5-62932552c931" width="250"> | https://github.com/user-attachments/assets/b9d380fa-e802-4ed7-89a8-592a03784c8f ### Regressions - Nothing changes for people who never use the share sheet, except that sending a top-level message or starting a Solo chat now makes one local `INInteraction.donate` call (skipped while the age restriction is on, which still purges every interaction). - Communication notifications look the same. Dropping the incoming donation removes work (and a deletion fence) from the notification extension's time budget. - The share hand-off reuses the existing deep link dispatcher. A share link is a new link type; notification and message links take the same paths as before. ### Validation - Added tests: - Dispatcher hand-off: a share to a suggested channel opens it with the shared text and files; shares to a removed community, an unlisted channel, an unknown manifest version or a missing manifest show the error and delete the pending share; share links accept only the extension's UUID ids. - Composer delivery: with an existing draft, Add appends the shared text on a new line and attaches the file, Replace clears the draft first, and the app group copy is deleted either way. - Notification presenter: specializes the notification from the intent, or falls back to the ordinary content when that throws (replaces the donation and deletion-fence tests). - Full mobile Flutter suite and BuzzPushKit Swift tests pass. - Automated app run on an iPhone 17 Pro simulator (iOS 27, dev relay test community), recorded above: sent a DM, shared a photo from Photos with the Buzz icon from a cold start (new Solo chat with the photo attached), then handed a link and photo to a DM that had a draft and chose Add. Also checked that a share's pending files are deleted after delivery. - Limitation: the iOS simulator never shows share-sheet conversation suggestions (it has no `coreduetd`), so the suggested-DM step in the video is staged by writing the same pending share and link the extension writes. Choosing a real suggestion still needs a check on a device. - Known gaps, all confined to sharing: suggestions have no avatar image yet; a suggestion for a conversation left after signing out shows "isn't available"; choosing Later in the unfinished-chat dialog keeps the share until the next new chat; and a pending share the app never receives (for example when Buzz doesn't open) stays in the app group. ### Before merge - [x] On a real iPhone, choose a suggested conversation in the share sheet and confirm the shared items open in that conversation's composer (the simulator can't show suggestions). Waived before merge: the managed test iPhone shows no share-sheet suggestions for any app, so this will be checked on a personal phone after landing. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com>
841 lines
30 KiB
Swift
841 lines
30 KiB
Swift
import CryptoKit
|
|
import Foundation
|
|
|
|
/// A verified sender profile retained for notification presentation.
|
|
public struct BuzzPushCachedProfile: Codable, Equatable, Sendable {
|
|
public let communityID: String
|
|
public let relayOrigin: String
|
|
public let pubkey: String
|
|
public let displayName: String?
|
|
public let pictureHash: String?
|
|
public let avatarPNG: Data?
|
|
public let eventID: String
|
|
public let eventCreatedAt: Int
|
|
public let cachedAt: Int
|
|
|
|
public init(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
pubkey: String,
|
|
displayName: String?,
|
|
pictureHash: String?,
|
|
avatarPNG: Data?,
|
|
eventID: String,
|
|
eventCreatedAt: Int,
|
|
cachedAt: Int
|
|
) {
|
|
self.communityID = communityID
|
|
self.relayOrigin = relayOrigin
|
|
self.pubkey = pubkey
|
|
self.displayName = displayName
|
|
self.pictureHash = pictureHash
|
|
self.avatarPNG = avatarPNG
|
|
self.eventID = eventID
|
|
self.eventCreatedAt = eventCreatedAt
|
|
self.cachedAt = cachedAt
|
|
}
|
|
}
|
|
|
|
/// Verified channel metadata retained for notification presentation.
|
|
public struct BuzzPushCachedChannel: Codable, Equatable, Sendable {
|
|
public let communityID: String
|
|
public let relayOrigin: String
|
|
public let channelID: String
|
|
public let relayMetadataPubkey: String
|
|
public let displayName: String?
|
|
/// Relay-verified Buzz channel type, when recognized.
|
|
public let channelType: String?
|
|
/// Whether relay metadata marks this as a private Solo stream (`buzz.solo` label).
|
|
public let isSolo: Bool?
|
|
/// Relay-authored creator (`P`), lowercased, when it is a valid pubkey.
|
|
public let creatorPubkey: String?
|
|
/// Exact unique-member count when bounded, or a value above the bound when oversized.
|
|
public let memberCount: Int?
|
|
/// Complete community-and-channel-scoped member digests, when within bounds.
|
|
public let memberDigests: [String]?
|
|
/// Event ID that established the cached membership snapshot.
|
|
public let membershipEventID: String?
|
|
/// Creation time of the cached membership replacement event.
|
|
public let membershipEventCreatedAt: Int?
|
|
/// Device time when the membership snapshot was cached.
|
|
public let membershipCachedAt: Int?
|
|
public let eventID: String
|
|
public let eventCreatedAt: Int
|
|
public let cachedAt: Int
|
|
|
|
public init(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
channelID: String,
|
|
relayMetadataPubkey: String,
|
|
displayName: String?,
|
|
channelType: String? = nil,
|
|
isSolo: Bool? = nil,
|
|
creatorPubkey: String? = nil,
|
|
memberCount: Int? = nil,
|
|
memberDigests: [String]? = nil,
|
|
membershipEventID: String? = nil,
|
|
membershipEventCreatedAt: Int? = nil,
|
|
membershipCachedAt: Int? = nil,
|
|
eventID: String,
|
|
eventCreatedAt: Int,
|
|
cachedAt: Int
|
|
) {
|
|
self.communityID = communityID
|
|
self.relayOrigin = relayOrigin
|
|
self.channelID = channelID
|
|
self.relayMetadataPubkey = relayMetadataPubkey
|
|
self.displayName = displayName
|
|
self.channelType = channelType
|
|
self.isSolo = isSolo
|
|
self.creatorPubkey = creatorPubkey
|
|
self.memberCount = memberCount
|
|
self.memberDigests = memberDigests
|
|
self.membershipEventID = membershipEventID
|
|
self.membershipEventCreatedAt = membershipEventCreatedAt
|
|
self.membershipCachedAt = membershipCachedAt
|
|
self.eventID = eventID
|
|
self.eventCreatedAt = eventCreatedAt
|
|
self.cachedAt = cachedAt
|
|
}
|
|
}
|
|
|
|
/// Atomic App Group snapshot shared by the app and its notification extension.
|
|
public struct BuzzPushPresentationCacheSnapshot: Codable, Equatable, Sendable {
|
|
public static let currentVersion = 1
|
|
|
|
public let version: Int
|
|
public var communities: [PushLeaseCommunity]
|
|
public var profiles: [BuzzPushCachedProfile]
|
|
public var channels: [BuzzPushCachedChannel]
|
|
|
|
public init(
|
|
version: Int = currentVersion,
|
|
communities: [PushLeaseCommunity] = [],
|
|
profiles: [BuzzPushCachedProfile] = [],
|
|
channels: [BuzzPushCachedChannel] = []
|
|
) {
|
|
self.version = version
|
|
self.communities = communities
|
|
self.profiles = profiles
|
|
self.channels = channels
|
|
}
|
|
|
|
public static func decode(_ data: Data?) -> Self {
|
|
guard let data,
|
|
let snapshot = try? JSONDecoder().decode(Self.self, from: data),
|
|
snapshot.version == currentVersion
|
|
else { return Self() }
|
|
return snapshot
|
|
}
|
|
|
|
public func profile(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
pubkey: String
|
|
) -> BuzzPushCachedProfile? {
|
|
let normalizedPubkey = pubkey.lowercased()
|
|
return profiles.first {
|
|
$0.communityID == communityID && $0.relayOrigin == relayOrigin
|
|
&& $0.pubkey == normalizedPubkey
|
|
}
|
|
}
|
|
|
|
public func channel(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
channelID: String
|
|
) -> BuzzPushCachedChannel? {
|
|
channels.first {
|
|
$0.communityID == communityID && $0.relayOrigin == relayOrigin
|
|
&& $0.channelID == channelID
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One app-provided profile update, optionally carrying a sanitized local thumbnail.
|
|
public struct BuzzPushProfileCacheUpdate: Sendable {
|
|
public let event: VerifiedNostrEvent
|
|
public let avatarPNG: Data?
|
|
|
|
public init(event: VerifiedNostrEvent, avatarPNG: Data? = nil) {
|
|
self.event = event
|
|
self.avatarPNG = avatarPNG
|
|
}
|
|
}
|
|
|
|
/// Maintains the bounded presentation snapshot. The app is the sole writer.
|
|
public final class BuzzPushPresentationCacheStore: @unchecked Sendable {
|
|
public static let fileName = "push-snapshot.json"
|
|
public static let freshnessLifetime: TimeInterval = 24 * 60 * 60
|
|
public static let maximumProfiles = 256
|
|
public static let maximumChannels = 512
|
|
public static let maximumCommunities = 64
|
|
public static let maximumMembersPerChannel = 512
|
|
public static let maximumTotalMemberDigests = 8_192
|
|
public static let maximumAvatarBytes = 64 * 1024
|
|
public static let maximumTotalAvatarBytes = 4 * 1024 * 1024
|
|
public static let maximumSnapshotBytes = 8 * 1024 * 1024
|
|
static let maximumProfileMetadataBytes = 256 * 1024
|
|
|
|
private let fileURL: URL
|
|
private let now: () -> Date
|
|
private let lock = NSLock()
|
|
|
|
public init(containerURL: URL, now: @escaping () -> Date = Date.init) {
|
|
fileURL = containerURL.appendingPathComponent(Self.fileName)
|
|
self.now = now
|
|
}
|
|
|
|
/// Replaces the app's flattened, relay-accepted community query policy.
|
|
public func replaceCommunities(_ communities: [PushLeaseCommunity]) throws {
|
|
guard communities.count <= Self.maximumCommunities else { return }
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
var snapshot = loadLocked()
|
|
snapshot.communities = communities.map { community in
|
|
var community = community
|
|
let previous = snapshot.communities.first {
|
|
$0.id == community.id && $0.pubkey == community.pubkey
|
|
&& Self.canonicalRelayOrigin($0.relayUrl) == Self.canonicalRelayOrigin(community.relayUrl)
|
|
}
|
|
community.notificationSessionID = previous?.notificationSessionID ?? UUID().uuidString
|
|
return community
|
|
}
|
|
// Account configuration is the only app-owned notification data. Discard
|
|
// presentation exports left by older app versions, including retained accounts.
|
|
snapshot.profiles.removeAll()
|
|
snapshot.channels.removeAll()
|
|
try writeLocked(snapshot)
|
|
}
|
|
|
|
/// Saves verified kind-0 events and returns the event IDs still needing thumbnails.
|
|
@discardableResult
|
|
public func updateProfiles(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
updates: [BuzzPushProfileCacheUpdate]
|
|
) throws -> Set<String> {
|
|
guard Self.isBoundedOpaqueID(communityID),
|
|
let canonicalRelayOrigin = Self.canonicalRelayOrigin(relayOrigin),
|
|
updates.count <= Self.maximumProfiles
|
|
else { return [] }
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
|
|
var snapshot = loadLocked()
|
|
let cachedAt = Int(now().timeIntervalSince1970)
|
|
var acceptedEventIDs = Set<String>()
|
|
for update in updates {
|
|
let event = update.event
|
|
guard event.kind == 0, event.hasValidIDAndSignature() else { continue }
|
|
let pubkey = event.pubkey.lowercased()
|
|
guard Self.isHexPubkey(pubkey) else { continue }
|
|
|
|
let metadata = Self.profileMetadata(event)
|
|
let index = snapshot.profiles.firstIndex {
|
|
$0.communityID == communityID && $0.relayOrigin == canonicalRelayOrigin
|
|
&& $0.pubkey == pubkey
|
|
}
|
|
let existing = index.map { snapshot.profiles[$0] }
|
|
guard
|
|
Self.shouldReplace(
|
|
existingCreatedAt: existing?.eventCreatedAt,
|
|
existingID: existing?.eventID,
|
|
candidateCreatedAt: event.createdAt,
|
|
candidateID: event.id
|
|
)
|
|
else { continue }
|
|
|
|
let suppliedAvatar = Self.normalizedAvatarPNG(update.avatarPNG)
|
|
let preservedAvatar =
|
|
existing?.pictureHash == metadata.pictureHash
|
|
? existing?.avatarPNG : nil
|
|
let entry = BuzzPushCachedProfile(
|
|
communityID: communityID,
|
|
relayOrigin: canonicalRelayOrigin,
|
|
pubkey: pubkey,
|
|
displayName: metadata.displayName,
|
|
pictureHash: metadata.pictureHash,
|
|
avatarPNG: metadata.pictureHash == nil ? nil : suppliedAvatar ?? preservedAvatar,
|
|
eventID: event.id,
|
|
eventCreatedAt: event.createdAt,
|
|
cachedAt: cachedAt
|
|
)
|
|
if let index {
|
|
snapshot.profiles[index] = entry
|
|
} else {
|
|
snapshot.profiles.append(entry)
|
|
}
|
|
acceptedEventIDs.insert(event.id)
|
|
}
|
|
|
|
Self.enforceBounds(&snapshot)
|
|
try writeLocked(snapshot)
|
|
return Set(
|
|
snapshot.profiles.compactMap { profile in
|
|
guard profile.communityID == communityID,
|
|
profile.relayOrigin == canonicalRelayOrigin,
|
|
acceptedEventIDs.contains(profile.eventID),
|
|
profile.pictureHash != nil,
|
|
profile.avatarPNG == nil
|
|
else { return nil }
|
|
return profile.eventID
|
|
})
|
|
}
|
|
|
|
/// Saves bounded relay-authorized kind-39000 metadata and kind-39002 membership snapshots.
|
|
public func updateChannels(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
relayMetadataPubkey: String,
|
|
metadataEvents: [VerifiedNostrEvent],
|
|
membershipEvents: [VerifiedNostrEvent]
|
|
) throws {
|
|
let normalizedRelayPubkey = relayMetadataPubkey.lowercased()
|
|
guard Self.isBoundedOpaqueID(communityID),
|
|
let canonicalRelayOrigin = Self.canonicalRelayOrigin(relayOrigin),
|
|
Self.isHexPubkey(normalizedRelayPubkey),
|
|
metadataEvents.count <= Self.maximumChannels,
|
|
membershipEvents.count <= Self.maximumChannels
|
|
else {
|
|
return
|
|
}
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
|
|
var snapshot = loadLocked()
|
|
let cachedAt = Int(now().timeIntervalSince1970)
|
|
for event in metadataEvents {
|
|
guard event.kind == 39_000, event.hasValidIDAndSignature(),
|
|
event.pubkey.lowercased() == normalizedRelayPubkey,
|
|
let channelID = Self.tagValue("d", in: event),
|
|
Self.isBoundedOpaqueID(channelID)
|
|
else { continue }
|
|
let index = snapshot.channels.firstIndex {
|
|
$0.communityID == communityID && $0.relayOrigin == canonicalRelayOrigin
|
|
&& $0.channelID == channelID
|
|
}
|
|
let existing = index.map { snapshot.channels[$0] }
|
|
let hasCurrentAuthority = existing?.relayMetadataPubkey == normalizedRelayPubkey
|
|
guard
|
|
!hasCurrentAuthority
|
|
|| Self.shouldReplace(
|
|
existingCreatedAt: existing?.eventCreatedAt,
|
|
existingID: existing?.eventID,
|
|
candidateCreatedAt: event.createdAt,
|
|
candidateID: event.id
|
|
)
|
|
else { continue }
|
|
|
|
let entry = BuzzPushCachedChannel(
|
|
communityID: communityID,
|
|
relayOrigin: canonicalRelayOrigin,
|
|
channelID: channelID,
|
|
relayMetadataPubkey: normalizedRelayPubkey,
|
|
displayName: Self.normalizedDisplayName(Self.tagValue("name", in: event)),
|
|
channelType: Self.normalizedChannelType(Self.tagValue("t", in: event)),
|
|
isSolo: Self.isSoloChannel(event),
|
|
creatorPubkey: Self.normalizedCreator(event),
|
|
memberCount: hasCurrentAuthority ? existing?.memberCount : nil,
|
|
memberDigests: hasCurrentAuthority ? existing?.memberDigests : nil,
|
|
membershipEventID: hasCurrentAuthority ? existing?.membershipEventID : nil,
|
|
membershipEventCreatedAt: hasCurrentAuthority
|
|
? existing?.membershipEventCreatedAt : nil,
|
|
membershipCachedAt: hasCurrentAuthority ? existing?.membershipCachedAt : nil,
|
|
eventID: event.id,
|
|
eventCreatedAt: event.createdAt,
|
|
cachedAt: cachedAt
|
|
)
|
|
if let index {
|
|
snapshot.channels[index] = entry
|
|
} else {
|
|
snapshot.channels.append(entry)
|
|
}
|
|
}
|
|
Self.enforceChannelCountBound(&snapshot)
|
|
|
|
for event in membershipEvents {
|
|
guard event.kind == 39_002, event.hasValidIDAndSignature(),
|
|
event.pubkey.lowercased() == normalizedRelayPubkey,
|
|
let channelID = Self.tagValue("d", in: event),
|
|
Self.isBoundedOpaqueID(channelID),
|
|
let membership = Self.normalizedChannelMembership(
|
|
event,
|
|
communityID: communityID,
|
|
channelID: channelID
|
|
),
|
|
let index = snapshot.channels.firstIndex(where: {
|
|
$0.communityID == communityID && $0.relayOrigin == canonicalRelayOrigin
|
|
&& $0.channelID == channelID
|
|
&& $0.relayMetadataPubkey == normalizedRelayPubkey
|
|
})
|
|
else { continue }
|
|
let existing = snapshot.channels[index]
|
|
guard
|
|
Self.shouldReplace(
|
|
existingCreatedAt: existing.membershipEventCreatedAt,
|
|
existingID: existing.membershipEventID,
|
|
candidateCreatedAt: event.createdAt,
|
|
candidateID: event.id
|
|
)
|
|
else { continue }
|
|
|
|
snapshot.channels[index] = BuzzPushCachedChannel(
|
|
communityID: existing.communityID,
|
|
relayOrigin: existing.relayOrigin,
|
|
channelID: existing.channelID,
|
|
relayMetadataPubkey: existing.relayMetadataPubkey,
|
|
displayName: existing.displayName,
|
|
channelType: existing.channelType,
|
|
isSolo: existing.isSolo,
|
|
creatorPubkey: existing.creatorPubkey,
|
|
memberCount: membership.count,
|
|
memberDigests: membership.digests,
|
|
membershipEventID: event.id,
|
|
membershipEventCreatedAt: event.createdAt,
|
|
membershipCachedAt: cachedAt,
|
|
eventID: existing.eventID,
|
|
eventCreatedAt: existing.eventCreatedAt,
|
|
cachedAt: existing.cachedAt
|
|
)
|
|
Self.enforceMemberDigestBound(&snapshot)
|
|
}
|
|
|
|
Self.enforceBounds(&snapshot)
|
|
try writeLocked(snapshot)
|
|
}
|
|
|
|
/// Attaches an app-rendered thumbnail to every verified profile with this source digest.
|
|
@discardableResult
|
|
public func updateAvatar(
|
|
communityID: String,
|
|
relayOrigin: String,
|
|
sourceURL: String,
|
|
avatarPNG: Data
|
|
) throws -> Bool {
|
|
guard Self.isBoundedOpaqueID(communityID),
|
|
let canonicalRelayOrigin = Self.canonicalRelayOrigin(relayOrigin),
|
|
let normalizedURL = Self.normalizedAvatarURL(sourceURL),
|
|
let normalizedPNG = Self.normalizedAvatarPNG(avatarPNG)
|
|
else { return false }
|
|
let pictureHash = VerifiedNostrEvent.hex(
|
|
SHA256.hash(data: Data(normalizedURL.utf8))
|
|
)
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
|
|
var snapshot = loadLocked()
|
|
var changed = false
|
|
for index in snapshot.profiles.indices
|
|
where
|
|
snapshot.profiles[index].communityID == communityID
|
|
&& snapshot.profiles[index].relayOrigin == canonicalRelayOrigin
|
|
&& snapshot.profiles[index].pictureHash == pictureHash
|
|
&& snapshot.profiles[index].avatarPNG != normalizedPNG
|
|
{
|
|
let profile = snapshot.profiles[index]
|
|
snapshot.profiles[index] = BuzzPushCachedProfile(
|
|
communityID: profile.communityID,
|
|
relayOrigin: profile.relayOrigin,
|
|
pubkey: profile.pubkey,
|
|
displayName: profile.displayName,
|
|
pictureHash: profile.pictureHash,
|
|
avatarPNG: normalizedPNG,
|
|
eventID: profile.eventID,
|
|
eventCreatedAt: profile.eventCreatedAt,
|
|
cachedAt: profile.cachedAt
|
|
)
|
|
changed = true
|
|
}
|
|
guard changed else { return false }
|
|
Self.enforceBounds(&snapshot)
|
|
try writeLocked(snapshot)
|
|
return true
|
|
}
|
|
|
|
private func loadLocked() -> BuzzPushPresentationCacheSnapshot {
|
|
guard let values = try? fileURL.resourceValues(forKeys: [.fileSizeKey]),
|
|
let fileSize = values.fileSize,
|
|
fileSize <= Self.maximumSnapshotBytes
|
|
else { return BuzzPushPresentationCacheSnapshot() }
|
|
return BuzzPushPresentationCacheSnapshot.decode(try? Data(contentsOf: fileURL))
|
|
}
|
|
|
|
private func writeLocked(_ snapshot: BuzzPushPresentationCacheSnapshot) throws {
|
|
let data = try Self.encodedBoundedSnapshot(snapshot)
|
|
try data.write(to: fileURL, options: [.atomic])
|
|
#if os(iOS)
|
|
try FileManager.default.setAttributes(
|
|
[.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication],
|
|
ofItemAtPath: fileURL.path
|
|
)
|
|
#endif
|
|
}
|
|
|
|
static func encodedBoundedSnapshot(
|
|
_ snapshot: BuzzPushPresentationCacheSnapshot
|
|
) throws -> Data {
|
|
let encoder = JSONEncoder()
|
|
encoder.outputFormatting = [.sortedKeys]
|
|
var bounded = snapshot
|
|
Self.enforceBounds(&bounded)
|
|
var data = try encoder.encode(bounded)
|
|
|
|
if data.count > Self.maximumSnapshotBytes {
|
|
var estimatedExcess = data.count - Self.maximumSnapshotBytes + 1_024
|
|
for index in bounded.profiles.indices.reversed() {
|
|
guard let avatar = bounded.profiles[index].avatarPNG else { continue }
|
|
estimatedExcess -= min(estimatedExcess, 4 * ((avatar.count + 2) / 3))
|
|
bounded.profiles[index] = Self.removingAvatar(from: bounded.profiles[index])
|
|
if estimatedExcess == 0 { break }
|
|
}
|
|
data = try encoder.encode(bounded)
|
|
}
|
|
|
|
if data.count > Self.maximumSnapshotBytes {
|
|
for index in bounded.channels.indices.reversed() {
|
|
guard bounded.channels[index].memberDigests != nil else { continue }
|
|
bounded.channels[index] = Self.removingMemberDigests(from: bounded.channels[index])
|
|
data = try encoder.encode(bounded)
|
|
if data.count <= Self.maximumSnapshotBytes { break }
|
|
}
|
|
}
|
|
|
|
while data.count > Self.maximumSnapshotBytes,
|
|
!bounded.profiles.isEmpty || !bounded.channels.isEmpty
|
|
{
|
|
let entryCount = bounded.profiles.count + bounded.channels.count
|
|
let ratio = Double(Self.maximumSnapshotBytes) / Double(data.count)
|
|
let targetCount = max(0, min(entryCount - 1, Int(Double(entryCount) * ratio * 0.95)))
|
|
Self.removeOldestEntries(entryCount - targetCount, from: &bounded)
|
|
data = try encoder.encode(bounded)
|
|
}
|
|
return data
|
|
}
|
|
|
|
static func profileMetadata(
|
|
_ event: VerifiedNostrEvent
|
|
) -> (displayName: String?, pictureHash: String?) {
|
|
guard event.content.utf8.count <= maximumProfileMetadataBytes,
|
|
let data = event.content.data(using: .utf8),
|
|
let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
|
|
else { return (nil, nil) }
|
|
let displayName =
|
|
normalizedDisplayName(object["display_name"] as? String)
|
|
?? normalizedDisplayName(object["name"] as? String)
|
|
let pictureHash = normalizedAvatarURL(object["picture"] as? String).map {
|
|
VerifiedNostrEvent.hex(SHA256.hash(data: Data($0.utf8)))
|
|
}
|
|
return (displayName, pictureHash)
|
|
}
|
|
|
|
static func normalizedDisplayName(_ value: String?) -> String? {
|
|
guard let value else { return nil }
|
|
let collapsed = value.precomposedStringWithCanonicalMapping
|
|
.components(separatedBy: .whitespacesAndNewlines)
|
|
.filter { !$0.isEmpty }
|
|
.joined(separator: " ")
|
|
guard !collapsed.isEmpty else { return nil }
|
|
var bounded = String(collapsed.prefix(128))
|
|
while bounded.utf8.count > 512, !bounded.isEmpty {
|
|
bounded.removeLast()
|
|
}
|
|
return bounded.isEmpty ? nil : bounded
|
|
}
|
|
|
|
/// Mirrors the app's Solo rule (`Channel.isSolo`): a private stream whose
|
|
/// NIP-CL labels (every `t` after the leading type) include `buzz.solo`.
|
|
static func isSoloChannel(_ event: VerifiedNostrEvent) -> Bool {
|
|
let types = event.tags.filter { $0.count >= 2 && $0[0] == "t" }.map { $0[1] }
|
|
let isPrivate =
|
|
!event.tags.contains { $0.first == "public" }
|
|
&& event.tags.contains { $0.first == "private" }
|
|
return types.first == "stream" && isPrivate && types.dropFirst().contains("buzz.solo")
|
|
}
|
|
|
|
/// The relay-authored creator `P` tag, lowercased, when it is a valid pubkey.
|
|
static func normalizedCreator(_ event: VerifiedNostrEvent) -> String? {
|
|
guard let creator = tagValue("P", in: event)?.lowercased(), isHexPubkey(creator)
|
|
else { return nil }
|
|
return creator
|
|
}
|
|
|
|
static func normalizedChannelType(_ value: String?) -> String? {
|
|
guard let value, ["stream", "forum", "dm"].contains(value) else { return nil }
|
|
return value
|
|
}
|
|
|
|
static func normalizedChannelMembership(
|
|
_ event: VerifiedNostrEvent,
|
|
communityID: String,
|
|
channelID: String
|
|
) -> (count: Int, digests: [String]?)? {
|
|
var pubkeys = Set<String>()
|
|
var exceededMemberBound = false
|
|
for tag in event.tags where tag.first == "p" {
|
|
guard tag.count >= 2 else { return nil }
|
|
let pubkey = tag[1].lowercased()
|
|
guard isHexPubkey(pubkey) else { return nil }
|
|
if !exceededMemberBound {
|
|
pubkeys.insert(pubkey)
|
|
exceededMemberBound = pubkeys.count > maximumMembersPerChannel
|
|
}
|
|
}
|
|
let digests =
|
|
exceededMemberBound
|
|
? nil
|
|
: pubkeys.map {
|
|
BuzzPushPresentationIdentity.channelMember(
|
|
communityID: communityID,
|
|
channelID: channelID,
|
|
pubkey: $0
|
|
)
|
|
}.sorted()
|
|
return (
|
|
exceededMemberBound ? maximumMembersPerChannel + 1 : pubkeys.count,
|
|
digests
|
|
)
|
|
}
|
|
|
|
static func normalizedAvatarURL(_ value: String?) -> String? {
|
|
guard let value else { return nil }
|
|
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else { return nil }
|
|
if trimmed.hasPrefix("data:image/") {
|
|
guard trimmed.utf8.count <= maximumProfileMetadataBytes,
|
|
let separator = trimmed.firstIndex(of: ","),
|
|
separator < trimmed.index(before: trimmed.endIndex)
|
|
else { return nil }
|
|
let metadata = trimmed[..<separator].lowercased()
|
|
guard metadata.hasSuffix(";base64"),
|
|
["data:image/png;base64", "data:image/jpeg;base64", "data:image/webp;base64"]
|
|
.contains(String(metadata))
|
|
else { return nil }
|
|
return trimmed
|
|
}
|
|
guard trimmed.utf8.count <= 2_048,
|
|
let components = URLComponents(string: trimmed),
|
|
components.user == nil, components.password == nil,
|
|
components.host?.isEmpty == false,
|
|
["http", "https"].contains(components.scheme?.lowercased() ?? "")
|
|
else { return nil }
|
|
return components.url?.absoluteString
|
|
}
|
|
|
|
public static func canonicalRelayOrigin(_ value: String) -> String? {
|
|
guard value.utf8.count <= 2_048,
|
|
var components = URLComponents(string: value),
|
|
components.host?.isEmpty == false,
|
|
components.user == nil,
|
|
components.password == nil,
|
|
components.query == nil,
|
|
components.fragment == nil,
|
|
components.path.isEmpty || components.path == "/"
|
|
else { return nil }
|
|
switch components.scheme?.lowercased() {
|
|
case "wss": components.scheme = "https"
|
|
case "ws": components.scheme = "http"
|
|
case "https", "http": break
|
|
default: return nil
|
|
}
|
|
components.path = ""
|
|
guard let result = components.string, result.utf8.count <= 2_048 else { return nil }
|
|
return result
|
|
}
|
|
|
|
static func tagValue(_ name: String, in event: VerifiedNostrEvent) -> String? {
|
|
event.tags.first { $0.count >= 2 && $0[0] == name }?[1]
|
|
}
|
|
|
|
private static func isBoundedOpaqueID(_ value: String) -> Bool {
|
|
!value.isEmpty && value.utf8.count <= 1_024
|
|
}
|
|
|
|
private static func isHexPubkey(_ value: String) -> Bool {
|
|
value.count == 64 && VerifiedNostrEvent.hexBytes(value)?.count == 32
|
|
}
|
|
|
|
private static func normalizedAvatarPNG(_ data: Data?) -> Data? {
|
|
guard let data, !data.isEmpty, data.count <= maximumAvatarBytes,
|
|
data.starts(with: [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
|
|
else { return nil }
|
|
return data
|
|
}
|
|
|
|
static func shouldReplace(
|
|
existingCreatedAt: Int?,
|
|
existingID: String?,
|
|
candidateCreatedAt: Int,
|
|
candidateID: String
|
|
) -> Bool {
|
|
guard let existingCreatedAt, let existingID else { return true }
|
|
return candidateCreatedAt > existingCreatedAt
|
|
|| (candidateCreatedAt == existingCreatedAt && candidateID <= existingID)
|
|
}
|
|
|
|
static func enforceBounds(_ snapshot: inout BuzzPushPresentationCacheSnapshot) {
|
|
snapshot.communities = Array(snapshot.communities.prefix(maximumCommunities))
|
|
snapshot.profiles = Array(
|
|
snapshot.profiles.sorted(by: profileNewestFirst).prefix(maximumProfiles)
|
|
)
|
|
enforceChannelCountBound(&snapshot)
|
|
enforceMemberDigestBound(&snapshot)
|
|
|
|
var avatarBytes = snapshot.profiles.reduce(0) { $0 + ($1.avatarPNG?.count ?? 0) }
|
|
guard avatarBytes > maximumTotalAvatarBytes else { return }
|
|
for index in snapshot.profiles.indices.reversed() {
|
|
guard let avatar = snapshot.profiles[index].avatarPNG else { continue }
|
|
avatarBytes -= avatar.count
|
|
let profile = snapshot.profiles[index]
|
|
snapshot.profiles[index] = removingAvatar(from: profile)
|
|
if avatarBytes <= maximumTotalAvatarBytes { break }
|
|
}
|
|
}
|
|
|
|
private static func enforceChannelCountBound(
|
|
_ snapshot: inout BuzzPushPresentationCacheSnapshot
|
|
) {
|
|
snapshot.channels = Array(
|
|
snapshot.channels.sorted(by: channelNewestFirst).prefix(maximumChannels)
|
|
)
|
|
}
|
|
|
|
private static func enforceMemberDigestBound(
|
|
_ snapshot: inout BuzzPushPresentationCacheSnapshot
|
|
) {
|
|
snapshot.channels.sort(by: channelNewestFirst)
|
|
var memberDigestCount = snapshot.channels.reduce(0) {
|
|
$0 + ($1.memberDigests?.count ?? 0)
|
|
}
|
|
guard memberDigestCount > maximumTotalMemberDigests else { return }
|
|
for index in snapshot.channels.indices.reversed() {
|
|
guard let memberDigests = snapshot.channels[index].memberDigests else { continue }
|
|
memberDigestCount -= memberDigests.count
|
|
snapshot.channels[index] = removingMemberDigests(from: snapshot.channels[index])
|
|
if memberDigestCount <= maximumTotalMemberDigests { break }
|
|
}
|
|
}
|
|
|
|
private static func removingAvatar(
|
|
from profile: BuzzPushCachedProfile
|
|
) -> BuzzPushCachedProfile {
|
|
BuzzPushCachedProfile(
|
|
communityID: profile.communityID,
|
|
relayOrigin: profile.relayOrigin,
|
|
pubkey: profile.pubkey,
|
|
displayName: profile.displayName,
|
|
pictureHash: profile.pictureHash,
|
|
avatarPNG: nil,
|
|
eventID: profile.eventID,
|
|
eventCreatedAt: profile.eventCreatedAt,
|
|
cachedAt: profile.cachedAt
|
|
)
|
|
}
|
|
|
|
private static func removingMemberDigests(
|
|
from channel: BuzzPushCachedChannel
|
|
) -> BuzzPushCachedChannel {
|
|
BuzzPushCachedChannel(
|
|
communityID: channel.communityID,
|
|
relayOrigin: channel.relayOrigin,
|
|
channelID: channel.channelID,
|
|
relayMetadataPubkey: channel.relayMetadataPubkey,
|
|
displayName: channel.displayName,
|
|
channelType: channel.channelType,
|
|
isSolo: channel.isSolo,
|
|
creatorPubkey: channel.creatorPubkey,
|
|
memberCount: channel.memberCount,
|
|
memberDigests: nil,
|
|
membershipEventID: channel.membershipEventID,
|
|
membershipEventCreatedAt: channel.membershipEventCreatedAt,
|
|
membershipCachedAt: channel.membershipCachedAt,
|
|
eventID: channel.eventID,
|
|
eventCreatedAt: channel.eventCreatedAt,
|
|
cachedAt: channel.cachedAt
|
|
)
|
|
}
|
|
|
|
private static func removeOldestEntries(
|
|
_ count: Int,
|
|
from snapshot: inout BuzzPushPresentationCacheSnapshot
|
|
) {
|
|
for _ in 0..<count {
|
|
switch (snapshot.profiles.last, snapshot.channels.last) {
|
|
case (nil, nil): return
|
|
case (.some, nil): snapshot.profiles.removeLast()
|
|
case (nil, .some): snapshot.channels.removeLast()
|
|
case (let profile?, let channel?):
|
|
let channelCachedAt = channelLastCachedAt(channel)
|
|
if profile.cachedAt < channelCachedAt
|
|
|| (profile.cachedAt == channelCachedAt && profile.eventID <= channel.eventID)
|
|
{
|
|
snapshot.profiles.removeLast()
|
|
} else {
|
|
snapshot.channels.removeLast()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static func profileNewestFirst(
|
|
_ lhs: BuzzPushCachedProfile,
|
|
_ rhs: BuzzPushCachedProfile
|
|
) -> Bool {
|
|
lhs.cachedAt == rhs.cachedAt ? lhs.eventID > rhs.eventID : lhs.cachedAt > rhs.cachedAt
|
|
}
|
|
|
|
private static func channelNewestFirst(
|
|
_ lhs: BuzzPushCachedChannel,
|
|
_ rhs: BuzzPushCachedChannel
|
|
) -> Bool {
|
|
let lhsCachedAt = channelLastCachedAt(lhs)
|
|
let rhsCachedAt = channelLastCachedAt(rhs)
|
|
return lhsCachedAt == rhsCachedAt ? lhs.eventID > rhs.eventID : lhsCachedAt > rhsCachedAt
|
|
}
|
|
|
|
private static func channelLastCachedAt(_ channel: BuzzPushCachedChannel) -> Int {
|
|
max(channel.cachedAt, channel.membershipCachedAt ?? 0)
|
|
}
|
|
}
|
|
|
|
/// Stable identifiers used only after the NSE resolves an event.
|
|
public enum BuzzPushPresentationIdentity {
|
|
/// The conversation's real community and channel IDs, which the share
|
|
/// extension hands back to the app to open that conversation. It must match
|
|
/// `shareConversationIdentifier` in the Dart app, which donates outgoing
|
|
/// messages under the same identifier.
|
|
public static func conversation(communityID: String, channelID: String) -> String {
|
|
// A JSON array of two strings always encodes.
|
|
String(decoding: try! JSONEncoder().encode([communityID, channelID]), as: UTF8.self)
|
|
}
|
|
|
|
/// Groups a conversation's notifications in Notification Center. It keeps
|
|
/// the hashed form notifications were already delivered under, so an
|
|
/// upgrade doesn't split a conversation into two groups.
|
|
public static func notificationThread(communityID: String, channelID: String) -> String {
|
|
scoped(namespace: "conversation", values: [communityID, channelID])
|
|
}
|
|
|
|
public static func sender(communityID: String, pubkey: String) -> String {
|
|
scoped(namespace: "sender", values: [communityID, pubkey.lowercased()])
|
|
}
|
|
|
|
/// Returns a stable, channel-scoped digest used for exact local membership checks.
|
|
public static func channelMember(
|
|
communityID: String,
|
|
channelID: String,
|
|
pubkey: String
|
|
) -> String {
|
|
scoped(
|
|
namespace: "channel-member",
|
|
values: [communityID, channelID, pubkey.lowercased()]
|
|
)
|
|
}
|
|
|
|
private static func scoped(namespace: String, values: [String]) -> String {
|
|
let encoded = (try? JSONEncoder().encode([namespace] + values)) ?? Data()
|
|
return "buzz.\(namespace).\(VerifiedNostrEvent.hex(SHA256.hash(data: encoded)))"
|
|
}
|
|
}
|