|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | +import 'dart:math'; |
| 4 | + |
| 5 | +import 'package:flutter/foundation.dart'; |
| 6 | +import 'package:nostr/nostr.dart' as nostr; |
| 7 | +import 'package:shared_preferences/shared_preferences.dart'; |
| 8 | +import 'package:uuid/uuid.dart'; |
| 9 | + |
| 10 | +import '../../../shared/crypto/nip44.dart'; |
| 11 | +import '../../../shared/relay/relay.dart'; |
| 12 | +import '../read_state/read_state_time.dart'; |
| 13 | +import 'channel_sections_storage.dart'; |
| 14 | + |
| 15 | +const _uuid = Uuid(); |
| 16 | + |
| 17 | +class ChannelSectionsCrypto { |
| 18 | + final Uint8List _conversationKey; |
| 19 | + |
| 20 | + ChannelSectionsCrypto(String nsec, String pubkey) |
| 21 | + : _conversationKey = _deriveKey(nsec, pubkey); |
| 22 | + |
| 23 | + static Uint8List _deriveKey(String nsec, String pubkey) { |
| 24 | + final privkeyHex = nostr.Nip19.decode(payload: nsec).data; |
| 25 | + return getConversationKey(privkeyHex, pubkey); |
| 26 | + } |
| 27 | + |
| 28 | + String encrypt(String plaintext) => nip44Encrypt(_conversationKey, plaintext); |
| 29 | + |
| 30 | + String decrypt(String ciphertext) => |
| 31 | + nip44Decrypt(_conversationKey, ciphertext); |
| 32 | +} |
| 33 | + |
| 34 | +class ChannelSectionsManager { |
| 35 | + final String pubkey; |
| 36 | + final ChannelSectionsStorage _storage; |
| 37 | + final ChannelSectionsCrypto _crypto; |
| 38 | + final RelaySessionNotifier? _relaySession; |
| 39 | + final SignedEventRelay? _signedEventRelay; |
| 40 | + final bool _remoteEnabled; |
| 41 | + final VoidCallback _onChanged; |
| 42 | + |
| 43 | + ChannelSectionStore _store; |
| 44 | + Timer? _publishDebounce; |
| 45 | + int _lastRemoteCreatedAt = 0; |
| 46 | + void Function()? _unsubscribe; |
| 47 | + bool _disposed = false; |
| 48 | + |
| 49 | + ChannelSectionsManager({ |
| 50 | + required this.pubkey, |
| 51 | + required SharedPreferences prefs, |
| 52 | + required ChannelSectionsCrypto crypto, |
| 53 | + required RelaySessionNotifier? relaySession, |
| 54 | + required SignedEventRelay? signedEventRelay, |
| 55 | + required bool remoteEnabled, |
| 56 | + required VoidCallback onChanged, |
| 57 | + }) : _storage = ChannelSectionsStorage(prefs), |
| 58 | + _crypto = crypto, |
| 59 | + _relaySession = relaySession, |
| 60 | + _signedEventRelay = signedEventRelay, |
| 61 | + _remoteEnabled = remoteEnabled, |
| 62 | + _onChanged = onChanged, |
| 63 | + _store = ChannelSectionsStorage(prefs).read(pubkey); |
| 64 | + |
| 65 | + ChannelSectionStore get store => _store; |
| 66 | + |
| 67 | + Future<void> initialize() async { |
| 68 | + if (_disposed) return; |
| 69 | + |
| 70 | + if (!_remoteEnabled || _relaySession == null) { |
| 71 | + _onChanged(); |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + await _fetchAndMerge(); |
| 76 | + await _startLiveSubscription(); |
| 77 | + _onChanged(); |
| 78 | + } |
| 79 | + |
| 80 | + void dispose({bool flushPending = true}) { |
| 81 | + if (_disposed) return; |
| 82 | + _disposed = true; |
| 83 | + |
| 84 | + final hadPending = _publishDebounce != null; |
| 85 | + _publishDebounce?.cancel(); |
| 86 | + _publishDebounce = null; |
| 87 | + |
| 88 | + if (flushPending && hadPending && _remoteEnabled) { |
| 89 | + unawaited(_publish(allowDisposed: true)); |
| 90 | + } |
| 91 | + |
| 92 | + _unsubscribe?.call(); |
| 93 | + _unsubscribe = null; |
| 94 | + } |
| 95 | + |
| 96 | + // ------------------------------------------------------------------------- |
| 97 | + // CRUD |
| 98 | + // ------------------------------------------------------------------------- |
| 99 | + |
| 100 | + void createSection(String name) { |
| 101 | + if (_disposed) return; |
| 102 | + final maxOrder = _store.sections.fold<int>( |
| 103 | + -1, |
| 104 | + (max, s) => s.order > max ? s.order : max, |
| 105 | + ); |
| 106 | + final section = ChannelSection( |
| 107 | + id: _uuid.v4(), |
| 108 | + name: name.trim(), |
| 109 | + order: maxOrder + 1, |
| 110 | + ); |
| 111 | + _store = ChannelSectionStore( |
| 112 | + sections: [..._store.sections, section], |
| 113 | + assignments: _store.assignments, |
| 114 | + ); |
| 115 | + _persist(); |
| 116 | + markDirty(); |
| 117 | + } |
| 118 | + |
| 119 | + void renameSection(String sectionId, String newName) { |
| 120 | + if (_disposed) return; |
| 121 | + _store = ChannelSectionStore( |
| 122 | + sections: [ |
| 123 | + for (final s in _store.sections) |
| 124 | + if (s.id == sectionId) |
| 125 | + ChannelSection(id: s.id, name: newName.trim(), order: s.order) |
| 126 | + else |
| 127 | + s, |
| 128 | + ], |
| 129 | + assignments: _store.assignments, |
| 130 | + ); |
| 131 | + _persist(); |
| 132 | + markDirty(); |
| 133 | + } |
| 134 | + |
| 135 | + void deleteSection(String sectionId) { |
| 136 | + if (_disposed) return; |
| 137 | + final updatedAssignments = Map<String, String>.from(_store.assignments) |
| 138 | + ..removeWhere((_, sid) => sid == sectionId); |
| 139 | + _store = ChannelSectionStore( |
| 140 | + sections: [ |
| 141 | + for (final s in _store.sections) |
| 142 | + if (s.id != sectionId) s, |
| 143 | + ], |
| 144 | + assignments: updatedAssignments, |
| 145 | + ); |
| 146 | + _persist(); |
| 147 | + markDirty(); |
| 148 | + } |
| 149 | + |
| 150 | + void moveSectionUp(String sectionId) { |
| 151 | + if (_disposed) return; |
| 152 | + final sorted = _sortedSections(); |
| 153 | + final idx = sorted.indexWhere((s) => s.id == sectionId); |
| 154 | + if (idx <= 0) return; |
| 155 | + _swapOrders(sorted, idx, idx - 1); |
| 156 | + markDirty(); |
| 157 | + } |
| 158 | + |
| 159 | + void moveSectionDown(String sectionId) { |
| 160 | + if (_disposed) return; |
| 161 | + final sorted = _sortedSections(); |
| 162 | + final idx = sorted.indexWhere((s) => s.id == sectionId); |
| 163 | + if (idx < 0 || idx >= sorted.length - 1) return; |
| 164 | + _swapOrders(sorted, idx, idx + 1); |
| 165 | + markDirty(); |
| 166 | + } |
| 167 | + |
| 168 | + void assignChannel(String channelId, String sectionId) { |
| 169 | + if (_disposed) return; |
| 170 | + final updated = Map<String, String>.from(_store.assignments) |
| 171 | + ..[channelId] = sectionId; |
| 172 | + _store = ChannelSectionStore( |
| 173 | + sections: _store.sections, |
| 174 | + assignments: updated, |
| 175 | + ); |
| 176 | + _persist(); |
| 177 | + markDirty(); |
| 178 | + } |
| 179 | + |
| 180 | + void unassignChannel(String channelId) { |
| 181 | + if (_disposed) return; |
| 182 | + final updated = Map<String, String>.from(_store.assignments) |
| 183 | + ..remove(channelId); |
| 184 | + _store = ChannelSectionStore( |
| 185 | + sections: _store.sections, |
| 186 | + assignments: updated, |
| 187 | + ); |
| 188 | + _persist(); |
| 189 | + markDirty(); |
| 190 | + } |
| 191 | + |
| 192 | + void markDirty() { |
| 193 | + if (!_remoteEnabled || _disposed) return; |
| 194 | + _publishDebounce?.cancel(); |
| 195 | + _publishDebounce = Timer(const Duration(seconds: 5), () { |
| 196 | + _publishDebounce = null; |
| 197 | + unawaited(_publish()); |
| 198 | + }); |
| 199 | + } |
| 200 | + |
| 201 | + // ------------------------------------------------------------------------- |
| 202 | + // Remote sync |
| 203 | + // ------------------------------------------------------------------------- |
| 204 | + |
| 205 | + Future<void> _fetchAndMerge() async { |
| 206 | + if (_relaySession == null) return; |
| 207 | + try { |
| 208 | + final events = await _relaySession.fetchHistory( |
| 209 | + NostrFilter( |
| 210 | + kinds: const [EventKind.readState], |
| 211 | + authors: [pubkey], |
| 212 | + tags: const { |
| 213 | + '#d': ['channel-sections'], |
| 214 | + }, |
| 215 | + limit: 1, |
| 216 | + ), |
| 217 | + ); |
| 218 | + _mergeEvents(events); |
| 219 | + _persist(); |
| 220 | + if (!_disposed) _onChanged(); |
| 221 | + } catch (_) { |
| 222 | + // Local state remains usable when relay is unavailable. |
| 223 | + } |
| 224 | + } |
| 225 | + |
| 226 | + Future<void> _startLiveSubscription() async { |
| 227 | + if (_relaySession == null) return; |
| 228 | + try { |
| 229 | + _unsubscribe = await _relaySession.subscribe( |
| 230 | + NostrFilter( |
| 231 | + kinds: const [EventKind.readState], |
| 232 | + authors: [pubkey], |
| 233 | + tags: const { |
| 234 | + '#d': ['channel-sections'], |
| 235 | + }, |
| 236 | + limit: 1, |
| 237 | + ), |
| 238 | + _handleIncomingEvent, |
| 239 | + ); |
| 240 | + } catch (_) { |
| 241 | + // Non-fatal — local state and history still work. |
| 242 | + } |
| 243 | + } |
| 244 | + |
| 245 | + void _mergeEvents(List<NostrEvent> events) { |
| 246 | + for (final event in events) { |
| 247 | + if (event.pubkey != pubkey) continue; |
| 248 | + _mergeEvent(event); |
| 249 | + } |
| 250 | + } |
| 251 | + |
| 252 | + void _mergeEvent(NostrEvent event) { |
| 253 | + // Only process channel-sections d-tag events. |
| 254 | + final dTag = event.getTagValue('d'); |
| 255 | + if (dTag != 'channel-sections') return; |
| 256 | + |
| 257 | + try { |
| 258 | + final plaintext = _crypto.decrypt(event.content); |
| 259 | + final parsed = jsonDecode(plaintext); |
| 260 | + if (parsed is! Map<String, dynamic>) return; |
| 261 | + |
| 262 | + final incoming = ChannelSectionStore.fromJson(parsed); |
| 263 | + |
| 264 | + // Last-write-wins: newer createdAt wins; tie-break by event ID. |
| 265 | + final isNewer = |
| 266 | + event.createdAt > _lastRemoteCreatedAt || |
| 267 | + (event.createdAt == _lastRemoteCreatedAt && |
| 268 | + event.id.compareTo(_lastRemoteEventId ?? '') > 0); |
| 269 | + |
| 270 | + if (isNewer) { |
| 271 | + _lastRemoteCreatedAt = event.createdAt; |
| 272 | + _lastRemoteEventId = event.id; |
| 273 | + _store = incoming; |
| 274 | + _persist(); |
| 275 | + } |
| 276 | + } catch (_) { |
| 277 | + // Decryption failure or parse error — keep existing state. |
| 278 | + } |
| 279 | + } |
| 280 | + |
| 281 | + String? _lastRemoteEventId; |
| 282 | + |
| 283 | + void _handleIncomingEvent(NostrEvent event) { |
| 284 | + if (_disposed) return; |
| 285 | + _mergeEvent(event); |
| 286 | + if (!_disposed) _onChanged(); |
| 287 | + } |
| 288 | + |
| 289 | + Future<void> _publish({bool allowDisposed = false}) async { |
| 290 | + if ((!allowDisposed && _disposed) || |
| 291 | + !_remoteEnabled || |
| 292 | + _signedEventRelay == null) { |
| 293 | + return; |
| 294 | + } |
| 295 | + |
| 296 | + try { |
| 297 | + final payload = jsonEncode(_store.toJson()); |
| 298 | + final ciphertext = _crypto.encrypt(payload); |
| 299 | + final createdAt = max(currentUnixSeconds(), _lastRemoteCreatedAt + 1); |
| 300 | + |
| 301 | + await _signedEventRelay.submit( |
| 302 | + kind: EventKind.readState, |
| 303 | + content: ciphertext, |
| 304 | + tags: [ |
| 305 | + ['d', 'channel-sections'], |
| 306 | + ['t', 'channel-sections'], |
| 307 | + ], |
| 308 | + createdAt: createdAt, |
| 309 | + ); |
| 310 | + |
| 311 | + _lastRemoteCreatedAt = max(_lastRemoteCreatedAt, createdAt); |
| 312 | + } catch (error) { |
| 313 | + debugPrint('[ChannelSectionsManager] publish failed: $error'); |
| 314 | + } |
| 315 | + } |
| 316 | + |
| 317 | + void _persist() { |
| 318 | + _storage.write(pubkey, _store); |
| 319 | + } |
| 320 | + |
| 321 | + List<ChannelSection> _sortedSections() { |
| 322 | + final sorted = _store.sections.toList() |
| 323 | + ..sort((a, b) => a.order.compareTo(b.order)); |
| 324 | + return sorted; |
| 325 | + } |
| 326 | + |
| 327 | + void _swapOrders(List<ChannelSection> sorted, int indexA, int indexB) { |
| 328 | + final orderA = sorted[indexA].order; |
| 329 | + final orderB = sorted[indexB].order; |
| 330 | + final idA = sorted[indexA].id; |
| 331 | + final idB = sorted[indexB].id; |
| 332 | + |
| 333 | + _store = ChannelSectionStore( |
| 334 | + sections: [ |
| 335 | + for (final s in _store.sections) |
| 336 | + if (s.id == idA) |
| 337 | + ChannelSection(id: s.id, name: s.name, order: orderB) |
| 338 | + else if (s.id == idB) |
| 339 | + ChannelSection(id: s.id, name: s.name, order: orderA) |
| 340 | + else |
| 341 | + s, |
| 342 | + ], |
| 343 | + assignments: _store.assignments, |
| 344 | + ); |
| 345 | + _persist(); |
| 346 | + } |
| 347 | +} |
0 commit comments