|
| 1 | +import 'package:core/core.dart'; |
| 2 | +import 'package:flutter_news_app_api_server_full_source_code/src/database/migration.dart'; |
| 3 | +import 'package:logging/logging.dart'; |
| 4 | +import 'package:mongo_dart/mongo_dart.dart'; |
| 5 | + |
| 6 | +/// {@template unify_interests_and_remote_config} |
| 7 | +/// A migration to refactor the database schema by unifying `SavedFilter` and |
| 8 | +/// `PushNotificationSubscription` into a single `Interest` model. |
| 9 | +/// |
| 10 | +/// This migration performs two critical transformations: |
| 11 | +/// |
| 12 | +/// 1. **User Preferences Transformation:** It iterates through all |
| 13 | +/// `user_content_preferences` documents. For each user, it reads the |
| 14 | +/// legacy `savedFilters` and `notificationSubscriptions` arrays, converts |
| 15 | +/// them into the new `Interest` format, and merges them. It then saves |
| 16 | +/// this new list to an `interests` field and removes the old, obsolete |
| 17 | +/// arrays. |
| 18 | +/// |
| 19 | +/// 2. **Remote Config Transformation:** It updates the single `remote_configs` |
| 20 | +/// document by adding the new `interestConfig` field with default limits |
| 21 | +/// and removing the now-deprecated limit fields from `userPreferenceConfig` |
| 22 | +/// and `pushNotificationConfig`. |
| 23 | +/// {@endtemplate} |
| 24 | +class UnifyInterestsAndRemoteConfig extends Migration { |
| 25 | + /// {@macro unify_interests_and_remote_config} |
| 26 | + UnifyInterestsAndRemoteConfig() |
| 27 | + : super( |
| 28 | + prDate: '20251111000000', |
| 29 | + prId: '74', |
| 30 | + prSummary: |
| 31 | + 'This pull request introduces a significant new Interest feature, designed to enhance user personalization by unifying content filtering and notification subscriptions.', |
| 32 | + ); |
| 33 | + |
| 34 | + @override |
| 35 | + Future<void> up(Db db, Logger log) async { |
| 36 | + log.info('Starting migration: UnifyInterestsAndRemoteConfig.up'); |
| 37 | + |
| 38 | + // --- 1. Migrate user_content_preferences --- |
| 39 | + log.info('Migrating user_content_preferences collection...'); |
| 40 | + final preferencesCollection = db.collection('user_content_preferences'); |
| 41 | + final allPreferences = await preferencesCollection.find().toList(); |
| 42 | + |
| 43 | + for (final preferenceDoc in allPreferences) { |
| 44 | + final userId = (preferenceDoc['_id'] as ObjectId).oid; |
| 45 | + log.finer('Processing preferences for user: $userId'); |
| 46 | + |
| 47 | + final savedFilters = |
| 48 | + (preferenceDoc['savedFilters'] as List<dynamic>? ?? []) |
| 49 | + .map((e) => e as Map<String, dynamic>) |
| 50 | + .toList(); |
| 51 | + final notificationSubscriptions = |
| 52 | + (preferenceDoc['notificationSubscriptions'] as List<dynamic>? ?? []) |
| 53 | + .map((e) => e as Map<String, dynamic>) |
| 54 | + .toList(); |
| 55 | + |
| 56 | + if (savedFilters.isEmpty && notificationSubscriptions.isEmpty) { |
| 57 | + log.finer('User $userId has no legacy data to migrate. Skipping.'); |
| 58 | + continue; |
| 59 | + } |
| 60 | + |
| 61 | + // Use a map to merge filters and subscriptions with the same criteria. |
| 62 | + final interestMap = <String, Interest>{}; |
| 63 | + |
| 64 | + // Process saved filters |
| 65 | + for (final filter in savedFilters) { |
| 66 | + final criteriaData = filter['criteria']; |
| 67 | + if (criteriaData is! Map<String, dynamic>) { |
| 68 | + log.warning( |
| 69 | + 'User $userId has a malformed savedFilter with missing or invalid ' |
| 70 | + '"criteria". Skipping this filter.', |
| 71 | + ); |
| 72 | + continue; |
| 73 | + } |
| 74 | + |
| 75 | + final criteria = InterestCriteria.fromJson(criteriaData); |
| 76 | + final key = _generateCriteriaKey(criteria); |
| 77 | + |
| 78 | + interestMap.update( |
| 79 | + key, |
| 80 | + (existing) => existing.copyWith(isPinnedFeedFilter: true), |
| 81 | + ifAbsent: () => Interest( |
| 82 | + id: ObjectId().oid, |
| 83 | + userId: userId, |
| 84 | + name: filter['name'] as String, |
| 85 | + criteria: criteria, |
| 86 | + isPinnedFeedFilter: true, |
| 87 | + deliveryTypes: const {}, |
| 88 | + ), |
| 89 | + ); |
| 90 | + } |
| 91 | + |
| 92 | + // Process notification subscriptions |
| 93 | + for (final subscription in notificationSubscriptions) { |
| 94 | + final criteriaData = subscription['criteria']; |
| 95 | + if (criteriaData is! Map<String, dynamic>) { |
| 96 | + log.warning( |
| 97 | + 'User $userId has a malformed notificationSubscription with ' |
| 98 | + 'missing or invalid "criteria". Skipping this subscription.', |
| 99 | + ); |
| 100 | + continue; |
| 101 | + } |
| 102 | + |
| 103 | + final criteria = InterestCriteria.fromJson(criteriaData); |
| 104 | + final key = _generateCriteriaKey(criteria); |
| 105 | + final deliveryTypes = |
| 106 | + (subscription['deliveryTypes'] as List<dynamic>? ?? []) |
| 107 | + .map((e) { |
| 108 | + try { |
| 109 | + return PushNotificationSubscriptionDeliveryType.values |
| 110 | + .byName(e as String); |
| 111 | + } catch (_) { |
| 112 | + log.warning( |
| 113 | + 'User $userId has a notificationSubscription with an invalid deliveryType: "$e". Skipping this type.', |
| 114 | + ); |
| 115 | + return null; |
| 116 | + } |
| 117 | + }) |
| 118 | + .whereType<PushNotificationSubscriptionDeliveryType>() |
| 119 | + .toSet(); |
| 120 | + |
| 121 | + interestMap.update( |
| 122 | + key, |
| 123 | + (existing) => existing.copyWith( |
| 124 | + deliveryTypes: {...existing.deliveryTypes, ...deliveryTypes}, |
| 125 | + ), |
| 126 | + ifAbsent: () => Interest( |
| 127 | + id: ObjectId().oid, |
| 128 | + userId: userId, |
| 129 | + name: subscription['name'] as String, |
| 130 | + criteria: criteria, |
| 131 | + isPinnedFeedFilter: false, |
| 132 | + deliveryTypes: deliveryTypes, |
| 133 | + ), |
| 134 | + ); |
| 135 | + } |
| 136 | + |
| 137 | + final newInterests = interestMap.values.map((i) => i.toJson()).toList(); |
| 138 | + |
| 139 | + await preferencesCollection.updateOne( |
| 140 | + where.id(preferenceDoc['_id'] as ObjectId), |
| 141 | + modify |
| 142 | + .set('interests', newInterests) |
| 143 | + .unset('savedFilters') |
| 144 | + .unset('notificationSubscriptions'), |
| 145 | + ); |
| 146 | + log.info( |
| 147 | + 'Successfully migrated ${newInterests.length} interests for user $userId.', |
| 148 | + ); |
| 149 | + } |
| 150 | + |
| 151 | + // --- 2. Migrate remote_configs --- |
| 152 | + log.info('Migrating remote_configs collection...'); |
| 153 | + final remoteConfigCollection = db.collection('remote_configs'); |
| 154 | + final remoteConfig = await remoteConfigCollection.findOne(); |
| 155 | + |
| 156 | + if (remoteConfig != null) { |
| 157 | + // Use the default from the core package fixtures as the base. |
| 158 | + final defaultConfig = remoteConfigsFixturesData.first.interestConfig; |
| 159 | + |
| 160 | + await remoteConfigCollection.updateOne( |
| 161 | + where.id(remoteConfig['_id'] as ObjectId), |
| 162 | + modify |
| 163 | + .set('interestConfig', defaultConfig.toJson()) |
| 164 | + .unset('userPreferenceConfig.guestSavedFiltersLimit') |
| 165 | + .unset('userPreferenceConfig.authenticatedSavedFiltersLimit') |
| 166 | + .unset('userPreferenceConfig.premiumSavedFiltersLimit') |
| 167 | + .unset('pushNotificationConfig.deliveryConfigs'), |
| 168 | + ); |
| 169 | + log.info('Successfully migrated remote_configs document.'); |
| 170 | + } else { |
| 171 | + log.warning('Remote config document not found. Skipping migration.'); |
| 172 | + } |
| 173 | + |
| 174 | + log.info('Migration UnifyInterestsAndRemoteConfig.up completed.'); |
| 175 | + } |
| 176 | + |
| 177 | + @override |
| 178 | + Future<void> down(Db db, Logger log) async { |
| 179 | + log.warning( |
| 180 | + 'Executing "down" for UnifyInterestsAndRemoteConfig. ' |
| 181 | + 'This is a destructive operation and may result in data loss.', |
| 182 | + ); |
| 183 | + |
| 184 | + // --- 1. Revert user_content_preferences --- |
| 185 | + final preferencesCollection = db.collection('user_content_preferences'); |
| 186 | + await preferencesCollection.updateMany( |
| 187 | + where.exists('interests'), |
| 188 | + modify |
| 189 | + .unset('interests') |
| 190 | + .set('savedFilters', <dynamic>[]) |
| 191 | + .set('notificationSubscriptions', <dynamic>[]), |
| 192 | + ); |
| 193 | + log.info( |
| 194 | + 'Removed "interests" field and re-added empty legacy fields to all ' |
| 195 | + 'user_content_preferences documents.', |
| 196 | + ); |
| 197 | + |
| 198 | + // --- 2. Revert remote_configs --- |
| 199 | + final remoteConfigCollection = db.collection('remote_configs'); |
| 200 | + await remoteConfigCollection.updateMany( |
| 201 | + where.exists('interestConfig'), |
| 202 | + modify |
| 203 | + .unset('interestConfig') |
| 204 | + .set('userPreferenceConfig.guestSavedFiltersLimit', 5) |
| 205 | + .set('userPreferenceConfig.authenticatedSavedFiltersLimit', 20) |
| 206 | + .set('userPreferenceConfig.premiumSavedFiltersLimit', 50) |
| 207 | + .set( |
| 208 | + 'pushNotificationConfig.deliveryConfigs', |
| 209 | + { |
| 210 | + 'breakingOnly': true, |
| 211 | + 'dailyDigest': true, |
| 212 | + 'weeklyRoundup': true, |
| 213 | + }, |
| 214 | + ), |
| 215 | + ); |
| 216 | + log.info('Reverted remote_configs document to legacy structure.'); |
| 217 | + |
| 218 | + log.info('Migration UnifyInterestsAndRemoteConfig.down completed.'); |
| 219 | + } |
| 220 | + |
| 221 | + /// Generates a stable, sorted key from interest criteria to identify |
| 222 | + /// duplicates. |
| 223 | + String _generateCriteriaKey(InterestCriteria criteria) { |
| 224 | + final topics = criteria.topics.map((t) => t.id).toList()..sort(); |
| 225 | + final sources = criteria.sources.map((s) => s.id).toList()..sort(); |
| 226 | + final countries = criteria.countries.map((c) => c.id).toList()..sort(); |
| 227 | + return 't:${topics.join(',')};s:${sources.join(',')};c:${countries.join(',')}'; |
| 228 | + } |
| 229 | +} |
0 commit comments