Compare commits

...

56 Commits

Author SHA1 Message Date
c16d8a5912 🚀 Launch 3.5.0+158 (SNAPSHOT) 2026-01-02 03:13:37 +08:00
cb9eca0424 Better fediverse content 2026-01-02 03:08:50 +08:00
d7858bab67 🐛 Fix some bugs 2026-01-02 02:34:45 +08:00
5ce590029b 👽 Fix realm chat API didn't move 2026-01-02 00:15:32 +08:00
4d92dec45c 👽 Changes to API path since sphere no longer handle messages 2026-01-01 23:59:21 +08:00
0a4e797eec ♻️ Update the way to render total counts of data in UI, close #220 2026-01-01 11:44:10 +08:00
38dffa414f ♻️ Rebuilt fetching state machine 2026-01-01 11:40:28 +08:00
eea56a742e 🐛 Fix the paging refreshing issue 2026-01-01 11:10:04 +08:00
56b7ee1d69 🐛 Fix style mismatch 2026-01-01 02:44:25 +08:00
3b564f7e7f Able to render fediverse reactions (likes) 2026-01-01 02:37:05 +08:00
93d2670063 Able to manage publisher actor 2026-01-01 02:29:27 +08:00
788165ac5b 🐛 Fix poll feedback, close #224 2026-01-01 02:02:12 +08:00
ec71125fa9 Able to render offsite media 2026-01-01 02:00:09 +08:00
adb231278c Able to render fediverse posts 2026-01-01 01:47:09 +08:00
b3ae4ab36f 👽 Update the models to match API 2025-12-31 01:43:23 +08:00
3670fe0f10 👽 Update according to AP api changes 2025-12-29 01:43:00 +08:00
bb1a5155ed ActivityPub service impl basis 2025-12-29 01:01:47 +08:00
eb90dbbc5a 🐛 Fix fab 2025-12-28 17:19:27 +08:00
a73d9f8ec0 ♻️ Improve file viewing experience 2025-12-28 15:32:00 +08:00
4c8f2e3251 🐛 Fix tabs padding cause background color missing, close #221 2025-12-28 14:10:42 +08:00
bc9d2ab8ce 🚀 Launch 3.5.0+157 2025-12-28 00:56:40 +08:00
8bc01f1b97 Optimize call 2025-12-28 00:46:21 +08:00
200cf3ec80 💄 Better call UI 2025-12-28 00:40:20 +08:00
d910d837eb 💄 Improve of the message notifier 2025-12-27 23:59:49 +08:00
56d1f14206 💄 Optimize embed links 2025-12-27 23:51:47 +08:00
a7c8a8d2ee 💄 Better screenshot of post 2025-12-27 23:41:10 +08:00
411c71dae0 💄 Improve performance and bugs 2025-12-27 23:19:58 +08:00
a8430604f9 🐛 Fix unsubscribed status cause subscription status loading infinitly 2025-12-27 23:09:52 +08:00
fe37d219b7 💄 Optimize post subscription filter card 2025-12-27 23:07:05 +08:00
bc1ebc799a 🐛 Fix sticker filter didn't apply as expected in marketplace, close #219 2025-12-27 23:02:48 +08:00
37940ef12a 🐛 Fix sticker pack detail placeholder still using v1 2025-12-27 23:02:32 +08:00
5d0469e187 🐛 Fix the is syncing state of chat shows wrongly 2025-12-27 22:55:13 +08:00
7ad7ab53a6 👔 Make request timeout not seem as device offline 2025-12-27 22:50:40 +08:00
6b0343d3dc 🐛 Fixes the lifecycle issue of chat #211 2025-12-27 22:48:55 +08:00
f541580281 🐛 Fix cursor based loading in timeline cause duplicate data due to not covered the popularity reordered case, close #213 2025-12-27 22:38:41 +08:00
6e7eedc026 💄 Optimize chat list expansion tiles and close #210 2025-12-27 22:18:21 +08:00
5d5bda7925 ♻️ Better refresh indicator 2025-12-27 22:16:00 +08:00
48e66580c3 💄 Optimize tabs design 2025-12-27 22:07:12 +08:00
836449e3f4 ♻️ Remove fab menu 2025-12-27 22:01:54 +08:00
804dd029b1 💄 Unifined layout of dashboard cards 2025-12-27 21:32:52 +08:00
e13928b03f 🍱 Sync the translations with crowdin, close #217 2025-12-27 17:10:59 +08:00
5c14236603 📝 Update english localization file 2025-12-25 19:07:55 +08:00
738ed357bf 🚀 Launch 3.5.0+156 (SNAPSHOT) 2025-12-25 00:34:59 +08:00
0876ab9b74 💄 Optimized fortune saying and dashboard clock 2025-12-25 00:29:11 +08:00
7071399cd8 💄 Reduce the space usage in account screen 2025-12-25 00:00:25 +08:00
af23df6e48 💄 Update account screen 2025-12-24 23:59:41 +08:00
e7e7cc424b 🐛 Update the image site file list, close #204 2025-12-24 23:55:46 +08:00
56ad8f60ea Default screen 2025-12-24 23:44:15 +08:00
026dd3eb01 💄 Optimize the talker route 2025-12-24 23:16:42 +08:00
72baf0ca5c 👔 Make all network status sheet dismissable 2025-12-24 23:14:18 +08:00
82cb8c7ff9 API network request status 2025-12-24 23:08:27 +08:00
a266177628 Connection sheet got API status 2025-12-24 22:58:07 +08:00
2474c7f97c 💄 Redesign the network status sheet 2025-12-24 22:43:52 +08:00
1716afd66c 💄 Better ws reconnect experience 2025-12-24 22:33:28 +08:00
78a3cd6dd2 💄 Redesigned ws indicator 2025-12-24 22:27:02 +08:00
d655840e85 👔 No longer rapid websocket reconnect (stops after 5 times in a minute) 2025-12-24 22:15:33 +08:00
165 changed files with 17899 additions and 11605 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -158,7 +158,7 @@
"checkIn": "Check In",
"checkInNone": "Not checked-in yet",
"checkInNoneHint": "Get your fortune tips and daily rewards by checking in.",
"checkInResultLevel0": "Wrost Luck",
"checkInResultLevel0": "Worst Luck",
"checkInResultLevel1": "Bad Luck",
"checkInResultLevel2": "A Normal Day",
"checkInResultLevel3": "Good Luck",
@@ -314,7 +314,6 @@
"settingsAutoTranslate": "Auto Translate",
"settingsHideBottomNav": "Hide Bottom Navigation",
"settingsSoundEffects": "Sound Effects",
"settingsAprilFoolFeatures": "April Fool Features",
"settingsEnterToSend": "Enter to Send",
"settingsTransparentAppBar": "Transparent App Bar",
"settingsCustomFonts": "Custom Fonts",
@@ -682,9 +681,9 @@
"articleAttachmentHint": "Attachments must be uploaded and inserted into the article body to be visible.",
"postVisibility": "Post Visibility",
"currentMembershipMember": "A member of Stellar Program · {}",
"membershipPriceStellar": "1200 NSP per month, level 3+ required",
"membershipPriceNova": "2400 NSP per month, level 6+ required",
"membershipPriceSupernova": "3600 NSP per month, level 9+ required",
"membershipPriceStellar": "1200 NSP per month, level 20+ required",
"membershipPriceNova": "2400 NSP per month, level 40+ required",
"membershipPriceSupernova": "3600 NSP per month, level 60+ required",
"sharePostPhoto": "Share Post as Photo",
"wouldYouLikeToNavigateToChat": "Would You like to navigate to the chat?",
"abuseReports": "Abuse Reports",
@@ -705,7 +704,7 @@
"aboutScreenDeveloperSectionTitle": "Developer",
"aboutScreenContactUsTitle": "Contact Us",
"aboutScreenLicenseTitle": "License",
"aboutScreenLicenseContent": "GNU Affero General Public License v3.0",
"aboutScreenLicenseContent": "AGPLv3",
"aboutScreenCopyright": "All rights reserved © Solsynth {}",
"aboutScreenMadeWith": "Made with ❤︎️ by Solar Network Team",
"aboutScreenFailedToLoadPackageInfo": "Failed to load package info: {error}",
@@ -1474,5 +1473,74 @@
"lotteryLastNumberSpecial": "The last selected number will be your special number.",
"lotteryMultiplierRequired": "Please enter a multiplier",
"lotteryMultiplierRange": "Multiplier must be between 1 and 10",
"dropToShare": "Drop to share"
"dropToShare": "Drop to share",
"affiliationSpell": "Affiliation Spell",
"affiliationSpellHint": "If you have an affiliation spell, enter it here.",
"friendsOnline": "Friends Online",
"createAccountAlmostThere": "Almost There",
"createAccountAlmostThereHint": "You're one step away from joining the Solar Network! Please solve the captcha puzzle shows next.",
"createAccountNotice": "Things you need to know before you create an account:",
"createAccountConfirmEmail": "After your account being created, you need go to your email inbox to active your account to get permission to use all features.",
"createAccountNoAltAccounts": "Multiple or alternative accounts are banned from the Solar Network, that will violates our terms of services.",
"createAccountAgreeTerms": "I've read these terms and agree to the terms of service.",
"createAccountProfile": "Create your profile",
"createAccountToS": "Review Terms & Conditions",
"updateYourProfileDescription": "Adjust how you looks on the Solar Network.",
"realmsDescription": "Manage realms you've joined.",
"exploreDescription": "Explore contents on the Solar Network.",
"accountDescription": "Information about your account.",
"chatDescription": "Group Chats and Direct Messages",
"connectionServerDown": "Unable to Connect",
"appSettingsDescription": "Customize your app.",
"accountSettingsDescription": "Manage your preferences on the Solar Network.",
"walletDescription": "Your source point wallet.",
"relationshipsDescription": "Friends and connections.",
"notificationsDescription": "See what's happended related to you recently.",
"settingsFestivalFeatures": "Festival Limited Features",
"categoriesAndTags": "Categories & Tags",
"webArticlesStandDescription": "Explore external sites articles.",
"aboutDescription": "Learn more about the Solar Network.",
"abuseReportsDescription": "View and manage abuse reports.",
"stickerMarketplaceDescription": "Browse and add sticker packs from the Solar Network marketplace.",
"webFeedsDescription": "Browse and subscribe to web feeds from the Solar Network.",
"discoverRealmsDescription": "Discover new realms and join them.",
"postShuffleDescription": "Shuffle posts to see the posts randomly.",
"levelingDescription": "See your leveling progress and history.",
"notableDayToday": "{} is today!",
"authSessionLogout": "Logout Session",
"authSessionLogoutHint": "Are you sure you want to logout this session? This will terminate this specific login session.",
"filesDescription": "Manage your files on the Solar Network Drive.",
"postComposeDescription": "Compose a new post",
"searchPostsDescription": "Search posts by title, content, or else.",
"accountActivationAlert": "Activate your account",
"accountActivationAlertHint": "Unactivated account may leads to various of permission issues, activate your account by clicking the link we sent to your email inbox.",
"accountActivationResendHint": "Didn't see it? Try click the button below to resend one. If you need to update your email while your account was unactivated, feel free to contact our customer service.",
"accountActivationResend": "Resend",
"ipAddress": "IP Address",
"noFurtherData": "No further data",
"searchAnything": "Search Anything...",
"tapToViewAllNotifications": "Tap to view all notifications",
"mostRecent": "Most Recent",
"noNotificationsYet": "No notifications yet",
"recentChats": "Recent Chats",
"noFeaturedPostsAvailable": "No featured posts available",
"searchChatsAndPages": "Search chats and pages...",
"dashboard": "Dashboard",
"dashboardDescription": "All your data in one place.",
"postTagsCategories": "Post Tags and Categories",
"postTagsCategoriesDescription": "Browse posts by category and tags.",
"debugLogs": "Debug Logs",
"debugLogsDescription": "View debug logs for troubleshooting.",
"pinChatRoom": "Pin Chat Room",
"pinChatRoomDescription": "Pin this chat room to the top.",
"chatRoomPinned": "Chat room pinned successfully.",
"chatRoomUnpinned": "Chat room unpinned successfully.",
"pinnedChatRoom": "Pinned Rooms",
"settingsGroupedChatList": "Grouped Chat List",
"settingsNotifyWithHaptic": "Notification with Haptic Feedback",
"settingsDashSearchEngine": "Search Engine for web",
"settingsDashSearchEngineHelper": "Use %s as the placeholder for the query.",
"settingsDefaultScreen": "Default Screen",
"notableDayChristmas": "Christmas",
"notableDayNewYear": "New Year"
}

View File

@@ -158,7 +158,7 @@
"checkIn": "Check In",
"checkInNone": "Not checked-in yet",
"checkInNoneHint": "Get your fortune tips and daily rewards by checking in.",
"checkInResultLevel0": "Wrost Luck",
"checkInResultLevel0": "Worst Luck",
"checkInResultLevel1": "Bad Luck",
"checkInResultLevel2": "A Normal Day",
"checkInResultLevel3": "Good Luck",
@@ -314,7 +314,6 @@
"settingsAutoTranslate": "Auto Translate",
"settingsHideBottomNav": "Hide Bottom Navigation",
"settingsSoundEffects": "Sound Effects",
"settingsAprilFoolFeatures": "April Fool Features",
"settingsEnterToSend": "Enter to Send",
"settingsTransparentAppBar": "Transparent App Bar",
"settingsCustomFonts": "Custom Fonts",
@@ -682,9 +681,9 @@
"articleAttachmentHint": "Attachments must be uploaded and inserted into the article body to be visible.",
"postVisibility": "Post Visibility",
"currentMembershipMember": "A member of Stellar Program · {}",
"membershipPriceStellar": "1200 NSP per month, level 3+ required",
"membershipPriceNova": "2400 NSP per month, level 6+ required",
"membershipPriceSupernova": "3600 NSP per month, level 9+ required",
"membershipPriceStellar": "1200 NSP per month, level 20+ required",
"membershipPriceNova": "2400 NSP per month, level 40+ required",
"membershipPriceSupernova": "3600 NSP per month, level 60+ required",
"sharePostPhoto": "Share Post as Photo",
"wouldYouLikeToNavigateToChat": "Would You like to navigate to the chat?",
"abuseReports": "Abuse Reports",
@@ -705,7 +704,7 @@
"aboutScreenDeveloperSectionTitle": "Developer",
"aboutScreenContactUsTitle": "Contact Us",
"aboutScreenLicenseTitle": "License",
"aboutScreenLicenseContent": "GNU Affero General Public License v3.0",
"aboutScreenLicenseContent": "AGPLv3",
"aboutScreenCopyright": "All rights reserved © Solsynth {}",
"aboutScreenMadeWith": "Made with ❤︎️ by Solar Network Team",
"aboutScreenFailedToLoadPackageInfo": "Failed to load package info: {error}",
@@ -1474,5 +1473,74 @@
"lotteryLastNumberSpecial": "The last selected number will be your special number.",
"lotteryMultiplierRequired": "Please enter a multiplier",
"lotteryMultiplierRange": "Multiplier must be between 1 and 10",
"dropToShare": "Drop to share"
"dropToShare": "Drop to share",
"affiliationSpell": "Affiliation Spell",
"affiliationSpellHint": "If you have an affiliation spell, enter it here.",
"friendsOnline": "Friends Online",
"createAccountAlmostThere": "Almost There",
"createAccountAlmostThereHint": "You're one step away from joining the Solar Network! Please solve the captcha puzzle shows next.",
"createAccountNotice": "Things you need to know before you create an account:",
"createAccountConfirmEmail": "After your account being created, you need go to your email inbox to active your account to get permission to use all features.",
"createAccountNoAltAccounts": "Multiple or alternative accounts are banned from the Solar Network, that will violates our terms of services.",
"createAccountAgreeTerms": "I've read these terms and agree to the terms of service.",
"createAccountProfile": "Create your profile",
"createAccountToS": "Review Terms & Conditions",
"updateYourProfileDescription": "Adjust how you looks on the Solar Network.",
"realmsDescription": "Manage realms you've joined.",
"exploreDescription": "Explore contents on the Solar Network.",
"accountDescription": "Information about your account.",
"chatDescription": "Group Chats and Direct Messages",
"connectionServerDown": "Unable to Connect",
"appSettingsDescription": "Customize your app.",
"accountSettingsDescription": "Manage your preferences on the Solar Network.",
"walletDescription": "Your source point wallet.",
"relationshipsDescription": "Friends and connections.",
"notificationsDescription": "See what's happended related to you recently.",
"settingsFestivalFeatures": "Festival Limited Features",
"categoriesAndTags": "Categories & Tags",
"webArticlesStandDescription": "Explore external sites articles.",
"aboutDescription": "Learn more about the Solar Network.",
"abuseReportsDescription": "View and manage abuse reports.",
"stickerMarketplaceDescription": "Browse and add sticker packs from the Solar Network marketplace.",
"webFeedsDescription": "Browse and subscribe to web feeds from the Solar Network.",
"discoverRealmsDescription": "Discover new realms and join them.",
"postShuffleDescription": "Shuffle posts to see the posts randomly.",
"levelingDescription": "See your leveling progress and history.",
"notableDayToday": "{} is today!",
"authSessionLogout": "Logout Session",
"authSessionLogoutHint": "Are you sure you want to logout this session? This will terminate this specific login session.",
"filesDescription": "Manage your files on the Solar Network Drive.",
"postComposeDescription": "Compose a new post",
"searchPostsDescription": "Search posts by title, content, or else.",
"accountActivationAlert": "Activate your account",
"accountActivationAlertHint": "Unactivated account may leads to various of permission issues, activate your account by clicking the link we sent to your email inbox.",
"accountActivationResendHint": "Didn't see it? Try click the button below to resend one. If you need to update your email while your account was unactivated, feel free to contact our customer service.",
"accountActivationResend": "Resend",
"ipAddress": "IP Address",
"noFurtherData": "No further data",
"searchAnything": "Search Anything...",
"tapToViewAllNotifications": "Tap to view all notifications",
"mostRecent": "Most Recent",
"noNotificationsYet": "No notifications yet",
"recentChats": "Recent Chats",
"noFeaturedPostsAvailable": "No featured posts available",
"searchChatsAndPages": "Search chats and pages...",
"dashboard": "Dashboard",
"dashboardDescription": "All your data in one place.",
"postTagsCategories": "Post Tags and Categories",
"postTagsCategoriesDescription": "Browse posts by category and tags.",
"debugLogs": "Debug Logs",
"debugLogsDescription": "View debug logs for troubleshooting.",
"pinChatRoom": "Pin Chat Room",
"pinChatRoomDescription": "Pin this chat room to the top.",
"chatRoomPinned": "Chat room pinned successfully.",
"chatRoomUnpinned": "Chat room unpinned successfully.",
"pinnedChatRoom": "Pinned Rooms",
"settingsGroupedChatList": "Grouped Chat List",
"settingsNotifyWithHaptic": "Notification with Haptic Feedback",
"settingsDashSearchEngine": "Search Engine for web",
"settingsDashSearchEngineHelper": "Use %s as the placeholder for the query.",
"settingsDefaultScreen": "Default Screen",
"notableDayChristmas": "Christmas",
"notableDayNewYear": "New Year"
}

View File

@@ -158,7 +158,7 @@
"checkIn": "Check In",
"checkInNone": "Not checked-in yet",
"checkInNoneHint": "Get your fortune tips and daily rewards by checking in.",
"checkInResultLevel0": "Wrost Luck",
"checkInResultLevel0": "Worst Luck",
"checkInResultLevel1": "Bad Luck",
"checkInResultLevel2": "A Normal Day",
"checkInResultLevel3": "Good Luck",
@@ -314,7 +314,6 @@
"settingsAutoTranslate": "Auto Translate",
"settingsHideBottomNav": "Hide Bottom Navigation",
"settingsSoundEffects": "Sound Effects",
"settingsAprilFoolFeatures": "April Fool Features",
"settingsEnterToSend": "Enter to Send",
"settingsTransparentAppBar": "Transparent App Bar",
"settingsCustomFonts": "Custom Fonts",
@@ -682,9 +681,9 @@
"articleAttachmentHint": "Attachments must be uploaded and inserted into the article body to be visible.",
"postVisibility": "Post Visibility",
"currentMembershipMember": "A member of Stellar Program · {}",
"membershipPriceStellar": "1200 NSP per month, level 3+ required",
"membershipPriceNova": "2400 NSP per month, level 6+ required",
"membershipPriceSupernova": "3600 NSP per month, level 9+ required",
"membershipPriceStellar": "1200 NSP per month, level 20+ required",
"membershipPriceNova": "2400 NSP per month, level 40+ required",
"membershipPriceSupernova": "3600 NSP per month, level 60+ required",
"sharePostPhoto": "Share Post as Photo",
"wouldYouLikeToNavigateToChat": "Would You like to navigate to the chat?",
"abuseReports": "Abuse Reports",
@@ -705,7 +704,7 @@
"aboutScreenDeveloperSectionTitle": "Developer",
"aboutScreenContactUsTitle": "Contact Us",
"aboutScreenLicenseTitle": "License",
"aboutScreenLicenseContent": "GNU Affero General Public License v3.0",
"aboutScreenLicenseContent": "AGPLv3",
"aboutScreenCopyright": "All rights reserved © Solsynth {}",
"aboutScreenMadeWith": "Made with ❤︎️ by Solar Network Team",
"aboutScreenFailedToLoadPackageInfo": "Failed to load package info: {error}",
@@ -1474,5 +1473,74 @@
"lotteryLastNumberSpecial": "The last selected number will be your special number.",
"lotteryMultiplierRequired": "Please enter a multiplier",
"lotteryMultiplierRange": "Multiplier must be between 1 and 10",
"dropToShare": "Drop to share"
"dropToShare": "Drop to share",
"affiliationSpell": "Affiliation Spell",
"affiliationSpellHint": "If you have an affiliation spell, enter it here.",
"friendsOnline": "Friends Online",
"createAccountAlmostThere": "Almost There",
"createAccountAlmostThereHint": "You're one step away from joining the Solar Network! Please solve the captcha puzzle shows next.",
"createAccountNotice": "Things you need to know before you create an account:",
"createAccountConfirmEmail": "After your account being created, you need go to your email inbox to active your account to get permission to use all features.",
"createAccountNoAltAccounts": "Multiple or alternative accounts are banned from the Solar Network, that will violates our terms of services.",
"createAccountAgreeTerms": "I've read these terms and agree to the terms of service.",
"createAccountProfile": "Create your profile",
"createAccountToS": "Review Terms & Conditions",
"updateYourProfileDescription": "Adjust how you looks on the Solar Network.",
"realmsDescription": "Manage realms you've joined.",
"exploreDescription": "Explore contents on the Solar Network.",
"accountDescription": "Information about your account.",
"chatDescription": "Group Chats and Direct Messages",
"connectionServerDown": "Unable to Connect",
"appSettingsDescription": "Customize your app.",
"accountSettingsDescription": "Manage your preferences on the Solar Network.",
"walletDescription": "Your source point wallet.",
"relationshipsDescription": "Friends and connections.",
"notificationsDescription": "See what's happended related to you recently.",
"settingsFestivalFeatures": "Festival Limited Features",
"categoriesAndTags": "Categories & Tags",
"webArticlesStandDescription": "Explore external sites articles.",
"aboutDescription": "Learn more about the Solar Network.",
"abuseReportsDescription": "View and manage abuse reports.",
"stickerMarketplaceDescription": "Browse and add sticker packs from the Solar Network marketplace.",
"webFeedsDescription": "Browse and subscribe to web feeds from the Solar Network.",
"discoverRealmsDescription": "Discover new realms and join them.",
"postShuffleDescription": "Shuffle posts to see the posts randomly.",
"levelingDescription": "See your leveling progress and history.",
"notableDayToday": "{} is today!",
"authSessionLogout": "Logout Session",
"authSessionLogoutHint": "Are you sure you want to logout this session? This will terminate this specific login session.",
"filesDescription": "Manage your files on the Solar Network Drive.",
"postComposeDescription": "Compose a new post",
"searchPostsDescription": "Search posts by title, content, or else.",
"accountActivationAlert": "Activate your account",
"accountActivationAlertHint": "Unactivated account may leads to various of permission issues, activate your account by clicking the link we sent to your email inbox.",
"accountActivationResendHint": "Didn't see it? Try click the button below to resend one. If you need to update your email while your account was unactivated, feel free to contact our customer service.",
"accountActivationResend": "Resend",
"ipAddress": "IP Address",
"noFurtherData": "No further data",
"searchAnything": "Search Anything...",
"tapToViewAllNotifications": "Tap to view all notifications",
"mostRecent": "Most Recent",
"noNotificationsYet": "No notifications yet",
"recentChats": "Recent Chats",
"noFeaturedPostsAvailable": "No featured posts available",
"searchChatsAndPages": "Search chats and pages...",
"dashboard": "Dashboard",
"dashboardDescription": "All your data in one place.",
"postTagsCategories": "Post Tags and Categories",
"postTagsCategoriesDescription": "Browse posts by category and tags.",
"debugLogs": "Debug Logs",
"debugLogsDescription": "View debug logs for troubleshooting.",
"pinChatRoom": "Pin Chat Room",
"pinChatRoomDescription": "Pin this chat room to the top.",
"chatRoomPinned": "Chat room pinned successfully.",
"chatRoomUnpinned": "Chat room unpinned successfully.",
"pinnedChatRoom": "Pinned Rooms",
"settingsGroupedChatList": "Grouped Chat List",
"settingsNotifyWithHaptic": "Notification with Haptic Feedback",
"settingsDashSearchEngine": "Search Engine for web",
"settingsDashSearchEngineHelper": "Use %s as the placeholder for the query.",
"settingsDefaultScreen": "Default Screen",
"notableDayChristmas": "Christmas",
"notableDayNewYear": "New Year"
}

File diff suppressed because it is too large Load Diff

View File

@@ -314,7 +314,6 @@
"settingsAutoTranslate": "自轉譯",
"settingsHideBottomNav": "隱底航",
"settingsSoundEffects": "音效",
"settingsAprilFoolFeatures": "謔辰妙能",
"settingsEnterToSend": "叩回車鍵即送",
"settingsTransparentAppBar": "透光應用欄",
"settingsCustomFonts": "自定字體",
@@ -328,13 +327,13 @@
"accountDeletion": "除去此账户",
"accountDeletionHint": "汝已存心除此账户?如已一意,信将至汝邮址,随信中之言续此行。",
"accountDeletionSent": "除此账户之信已送至,请于汝之邮址查阅。",
"accountSecurityTitle": "Security",
"accountDangerZoneTitle": "Danger Zone",
"accountSecurityTitle": "保护措施",
"accountDangerZoneTitle": "危险地区",
"accountPassword": "密碼",
"accountPasswordDescription": "變更账户密碼",
"accountPasswordChange": "變更密碼",
"accountPasswordChangeSent": "Password reset link sent, please check your email inbox.",
"accountPasswordChangeDescription": "We will send an email to your primary email address to reset your password.",
"accountPasswordChangeSent": "密码重置链接已发送,请查看您的电子邮箱收件箱。",
"accountPasswordChangeDescription": "我们将向您的主要电子邮箱发送一封邮件以重置您的密码。",
"accountAuthFactor": "Auth factors",
"accountAuthFactorDescription": "Multi-factor authentication to ensure safety and convience",
"accountDeletionDescription": "Permanently delete your account and all your data",
@@ -682,9 +681,9 @@
"articleAttachmentHint": "Attachments must be uploaded and inserted into the article body to be visible.",
"postVisibility": "Post Visibility",
"currentMembershipMember": "A member of Stellar Program · {}",
"membershipPriceStellar": "1200 NSP per month, level 3+ required",
"membershipPriceNova": "2400 NSP per month, level 6+ required",
"membershipPriceSupernova": "3600 NSP per month, level 9+ required",
"membershipPriceStellar": "1200 NSP per month, level 20+ required",
"membershipPriceNova": "2400 NSP per month, level 40+ required",
"membershipPriceSupernova": "3600 NSP per month, level 60+ required",
"sharePostPhoto": "Share Post as Photo",
"wouldYouLikeToNavigateToChat": "Would You like to navigate to the chat?",
"abuseReports": "Abuse Reports",
@@ -705,7 +704,7 @@
"aboutScreenDeveloperSectionTitle": "Developer",
"aboutScreenContactUsTitle": "Contact Us",
"aboutScreenLicenseTitle": "License",
"aboutScreenLicenseContent": "GNU Affero General Public License v3.0",
"aboutScreenLicenseContent": "AGPLv3",
"aboutScreenCopyright": "All rights reserved © Solsynth {}",
"aboutScreenMadeWith": "Made with ❤︎️ by Solar Network Team",
"aboutScreenFailedToLoadPackageInfo": "Failed to load package info: {error}",
@@ -1474,5 +1473,74 @@
"lotteryLastNumberSpecial": "The last selected number will be your special number.",
"lotteryMultiplierRequired": "Please enter a multiplier",
"lotteryMultiplierRange": "Multiplier must be between 1 and 10",
"dropToShare": "Drop to share"
"dropToShare": "Drop to share",
"affiliationSpell": "Affiliation Spell",
"affiliationSpellHint": "If you have an affiliation spell, enter it here.",
"friendsOnline": "Friends Online",
"createAccountAlmostThere": "Almost There",
"createAccountAlmostThereHint": "You're one step away from joining the Solar Network! Please solve the captcha puzzle shows next.",
"createAccountNotice": "Things you need to know before you create an account:",
"createAccountConfirmEmail": "After your account being created, you need go to your email inbox to active your account to get permission to use all features.",
"createAccountNoAltAccounts": "Multiple or alternative accounts are banned from the Solar Network, that will violates our terms of services.",
"createAccountAgreeTerms": "I've read these terms and agree to the terms of service.",
"createAccountProfile": "Create your profile",
"createAccountToS": "Review Terms & Conditions",
"updateYourProfileDescription": "Adjust how you looks on the Solar Network.",
"realmsDescription": "Manage realms you've joined.",
"exploreDescription": "Explore contents on the Solar Network.",
"accountDescription": "Information about your account.",
"chatDescription": "Group Chats and Direct Messages",
"connectionServerDown": "Unable to Connect",
"appSettingsDescription": "Customize your app.",
"accountSettingsDescription": "Manage your preferences on the Solar Network.",
"walletDescription": "Your source point wallet.",
"relationshipsDescription": "Friends and connections.",
"notificationsDescription": "See what's happended related to you recently.",
"settingsFestivalFeatures": "Festival Limited Features",
"categoriesAndTags": "Categories & Tags",
"webArticlesStandDescription": "Explore external sites articles.",
"aboutDescription": "Learn more about the Solar Network.",
"abuseReportsDescription": "View and manage abuse reports.",
"stickerMarketplaceDescription": "Browse and add sticker packs from the Solar Network marketplace.",
"webFeedsDescription": "Browse and subscribe to web feeds from the Solar Network.",
"discoverRealmsDescription": "Discover new realms and join them.",
"postShuffleDescription": "Shuffle posts to see the posts randomly.",
"levelingDescription": "See your leveling progress and history.",
"notableDayToday": "{} is today!",
"authSessionLogout": "Logout Session",
"authSessionLogoutHint": "Are you sure you want to logout this session? This will terminate this specific login session.",
"filesDescription": "Manage your files on the Solar Network Drive.",
"postComposeDescription": "Compose a new post",
"searchPostsDescription": "Search posts by title, content, or else.",
"accountActivationAlert": "Activate your account",
"accountActivationAlertHint": "Unactivated account may leads to various of permission issues, activate your account by clicking the link we sent to your email inbox.",
"accountActivationResendHint": "Didn't see it? Try click the button below to resend one. If you need to update your email while your account was unactivated, feel free to contact our customer service.",
"accountActivationResend": "Resend",
"ipAddress": "IP Address",
"noFurtherData": "No further data",
"searchAnything": "Search Anything...",
"tapToViewAllNotifications": "Tap to view all notifications",
"mostRecent": "Most Recent",
"noNotificationsYet": "No notifications yet",
"recentChats": "Recent Chats",
"noFeaturedPostsAvailable": "No featured posts available",
"searchChatsAndPages": "Search chats and pages...",
"dashboard": "Dashboard",
"dashboardDescription": "All your data in one place.",
"postTagsCategories": "Post Tags and Categories",
"postTagsCategoriesDescription": "Browse posts by category and tags.",
"debugLogs": "Debug Logs",
"debugLogsDescription": "View debug logs for troubleshooting.",
"pinChatRoom": "Pin Chat Room",
"pinChatRoomDescription": "Pin this chat room to the top.",
"chatRoomPinned": "Chat room pinned successfully.",
"chatRoomUnpinned": "Chat room unpinned successfully.",
"pinnedChatRoom": "Pinned Rooms",
"settingsGroupedChatList": "Grouped Chat List",
"settingsNotifyWithHaptic": "Notification with Haptic Feedback",
"settingsDashSearchEngine": "Search Engine for web",
"settingsDashSearchEngineHelper": "Use %s as the placeholder for the query.",
"settingsDefaultScreen": "Default Screen",
"notableDayChristmas": "Christmas",
"notableDayNewYear": "New Year"
}

View File

@@ -314,7 +314,6 @@
"settingsAutoTranslate": "自動翻譯",
"settingsHideBottomNav": "隱藏底部導航",
"settingsSoundEffects": "音效",
"settingsAprilFoolFeatures": "愚人節功能",
"settingsEnterToSend": "按下 Enter 發送",
"settingsTransparentAppBar": "使用完全透明的狀態欄",
"settingsCustomFonts": "自定義字體",
@@ -682,9 +681,9 @@
"articleAttachmentHint": "附件必須上傳並插入到文章主體中才能顯示出來。",
"postVisibility": "可見性",
"currentMembershipMember": "恆星計劃成員 · {}",
"membershipPriceStellar": "需要用戶等級 3+,每月價格 1200 NSP",
"membershipPriceNova": "需要用戶等級 6+,每月價格 2400 NSP",
"membershipPriceSupernova": "需要用戶等級 9+,每月價格 3600 NSP",
"membershipPriceStellar": "需要用戶等級 20+,每月價格 1200 NSP",
"membershipPriceNova": "需要用戶等級 40+,每月價格 2400 NSP",
"membershipPriceSupernova": "需要用戶等級 60+,每月價格 3600 NSP",
"sharePostPhoto": "通過圖片分享帖子",
"wouldYouLikeToNavigateToChat": "你想要前往聊天頁面嗎?",
"abuseReports": "舉報",
@@ -1060,7 +1059,7 @@
"failedToDeleteRecycledFiles": "已回收檔案刪除失敗",
"upload": "上傳",
"deleteMessage": "刪除訊息",
"deleteMessageConfirmation": "確定要刪除此郵件嗎?",
"deleteMessageConfirmation": "確定要刪除此郵件嗎",
"customReaction": "自訂反應",
"customReactions": "自訂反應",
"stickerPlaceholder": "貼紙佔位符",
@@ -1131,348 +1130,417 @@
"noReceivedGifts": "没有收到过礼物",
"stellarGift": "恆星禮物",
"novaGift": "新星禮物",
"supernovaGift": "Supernova Gift",
"sameAsMembership": "Same as membership",
"enterGiftCodeToRedeem": "Enter gift code to redeem",
"enterGiftCode": "Enter gift code",
"giftPurchased": "Gift Purchased!",
"shareCodeWithRecipient": "Share this code with the recipient to redeem the gift.",
"openGiftAnyoneCanRedeem": "This is an open gift that anyone can redeem.",
"ok": "OK",
"selectedRecipient": "Selected recipient",
"noRecipientSelected": "No recipient selected",
"thisWillBeAnOpenGift": "This will be an open gift",
"personalMessage": "Personal Message",
"addPersonalMessageForRecipient": "Add a personal message for the recipient",
"giftStatusCreated": "Created",
"giftStatusSent": "Sent",
"giftStatusRedeemed": "Redeemed",
"giftStatusCancelled": "Cancelled",
"giftStatusExpired": "Expired",
"giftStatusUnknown": "Unknown",
"giftCodeCopiedToClipboard": "Gift code copied to clipboard",
"codeLabel": "Code: ",
"subscriptionLabel": "Subscription: ",
"toLabel": "To: ",
"fromLabel": "From: ",
"messageLabel": "Message: ",
"giftRedeemed": "Gift Redeemed!",
"giftRedeemedSuccessfully": "You have successfully redeemed the gift. Your new subscription is now active.",
"cancelGift": "Cancel Gift",
"cancelGiftConfirm": "Are you sure you want to cancel this gift? This action cannot be undone.",
"giftCancelledSuccessfully": "Gift cancelled successfully",
"createFund": "Create Fund",
"fundAmount": "Fund Amount",
"enterAmount": "Enter Amount",
"selectCurrency": "Select Currency",
"splitType": "Split Type",
"evenSplit": "Even Split",
"equalAmountEach": "Equal amount for each recipient",
"randomSplit": "Random Split",
"randomAmountEach": "Random amount for each recipient",
"recipientCount": "Recipient Count",
"numberOfRecipients": "Number of Recipients",
"addPersonalMessageForRecipients": "Add a personal message for recipients",
"invalidAmount": "Invalid amount",
"invalidRecipientCount": "Invalid recipient count",
"fundOverview": "Fund Overview",
"totalFundsSent": "Total Funds Sent",
"totalFundsReceived": "Total Funds Received",
"transactions": "Transactions",
"myFunds": "My Funds",
"availableFunds": "Available Funds",
"fundStatusCreated": "Created",
"fundStatusPartial": "Partially Claimed",
"fundStatusCompleted": "Fully Claimed",
"fundStatusExpired": "Expired",
"fundStatusUnknown": "Unknown",
"recipients": "Recipients",
"fundClaimedSuccessfully": "Fund claimed successfully!",
"claim": "Claim",
"noFundsCreated": "No funds created yet",
"createYourFirstFund": "Create your first fund to get started",
"noAvailableFunds": "No available funds",
"fundsWillAppearHere": "Funds you can claim will appear here",
"fundCreatedSuccessfully": "Fund created successfully!",
"selectRecipients": "Select Recipients",
"noRecipientsSelected": "No recipients selected",
"selectRecipientsToSendFund": "Select recipients to send the fund to",
"addRecipient": "Add Recipient",
"addMoreRecipients": "Add More Recipients",
"transactionDetails": "Transaction Details",
"remarks": "Remarks",
"payer": "Payer",
"payee": "Payee",
"transactionType": "Transaction Type",
"transfer": "Transfer",
"payment": "Payment",
"systemWallet": "System Wallet",
"date": "Date",
"createTransfer": "Create Transfer",
"transferAmount": "Transfer Amount",
"selectPayee": "Select Payee",
"selectedPayee": "Selected Payee",
"noPayeeSelected": "No payee selected",
"selectPayeeToTransfer": "Select payee to transfer to",
"addRemark": "Add Remark",
"transferRemark": "Transfer Remark",
"addRemarkForTransfer": "Add remark for transfer",
"enterPinToConfirmTransfer": "Enter your 6-digit PIN to confirm transfer",
"transferCreatedSuccessfully": "Transfer created successfully!",
"postUpdate": "Update",
"fileMetadata": "File Metadata",
"resend": "Resend",
"fileInfoTitle": "File Information",
"download": "Download",
"info": "Info",
"noStickers": "No Stickers",
"noStickersInPack": "This pack does not contains stickers",
"noStickerPacks": "No Sticker Packs",
"refresh": "Refresh",
"spoiler": "Spoiler",
"activityHeatmap": "Activity Heatmap",
"custom": "Custom",
"usernameColor": "Username Color",
"colorType": "Color Type",
"plain": "Plain",
"gradient": "Gradient",
"colorValue": "Color Value",
"gradientDirection": "Gradient Direction",
"gradientDirectionToRight": "To Right",
"gradientDirectionToLeft": "To Left",
"gradientDirectionToBottom": "To Bottom",
"gradientDirectionToTop": "To Top",
"gradientDirectionToBottomRight": "To Bottom Right",
"gradientDirectionToBottomLeft": "To Bottom Left",
"gradientDirectionToTopRight": "To Top Right",
"gradientDirectionToTopLeft": "To Top Left",
"gradientColors": "Gradient Colors",
"color": "Color",
"addColor": "Add Color",
"availableWithYourPlan": "Available with your plan",
"upgradeRequired": "Upgrade required",
"settingsDisableAnimation": "Disable Animation",
"addTag": "Add Tag",
"supernovaGift": "超新星訂閱",
"sameAsMembership": "於成員相同",
"enterGiftCodeToRedeem": "輸入禮物程式碼以兌換",
"enterGiftCode": "輸入禮物程式碼",
"giftPurchased": "已購買禮物!",
"shareCodeWithRecipient": "與收件人分享此程式碼來兌換禮物。",
"openGiftAnyoneCanRedeem": "這是一份任何人都可以兌換的公開禮物。",
"ok": "好的",
"selectedRecipient": "選擇接收者",
"noRecipientSelected": "沒有選中的接受者",
"thisWillBeAnOpenGift": "這將是一份公開的禮物",
"personalMessage": "個人信息",
"addPersonalMessageForRecipient": "為收件人添加個人訊息",
"giftStatusCreated": "已創建",
"giftStatusSent": "發送",
"giftStatusRedeemed": "已兌換",
"giftStatusCancelled": "已取消",
"giftStatusExpired": "已過期",
"giftStatusUnknown": "未知",
"giftCodeCopiedToClipboard": "禮物程式碼已經複製到剪貼簿",
"codeLabel": "程式碼:",
"subscriptionLabel": "訂閱:",
"toLabel": "至:",
"fromLabel": "從:",
"messageLabel": "消息:",
"giftRedeemed": "禮物已兌換!",
"giftRedeemedSuccessfully": "您已成功兌換了禮物。您的新訂閱現在已經生效。",
"cancelGift": "取消禮物",
"cancelGiftConfirm": "您確定要取消此禮物?此操作無法撤銷。",
"giftCancelledSuccessfully": "禮物成功取消",
"createFund": "創建支票",
"fundAmount": "支票金額",
"enterAmount": "輸入金額",
"selectCurrency": "選擇貨幣",
"splitType": "拆分類型",
"evenSplit": "平均拆分",
"equalAmountEach": "每個收款人的金額相同",
"randomSplit": "隨機拆分",
"randomAmountEach": "每個收款人的金額隨機",
"recipientCount": "收款人總計",
"numberOfRecipients": "收款人數量",
"addPersonalMessageForRecipients": "為收款人添加個人信息",
"invalidAmount": "無效的金額",
"invalidRecipientCount": "收款人數量無效",
"fundOverview": "支票概覽",
"totalFundsSent": "共發送支票",
"totalFundsReceived": "共領取支票",
"transactions": "交易",
"myFunds": "我的支票",
"availableFunds": "可用支票",
"fundStatusCreated": "已創建",
"fundStatusPartial": "部分領取",
"fundStatusCompleted": "已領完",
"fundStatusExpired": "已過期",
"fundStatusUnknown": "未知",
"recipients": "收款人",
"fundClaimedSuccessfully": "支票成功領取!",
"claim": "領取",
"noFundsCreated": "還沒有創建的支票",
"createYourFirstFund": "創建您的第一個支票以開始",
"noAvailableFunds": "暫無可用支票",
"fundsWillAppearHere": "您可以領取的支票將出現在這裡",
"fundCreatedSuccessfully": "支票成功創建!",
"selectRecipients": "選擇收款人",
"noRecipientsSelected": "沒有選擇收款人",
"selectRecipientsToSendFund": "選擇收款人將支票發送到",
"addRecipient": "添加收款人",
"addMoreRecipients": "添加更多收款人",
"transactionDetails": "交易詳情",
"remarks": "備註",
"payer": "付款方",
"payee": "交易方",
"transactionType": "交易類型",
"transfer": "轉帳",
"payment": "支付",
"systemWallet": "系統錢包",
"date": "日期",
"createTransfer": "創建交易",
"transferAmount": "交易金額",
"selectPayee": "請選擇收款人",
"selectedPayee": "選定的收款人",
"noPayeeSelected": "沒有選擇收款人",
"selectPayeeToTransfer": "選擇要轉帳的收款人",
"addRemark": "添加備註",
"transferRemark": "交易備註",
"addRemarkForTransfer": "為轉帳添加備註",
"enterPinToConfirmTransfer": "輸入您的 6 位PIN碼以確認轉帳",
"transferCreatedSuccessfully": "轉帳成功創建",
"postUpdate": "更新",
"fileMetadata": "檔案資訊",
"resend": "重新發送",
"fileInfoTitle": "檔案信息",
"download": "下載",
"info": "信息",
"noStickers": "沒有貼圖",
"noStickersInPack": "這個包不包含貼圖",
"noStickerPacks": "沒有貼圖包",
"refresh": "刷新",
"spoiler": "已隱藏",
"activityHeatmap": "活动热力图",
"custom": "自定義",
"usernameColor": "用戶名顏色",
"colorType": "顏色類型",
"plain": "純色",
"gradient": "漸變",
"colorValue": "色值",
"gradientDirection": "漸變方向",
"gradientDirectionToRight": "向右",
"gradientDirectionToLeft": "向左",
"gradientDirectionToBottom": "向底部",
"gradientDirectionToTop": "向上",
"gradientDirectionToBottomRight": "向右下角",
"gradientDirectionToBottomLeft": "向左下角",
"gradientDirectionToTopRight": "向右上角",
"gradientDirectionToTopLeft": "向左下角",
"gradientColors": "漸變顏色",
"color": "顏色",
"addColor": "添加顏色",
"availableWithYourPlan": "隨您的方案提供",
"upgradeRequired": "需要升級",
"settingsDisableAnimation": "停用動畫",
"addTag": "添加標籤",
"accountConnectionProviderSpotify": "Spotify",
"accountConnectionProviderSteam": "Steam",
"timezoneNotFound": "Time zone not found",
"awardPoints": "Awarded {} points",
"postFeaturedOn": "Post featured on {}",
"messageSentAt": "Sent at {}",
"myTickets": "My Tickets",
"drawHistory": "Draw History",
"lottery": "Lottery",
"noLotteryTickets": "No lottery tickets yet",
"buyYourFirstTicket": "Buy your first lottery ticket to get started!",
"buyTicket": "Buy Ticket",
"ticketNumbers": "Numbers: {}, Special: {}",
"cost": "Cost",
"multiplier": "Multiplier",
"prizeWon": "Prize Won",
"pending": "Pending",
"drawn": "Drawn",
"won": "Won",
"lost": "Lost",
"noDrawHistory": "No draw history yet",
"buyLotteryTicket": "Buy Lottery Ticket",
"selectNumbers": "Select Numbers",
"select5UniqueNumbers": "Select 5 unique numbers",
"selectSpecialNumber": "Select Special Number",
"selectMultiplier": "Select Multiplier",
"baseCost": "Base Cost",
"totalCost": "Total Cost",
"prizeStructure": "Prize Structure",
"enterPinToConfirmPurchase": "Enter your PIN to confirm purchase",
"ticketPurchasedSuccessfully": "Ticket purchased successfully!",
"winningNumbers": "Winning Numbers",
"specialNumber": "Special Number",
"totalTickets": "Total Tickets",
"totalWinners": "Total Winners",
"prizePool": "Prize Pool",
"enterPinToConfirmPayment": "Enter your PIN code to confirm payment",
"purchase": "Purchase",
"multiplierLabel": "Multiplier",
"specialOnly": "Special Only",
"matches": "Matches",
"thoughtDefaultTopic": "Reflection",
"thoughtAiName": "SN-chan",
"thoughtUserName": "You",
"thoughtStreamingHint": "Sn-chan is thinking...",
"thoughtInputHint": "Ask sn-chan anything...",
"thoughtNewConversation": "Start New Conversation",
"thoughtParseError": "Failed to parse AI response",
"thoughtFunctionCall": "Use {}",
"aiThought": "AI Thought",
"aiThoughtTitle": "Let sn-chan think",
"postReferenceUnavailable": "Referenced post is unavailable",
"fabLocation": "FAB Location",
"activities": "Activities",
"presenceTypeGaming": "Playing",
"presenceTypeMusic": "Listening to Music",
"presenceTypeWorkout": "Working out",
"articleCompose": "Compose Article",
"backToHub": "Back to Hub",
"advancedFilters": "Advanced Filters",
"searchPosts": "Search Posts",
"sortBy": "Sort by",
"fromDate": "From Date",
"toDate": "To Date",
"popularity": "Popularity",
"descendingOrder": "Descending Order",
"selectDate": "Select Date",
"pinnedPosts": "Pinned Posts",
"customReactionHint": "Custom Reaction allow you to use user uploaded stickers as the symbol of the reaction for the post. Exclusive for Stellar Program members.",
"publicationSites": "Publication Sites",
"uploadTasks": "Upload Tasks",
"thoughtFunctionCallBegin": "Calling tool {}",
"thoughtFunctionCallFinish": "{} responded",
"thoughtUnpaidHint": "Thinking unavaiable due to unpaid orders",
"more": "More",
"collapse": "Collapse",
"pollConfirmDiscard": "Are you sure you want to leave? All the poll data you're editing will not be saved.",
"timezoneNotFound": "找不到時區",
"awardPoints": "獎賞 {} 點",
"postFeaturedOn": "帖文在 {} 被精選",
"messageSentAt": "發送在 {}",
"myTickets": "我的彩票",
"drawHistory": "開獎歷史",
"lottery": "彩票",
"noLotteryTickets": "還沒有彩票",
"buyYourFirstTicket": "購買您的第一張彩票以開始!",
"buyTicket": "買彩票",
"ticketNumbers": "數字:{},特殊數字:{}",
"cost": "花費",
"multiplier": "倍率",
"prizeWon": "獲勝者",
"pending": "待開獎",
"drawn": "已開獎",
"won": "獲勝",
"lost": "失敗",
"noDrawHistory": "還沒有開獎曆史",
"buyLotteryTicket": "購買彩票",
"selectNumbers": "選擇數字",
"select5UniqueNumbers": "選擇 5 個不同的數字",
"selectSpecialNumber": "選擇特殊數字",
"selectMultiplier": "選擇倍率",
"baseCost": "基礎花費",
"totalCost": "總費用",
"prizeStructure": "獎金分級",
"enterPinToConfirmPurchase": "輸入您的 PIN 碼以確認購買",
"ticketPurchasedSuccessfully": "彩票購買成功!",
"winningNumbers": "獲勝數字",
"specialNumber": "特殊數字",
"totalTickets": "總售出票數",
"totalWinners": "總中獎者",
"prizePool": "獎池",
"enterPinToConfirmPayment": "輸入您的 PIN 碼以確認交易",
"purchase": "購買",
"multiplierLabel": "倍率",
"specialOnly": "僅特殊數字",
"matches": "場次",
"thoughtDefaultTopic": "尋思",
"thoughtAiName": "SN",
"thoughtUserName": "",
"thoughtStreamingHint": "SN醬正在思考……",
"thoughtInputHint": "問SN醬一些東西……",
"thoughtNewConversation": "開始新對話",
"thoughtParseError": "解析 AI 響應失敗",
"thoughtFunctionCall": "使用 {}",
"aiThought": "尋思",
"aiThoughtTitle": "讓SN醬思考",
"postReferenceUnavailable": "應用的帖子不可用",
"fabLocation": "底部菜單按鈕位置",
"activities": "活動",
"presenceTypeGaming": "正在玩",
"presenceTypeMusic": "正在聽音樂",
"presenceTypeWorkout": "鍛煉中",
"articleCompose": "撰寫文章",
"backToHub": "返回至主頁",
"advancedFilters": "高級篩選",
"searchPosts": "搜索帖子",
"sortBy": "排序方式",
"fromDate": "起始日期",
"toDate": "截止日期",
"popularity": "按熱度",
"descendingOrder": "降序排序",
"selectDate": "選擇日期",
"pinnedPosts": "已置頂的帖子",
"customReactionHint": "自訂反應允許你使用用戶上傳貼紙作為帖子反應的符號,需要恆星計劃訂閱。",
"publicationSites": "發佈者網站",
"uploadTasks": "上傳任務",
"thoughtFunctionCallBegin": "調用工具 {}",
"thoughtFunctionCallFinish": "工具 {}",
"thoughtUnpaidHint": "尋思因為有未支付的訂單而被禁用",
"more": "更多",
"collapse": "折疊",
"pollConfirmDiscard": "您確定要離開嗎?您編輯的所有資料都不會被保存。",
"discard": "Discard",
"fund": "Fund",
"fundsRecent": "Recent Funds",
"fundCreateNew": "Create New",
"fundCreateNewHint": "Create a new fund for your message. Select recipients and amount.",
"amountOfSplits": "Amount of Splits",
"enterNumberOfSplits": "Enter Splits Amount",
"orCreateWith": "Or\ncreate with",
"unindexedFiles": "Unindexed files",
"folder": "Folder",
"clearCompleted": "Clear Completed",
"uploadSuccess": "Upload successful!",
"wouldYouLikeToViewFile": "Would you like to view the file?",
"contentCantEmpty": "Content cannot be empty",
"features": "Features",
"unnamed": "Unnamed",
"fundEnvelopeLoadFailed": "Failed to load fund envelope",
"fundEnvelope": "Fund Envelope",
"fundEnvelopeRemaining": "Remaining: {} {}",
"fundEnvelopeSplit": "Split: {}",
"fundEnvelopeSplitEvenly": "Evenly",
"fundEnvelopeSplitRandomly": "Randomly",
"fundEnvelopeClaimSuccess": "Fund claimed successfully!",
"fundEnvelopeStatusCreated": "Created",
"fundEnvelopeStatusPartial": "Partially Claimed",
"fundEnvelopeStatusCompleted": "Fully Claimed",
"fundEnvelopeStatusExpired": "Expired",
"fundEnvelopeStatusUnknown": "Unknown",
"fundEnvelopeRecipients": "Recipients ({}/{} claimed)",
"fund": "支票",
"fundsRecent": "最近的支票",
"fundCreateNew": "創建新的",
"fundCreateNewHint": "為您的消息創建一個新的紅包。選擇接收者和金額。",
"amountOfSplits": "份數",
"enterNumberOfSplits": "單份金額",
"orCreateWith": "或\n使用第三方賬戶登錄",
"unindexedFiles": "未索引的檔案",
"folder": "文件夾",
"clearCompleted": "清除已經完成的",
"uploadSuccess": "上傳成功!",
"wouldYouLikeToViewFile": "您想查看檔案嗎?",
"contentCantEmpty": "內容不能為空",
"features": "功能",
"unnamed": "未命名",
"fundEnvelopeLoadFailed": "載入支票信封失敗",
"fundEnvelope": "支票信封",
"fundEnvelopeRemaining": "剩餘:{} {}",
"fundEnvelopeSplit": "拆分:{}",
"fundEnvelopeSplitEvenly": "均分",
"fundEnvelopeSplitRandomly": "隨機",
"fundEnvelopeClaimSuccess": "支票領取成功!",
"fundEnvelopeStatusCreated": "已創建",
"fundEnvelopeStatusPartial": "已領取部分",
"fundEnvelopeStatusCompleted": "已全部領取",
"fundEnvelopeStatusExpired": "已過期",
"fundEnvelopeStatusUnknown": "未知",
"fundEnvelopeRecipients": "收款人 {}/{}已領取)",
"fundEnvelopeExpiredDaysAgo": {
"one": "Expired {} day ago",
"other": "Expired {} days ago"
"one": "{}天前過期",
"other": "{}天前過期"
},
"fundEnvelopeExpiresSoon": "Expires soon",
"fundEnvelopeExpiresSoon": "即將過期",
"fundEnvelopeExpiresInHours": {
"one": "Expires in {} hour",
"other": "Expires in {} hours"
"one": "{}小時後過期",
"other": "{}小時後過期"
},
"fundEnvelopeExpiresInDays": {
"one": "Expires in {} day",
"other": "Expires in {} days"
"one": "{}天後過期",
"other": "{}天後過期"
},
"fundEnvelopeRemainingWithSplits": "{} {} / {} splits",
"fundEnvelopeUnknownUser": "Unknown User",
"deleteSite": "Delete Site",
"deleteSiteConfirm": "Are you sure you want to delete this site?",
"siteDeletedSuccess": "Site deleted successfully",
"siteSlug": "Slug",
"siteSlugHint": "my-site",
"siteSlugRequired": "Please enter a slug",
"siteSlugInvalid": "Slug can only contain lowercase letters, numbers, and dashes",
"siteName": "Site Name",
"siteNameHint": "My Publication Site",
"siteNameRequired": "Please enter a site name",
"siteMode": "Mode",
"siteModeFullyManaged": "Fully Managed",
"siteModeSelfManaged": "Self-Managed",
"editPublicationSite": "Edit Publication Site",
"deletePublicationSite": "Delete Publication Site",
"publicationSiteSavedSuccess": "Publication site saved successfully",
"publicationSiteDeleteConfirm": "Are you sure you want to delete this publication site? This action cannot be undone.",
"publicationSiteDeletedSuccess": "Publication site deleted successfully",
"newPublicationSite": "New Publication Site",
"siteDetails": "Site Details",
"siteInformation": "Site Information",
"siteDomain": "Domain",
"siteCreated": "Created",
"siteUpdated": "Updated",
"failedToLoadSite": "Failed to load site",
"sitePages": "Pages",
"noPagesYet": "No pages yet",
"createFirstPage": "Create your first page to get started",
"failedToLoadPages": "Failed to load pages",
"fileManagement": "File Management",
"siteFiles": "Files",
"siteFolder": "Folder",
"siteRoot": "Root",
"noFilesUploadedYet": "No files uploaded yet",
"uploadFirstFile": "Upload your first file to get started",
"failedToLoadFiles": "Failed to load files",
"noFilesFoundInFolder": "No files found in the selected folder",
"fileActions": "File Actions",
"purgeFiles": "Purge Files",
"purgeFilesDescription": "Remove all uploaded files from the site",
"deploySite": "Deploy Site",
"deploySiteDescription": "Upload and deploy a new version from ZIP archive",
"confirmPurge": "Confirm Purge",
"purgeFilesConfirm": "This will permanently delete all files uploaded to this site. This action cannot be undone. Are you sure you want to continue?",
"purgeAllFiles": "Purge All Files",
"allFilesPurgedSuccess": "All files purged successfully",
"failedToPurgeFiles": "Failed to purge files: {}",
"siteDeployedSuccess": "Site deployed successfully",
"failedToDeploySite": "Failed to deploy site: {}",
"createPage": "Create Page",
"editPage": "Edit Page",
"pageType": "Page Type",
"htmlPage": "HTML Page",
"redirectPage": "Redirect Page",
"pageTypeRequired": "Please select a page type",
"pagePath": "Page Path",
"pagePathHint": "/about, /contact, etc.",
"pagePathRequired": "Please enter a page path",
"pagePathInvalid": "Page path can only contain letters, numbers, hyphens, underscores, and slashes",
"pagePathMustStartWithSlash": "Page path must start with /",
"pagePathNoConsecutiveSlashes": "Page path cannot have consecutive slashes",
"pageTitle": "Page Title",
"pageTitleHint": "About Us, Contact, etc.",
"pageTitleRequired": "Please enter a page title",
"pageContentHtml": "Page Content (HTML)",
"pageContentHint": "<h1>Hello World</h1><p>This is my page content...</p>",
"pageContentRequired": "Please enter HTML content for the page",
"redirectTarget": "Redirect Target",
"redirectTargetHint": "/new-page, https://example.com, etc.",
"redirectTargetRequired": "Please enter a redirect target",
"redirectTargetInvalid": "Target must be a relative path (/) or absolute URL (http/https)",
"deletePage": "Delete Page",
"deletePageConfirm": "Are you sure you want to delete this page?",
"savePage": "Save Page",
"pageCreatedSuccess": "Page created successfully",
"pageUpdatedSuccess": "Page updated successfully",
"pageDeletedSuccess": "Page deleted successfully",
"uploadFiles": "Upload Files",
"uploadPath": "Upload Path",
"uploadPathHint": "/ (root) or /assets/images/",
"uploadPathRequired": "Please enter an upload path",
"uploadPathMustStartWithSlash": "Path must start with /",
"uploadPathNoSpaces": "Path cannot contain spaces",
"uploadPathNoConsecutiveSlashes": "Path cannot have consecutive slashes",
"percentCompleted": "{}% completed",
"filesToUpload": "{} files to upload",
"fileSizeKb": "Size: {} KB",
"uploadingEllipsis": "Uploading...",
"fundEnvelopeRemainingWithSplits": "{} {} / {} ",
"fundEnvelopeUnknownUser": "未知用戶",
"deleteSite": "刪除網站",
"deleteSiteConfirm": "您確定要刪除此網站嗎?",
"siteDeletedSuccess": "網站成功刪除",
"siteSlug": "標識符",
"siteSlugHint": "我的站點",
"siteSlugRequired": "請輸入一個標識符",
"siteSlugInvalid": "標識符只能包含小寫字母、數字和連字符",
"siteName": "網站名稱",
"siteNameHint": "我的發佈者網站",
"siteNameRequired": "請輸入一個站點名稱",
"siteMode": "模式",
"siteModeFullyManaged": "全託管",
"siteModeSelfManaged": "自託管",
"editPublicationSite": "編輯發佈者網站",
"deletePublicationSite": "刪除發佈者網站",
"publicationSiteSavedSuccess": "發佈者網站保存成功",
"publicationSiteDeleteConfirm": "您確定要刪除此發佈者網站嗎?此操作不能撤銷。",
"publicationSiteDeletedSuccess": "發佈者網站成功刪除",
"newPublicationSite": "新建發佈者網站",
"siteDetails": "網站描述",
"siteInformation": "網站信息",
"siteDomain": "域名",
"siteCreated": "創建于",
"siteUpdated": "更新于",
"failedToLoadSite": "加載網站失敗",
"sitePages": "頁面",
"noPagesYet": "還沒有頁面",
"createFirstPage": "創建您的第一個頁面以開始",
"failedToLoadPages": "加載頁面失敗",
"fileManagement": "檔案管理器",
"siteFiles": "檔案",
"siteFolder": "資料夾",
"siteRoot": "",
"noFilesUploadedYet": "尚未上傳任何檔案",
"uploadFirstFile": "上傳您的第一個檔案以開始",
"failedToLoadFiles": "加載檔案失敗",
"noFilesFoundInFolder": "在選擇的資料夾中沒有檔案",
"fileActions": "檔案選項",
"purgeFiles": "清除檔案",
"purgeFilesDescription": "從這個網站刪除全部文件",
"deploySite": "部署網站",
"deploySiteDescription": "從ZIP存檔上傳和部署新版本",
"confirmPurge": "確認清空",
"purgeFilesConfirm": "這將永久刪除上傳到本網站的所有檔案。此操作無法復原。您確定要繼續嗎?",
"purgeAllFiles": "清除所有文檔案",
"allFilesPurgedSuccess": "全部檔案成功清空",
"failedToPurgeFiles": "清除檔案失敗:{}",
"siteDeployedSuccess": "網站成功部署",
"failedToDeploySite": "部署網站失敗:{}",
"createPage": "創建頁面",
"editPage": "編輯頁面",
"pageType": "頁面類型",
"htmlPage": "HTML 頁面",
"redirectPage": "重定向頁面",
"pageTypeRequired": "請選擇一個頁面類型",
"pagePath": "頁面路徑",
"pagePathHint": "例如/about/contact",
"pagePathRequired": "請輸入一個頁面路徑",
"pagePathInvalid": "頁面路徑只能包含字母、數字、連字符、底線和斜線",
"pagePathMustStartWithSlash": "頁面路徑以/開始",
"pagePathNoConsecutiveSlashes": "頁面路徑不能有連續的斜線",
"pageTitle": "頁面標題",
"pageTitleHint": "例如About UsContact",
"pageTitleRequired": "請輸入一個頁面標題",
"pageContentHtml": "頁面內容(HTML",
"pageContentHint": "<h1> Hello World</h1><p>這是我的頁面內容…</p>",
"pageContentRequired": "請為頁面輸入HTML內容",
"redirectTarget": "重定向目標",
"redirectTargetHint": "例如/new-pagehttps://example.com",
"redirectTargetRequired": "請輸入一個重定向目標",
"redirectTargetInvalid": "目標必須是相對路徑(/)或絕對 URLhttp/https",
"deletePage": "刪除頁面",
"deletePageConfirm": "您確定要刪除此頁面嗎?",
"savePage": "保存頁面",
"pageCreatedSuccess": "頁面創建成功",
"pageUpdatedSuccess": "頁面更新成功",
"pageDeletedSuccess": "頁面刪除成功",
"uploadFiles": "上傳檔案",
"uploadPath": "上傳路徑",
"uploadPathHint": "/ (根目錄) 或 /assets/images/",
"uploadPathRequired": "請輸入一個上傳路徑",
"uploadPathMustStartWithSlash": "路徑以/開始",
"uploadPathNoSpaces": "路徑不能包含空格",
"uploadPathNoConsecutiveSlashes": "路徑不能包含連續的斜槓",
"percentCompleted": "{}%已完成",
"filesToUpload": "{} 個檔案要上傳",
"fileSizeKb": "大小:{} KB",
"uploadingEllipsis": "上傳中……",
"uploadFilesCount": {
"one": "Upload {} File",
"other": "Upload {} Files"
"one": "上傳 {} 個檔案",
"other": "上傳 {} 個檔案"
},
"allUploadsCompleted": "All uploads completed",
"someUploadsFailed": "Some uploads failed",
"uploadingInProgress": "Uploading in progress",
"readyToUpload": "Ready to upload",
"allFilesUploadedSuccess": "All files uploaded successfully",
"lotteryLastNumberSpecial": "The last selected number will be your special number.",
"lotteryMultiplierRequired": "Please enter a multiplier",
"lotteryMultiplierRange": "Multiplier must be between 1 and 10",
"dropToShare": "Drop to share"
"allUploadsCompleted": "上傳全部完成",
"someUploadsFailed": "部分上傳失敗",
"uploadingInProgress": "正在上傳",
"readyToUpload": "準備好上傳",
"allFilesUploadedSuccess": "全部檔案完成上傳",
"lotteryLastNumberSpecial": "最後一個選擇的數字將是您的特殊數字。",
"lotteryMultiplierRequired": "請輸入一個倍率",
"lotteryMultiplierRange": "倍率需要在1到10之間",
"dropToShare": "拖拽以分享",
"affiliationSpell": "Affiliation Spell",
"affiliationSpellHint": "If you have an affiliation spell, enter it here.",
"friendsOnline": "Friends Online",
"createAccountAlmostThere": "Almost There",
"createAccountAlmostThereHint": "You're one step away from joining the Solar Network! Please solve the captcha puzzle shows next.",
"createAccountNotice": "Things you need to know before you create an account:",
"createAccountConfirmEmail": "After your account being created, you need go to your email inbox to active your account to get permission to use all features.",
"createAccountNoAltAccounts": "Multiple or alternative accounts are banned from the Solar Network, that will violates our terms of services.",
"createAccountAgreeTerms": "I've read these terms and agree to the terms of service.",
"createAccountProfile": "Create your profile",
"createAccountToS": "Review Terms & Conditions",
"updateYourProfileDescription": "Adjust how you looks on the Solar Network.",
"realmsDescription": "Manage realms you've joined.",
"exploreDescription": "Explore contents on the Solar Network.",
"accountDescription": "Information about your account.",
"chatDescription": "Group Chats and Direct Messages",
"connectionServerDown": "Unable to Connect",
"appSettingsDescription": "Customize your app.",
"accountSettingsDescription": "Manage your preferences on the Solar Network.",
"walletDescription": "Your source point wallet.",
"relationshipsDescription": "Friends and connections.",
"notificationsDescription": "See what's happended related to you recently.",
"settingsFestivalFeatures": "Festival Limited Features",
"categoriesAndTags": "Categories & Tags",
"webArticlesStandDescription": "Explore external sites articles.",
"aboutDescription": "Learn more about the Solar Network.",
"abuseReportsDescription": "View and manage abuse reports.",
"stickerMarketplaceDescription": "Browse and add sticker packs from the Solar Network marketplace.",
"webFeedsDescription": "Browse and subscribe to web feeds from the Solar Network.",
"discoverRealmsDescription": "Discover new realms and join them.",
"postShuffleDescription": "Shuffle posts to see the posts randomly.",
"levelingDescription": "See your leveling progress and history.",
"notableDayToday": "{} is today!",
"authSessionLogout": "Logout Session",
"authSessionLogoutHint": "Are you sure you want to logout this session? This will terminate this specific login session.",
"filesDescription": "Manage your files on the Solar Network Drive.",
"postComposeDescription": "Compose a new post",
"searchPostsDescription": "Search posts by title, content, or else.",
"accountActivationAlert": "Activate your account",
"accountActivationAlertHint": "Unactivated account may leads to various of permission issues, activate your account by clicking the link we sent to your email inbox.",
"accountActivationResendHint": "Didn't see it? Try click the button below to resend one. If you need to update your email while your account was unactivated, feel free to contact our customer service.",
"accountActivationResend": "Resend",
"ipAddress": "IP Address",
"noFurtherData": "No further data",
"searchAnything": "Search Anything...",
"tapToViewAllNotifications": "Tap to view all notifications",
"mostRecent": "Most Recent",
"noNotificationsYet": "No notifications yet",
"recentChats": "Recent Chats",
"noFeaturedPostsAvailable": "No featured posts available",
"searchChatsAndPages": "Search chats and pages...",
"dashboard": "Dashboard",
"dashboardDescription": "All your data in one place.",
"postTagsCategories": "Post Tags and Categories",
"postTagsCategoriesDescription": "Browse posts by category and tags.",
"debugLogs": "Debug Logs",
"debugLogsDescription": "View debug logs for troubleshooting.",
"pinChatRoom": "Pin Chat Room",
"pinChatRoomDescription": "Pin this chat room to the top.",
"chatRoomPinned": "Chat room pinned successfully.",
"chatRoomUnpinned": "Chat room unpinned successfully.",
"pinnedChatRoom": "Pinned Rooms",
"settingsGroupedChatList": "Grouped Chat List",
"settingsNotifyWithHaptic": "Notification with Haptic Feedback",
"settingsDashSearchEngine": "Search Engine for web",
"settingsDashSearchEngineHelper": "Use %s as the placeholder for the query.",
"settingsDefaultScreen": "Default Screen",
"notableDayChristmas": "Christmas",
"notableDayNewYear": "New Year"
}

View File

@@ -0,0 +1,287 @@
# ActivityPub Implementation for Solar Network
## Overview
This document outlines the initial implementation of ActivityPub federation for the Solar Network (DysonNetwork), following the plan outlined in `ACTIVITYPUB_PLAN.md`.
## What Has Been Created
### 1. Database Models (DysonNetwork.Shared/Models)
All ActivityPub-related models are shared across projects and located in `DysonNetwork.Shared/Models/`:
#### FediverseInstance.cs
- Tracks ActivityPub instances (servers) in the fediverse
- Stores instance metadata, blocking status, and activity tracking
- Links to actors and content from that instance
#### FediverseActor.cs
- Represents remote actors (users/accounts) from other instances
- Stores actor information including keys, inbox/outbox URLs
- Links to instance and manages relationships
- Tracks whether the actor is a bot, locked, or discoverable
#### FediverseContent.cs
- Stores content (posts, notes, etc.) received from the fediverse
- Supports multiple content types (Note, Article, Image, Video, etc.)
- Includes attachments, mentions, tags, and emojis
- Links to local posts for unified display
#### FediverseActivity.cs
- Tracks ActivityPub activities (Create, Follow, Like, Announce, etc.)
- Stores raw activity data and processing status
- Links to actors, content, and local entities
- Supports both incoming and outgoing activities
#### FediverseRelationship.cs
- Manages follow relationships between local and remote actors
- Tracks relationship state (Pending, Accepted, Rejected)
- Supports muting and blocking
- Links to local accounts/publishers
#### FediverseReaction.cs
- Stores reactions (likes, emoji) from both local and remote actors
- Links to content and actor
- Supports federation of reactions
### 2. Database Migration
**File**: `DysonNetwork.Sphere/Migrations/20251228120000_AddActivityPubModels.cs`
This migration creates the following tables:
- `fediverse_instances` - Instance tracking
- `fediverse_actors` - Remote actor profiles
- `fediverse_contents` - Federated content storage
- `fediverse_activities` - Activity tracking and processing
- `fediverse_relationships` - Follow relationships
- `fediverse_reactions` - Reactions from fediverse
### 3. API Controllers (DysonNetwork.Sphere/ActivityPub)
#### WebFingerController.cs
- **Endpoint**: `GET /.well-known/webfinger?resource=acct:<username>@<domain>`
- **Purpose**: Allows other instances to discover actors via WebFinger protocol
- **Response**: Returns actor's inbox/outbox URLs and profile page links
- Maps local Publishers to ActivityPub actors
#### ActivityPubController.cs
Provides three main endpoints:
1. **GET /activitypub/actors/{username}**
- Returns ActivityPub actor profile in JSON-LD format
- Includes actor's keys, inbox, outbox, followers, and following URLs
- Maps SnPublisher to ActivityPub Person type
2. **GET /activitypub/actors/{username}/outbox**
- Returns actor's outbox collection
- Lists public posts as ActivityPub activities
- Supports pagination
3. **POST /activitypub/actors/{username}/inbox**
- Receives incoming ActivityPub activities
- Supports Create, Follow, Like, Announce activities
- Placeholder for activity processing logic
## Architecture
### Data Flow
```
Remote Instance Solar Network (Sphere)
│ │
│ ───WebFinger─────> │
│ │
│ <───Actor JSON──── │
│ │
│ ───Activity─────> │ → Inbox Processing
│ │
│ <───Activity────── │ ← Outbox Distribution
```
### Model Relationships
- `SnFediverseInstance` has many `SnFediverseActor`
- `SnFediverseInstance` has many `SnFediverseContent`
- `SnFediverseActor` has many `SnFediverseContent`
- `SnFediverseActor` has many `SnFediverseActivity`
- `SnFediverseActor` has many `SnFediverseRelationship` (as follower and following)
- `SnFediverseContent` has many `SnFediverseActivity`
- `SnFediverseContent` has many `SnFediverseReaction`
- `SnFediverseContent` optionally links to `SnPost` (local copy)
### Local to Fediverse Mapping
| Solar Network Model | ActivityPub Type |
|-------------------|-----------------|
| SnPublisher | Person (Actor) |
| SnPost | Note / Article |
| SnPostReaction | Like / EmojiReact |
| Follow | Follow Activity |
| SnPublisherSubscription | Follow Relationship |
## Next Steps
### Stage 1: Core Infrastructure ✅ (COMPLETED)
- ✅ Create database models for ActivityPub entities
- ✅ Create database migration
- ✅ Implement basic WebFinger endpoint
- ✅ Implement basic Actor endpoint
- ✅ Implement Inbox/Outbox endpoints
### Stage 2: Activity Processing ✅ (COMPLETED)
- ✅ Implement HTTP Signature verification (ActivityPubSignatureService)
- ✅ Process incoming activities:
- Follow/Accept/Reject
- Create (incoming posts)
- Like/Announce
- Delete/Update
- Undo
- ✅ Generate outgoing activities (ActivityPubDeliveryService)
- ✅ Queue and retry failed deliveries (basic implementation)
### Stage 3: Key Management ✅ (COMPLETED)
- ✅ Generate RSA key pairs for each Publisher (ActivityPubKeyService)
- ✅ Store public/private keys in Publisher.Meta
- ✅ Sign outgoing HTTP requests
- ✅ Verify incoming HTTP signatures
### Stage 4: Content Federation (IN PROGRESS)
- ✅ Convert between SnPost and ActivityPub Note/Article (basic mapping)
- ✅ Handle content attachments and media
- ✅ Support content warnings and sensitive content
- ✅ Handle replies, boosts, and mentions
- ⏳ Add local post reference for federated content
- ⏳ Handle media attachments in federated content
### Stage 5: Relationship Management ✅ (COMPLETED)
- ✅ Handle follow/unfollow logic
- ✅ Update followers/following collections
- ✅ Block/mute functionality (data model ready)
- ✅ Relationship state machine (Pending, Accepted, Rejected)
### Stage 6: Testing & Interop (NEXT)
- ⏳ Test with Mastodon instances
- ⏳ Test with Pleroma/Akkoma instances
- ⏳ Test with Lemmy instances
- ⏳ Verify WebFinger and actor discovery
- ⏳ Test activity delivery and processing
## Implementation Details
### Core Services
#### 1. ActivityPubKeyService
- Generates RSA 2048-bit key pairs for ActivityPub
- Signs data with private key
- Verifies signatures with public key
- Key stored in `SnPublisher.Meta["private_key"]` and `["public_key"]`
#### 2. ActivityPubSignatureService
- Verifies incoming HTTP Signature headers
- Signs outgoing HTTP requests
- Manages key retrieval and storage
- Builds signing strings according to ActivityPub spec
#### 3. ActivityPubActivityProcessor
- Processes all incoming activity types
- Follow: Creates relationship, sends Accept
- Accept: Updates relationship to accepted state
- Reject: Updates relationship to rejected state
- Create: Stores federated content
- Like: Records like reaction
- Announce: Increments boost count
- Undo: Reverts previous actions
- Delete: Soft-deletes federated content
- Update: Marks content as edited
#### 4. ActivityPubDeliveryService
- Sends Follow activities to remote instances
- Sends Accept activities in response to follows
- Sends Create activities (posts) to followers
- Sends Like activities to remote instances
- Sends Undo activities
- Fetches remote actor profiles on-demand
### Data Flow
#### Incoming Activity Flow
```
Remote Server → HTTP Signature Verification → Activity Type → Specific Handler
Database Update & Response
```
#### Outgoing Activity Flow
```
Local Action → Create Activity → Sign with Key → Send to Followers' Inboxes
Track Status & Retry
```
## Configuration
Add to `appsettings.json`:
```json
{
"ActivityPub": {
"Domain": "your-domain.com",
"EnableFederation": true
}
}
```
## Database Migration
To apply the migration:
```bash
cd DysonNetwork.Sphere
dotnet ef database update
```
## Testing
### WebFinger
```bash
curl "https://your-domain.com/.well-known/webfinger?resource=acct:username@your-domain.com"
```
### Actor Profile
```bash
curl -H "Accept: application/activity+json" https://your-domain.com/activitypub/actors/username
```
### Outbox
```bash
curl -H "Accept: application/activity+json" https://your-domain.com/activitypub/actors/username/outbox
```
## Notes
- All models follow the existing Solar Network patterns (ModelBase, NodaTime, JSON columns)
- Controllers use standard ASP.NET Core patterns with dependency injection
- Database uses PostgreSQL with JSONB for flexible metadata storage
- Migration follows existing naming conventions
- Soft delete is enabled on all models
## References
- [ActivityPub W3C Recommendation](https://www.w3.org/TR/activitypub/)
- [ActivityStreams 2.0](https://www.w3.org/TR/activitystreams-core/)
- [WebFinger RFC 7033](https://tools.ietf.org/html/rfc7033)
- [Mastodon Federation Documentation](https://docs.joinmastodon.org/spec/activitypub/)
## TODOs
- [ ] Implement HTTP Signature verification middleware
- [ ] Create activity processor service
- [ ] Implement activity queue and retry logic
- [ ] Add key generation for Publishers
- [ ] Implement content conversion between formats
- [ ] Add inbox background worker
- [ ] Add outbox delivery worker
- [ ] Implement relationship management logic
- [ ] Add moderation tools for federated content
- [ ] Add federation metrics and monitoring
- [ ] Write comprehensive tests

View File

@@ -0,0 +1,197 @@
🛠️ ActivityPub 接入 Solar Network 的分步清单
🧱 1. 准备 & 设计阶段
1.1 理解 ActivityPub 的核心概念
• Actor / Object / Activity / Collection
• Outbox / Inbox / Followers 列表
ActivityPub 是使用 JSON-LD + ActivityStreams 2.0 来描述社交行为的规范。
1.2 映射你现有的 Solar Domain 结构
把你现在 Solar Network 的用户、帖子、关注、点赞等:
• 映射为 ActivityPub 的 Actor / Note / Follow / Like 等
• 明确本地模型与 ActivityStreams 对应关系
比如:
• Solar User → ActivityPub Actor
• Post → ActivityPub Note/Object
• Like → ActivityPub Like Activity
这一步是关键的领域建模设计。
🚪 2. Actor 发现与必要入口
2.1 实现 WebFinger
为每个用户提供 WebFinger endpoint
GET /.well-known/webfinger?resource=acct:<username>@<domain>
用来让远端服务器查出 actor 细节(包括 inbox/outbox URL
2.2 Actor 资源 URL
确保每个用户有一个全局可访问的 URL例如
https://solar.io/users/alice
并在其 JSON-LD 中包含:
• inbox
• outbox
• followers
• following
这些是 ActivityPub 基础通信的入口。
📮 3. 核心协议实现
3.1 Inbox / Outbox 接口
Inbox接收来自其他实例的 Activity
Outbox本地用户发布 Activity 的出口)
Outbox 需要:
• 生成 activity JSONCreate、Follow、Like 等)
• 存储至本地数据库
• 推送到各 follower 的 Inbox
Inbox 需要:
• 接收并 parse Activity
• 验证签名
• 处理活动(如接受 Follow记录远程 Post 等)
注意:
• 请求需要验证 HTTP Signatures远端服务器签名
• 必须满足 ActivityPub 规范对字段的要求。
🔐 4. 安全与签名
4.1 Actor Keys
每个 Actor 对应一对 RSA / Ed25519 密钥:
• 私钥用于签名发送到其它服务器的请求
• 公钥发布在 Actor JSON 中供对方验证
远端服务器发送到你的 Inbox 时,需要:
• 使用对方的公钥验证签名
HTTP Signatures 是服务器间通信安全的一部分,防止伪造请求。
🌐 5. 实现联邦逻辑
5.1 关注逻辑
处理:
• Follow Activity
• Accept / Reject Activity
• 更新本地 followers / following 数据
实现流程参考1. 本地用户发起 Follow 2. 推送 Follow 到远端 Inbox 3. 等待远端发送 Accept 或 Reject
5.2 推送 content联邦同步
当本地用户发布内容时:
• 从 Outbox 取出 Create Activity
• 发送到所有远端 followers 的 Inbox
注意:你可以缓存远端 followers 数据表来减少重复请求。
📡 6. 消息处理与存储
6.1 本地对象缓存
对于接收到的远端内容Post / Note / Like 等):
• 需要保存到 Solar 的数据库
• 供 UI / API 生成用户时间线
这使得 Solar 能把远端联邦内容与本地内容统一展示。
6.2 处理 Collections
ActivityPub 定义了 Collection 类型用于:
• followers 列表
• liked 列表
• outbox、inbox
你需要实现这些集合的获取与分页逻辑。
🔁 7. 与现有 Solar Network API 协调
你可能已经有本地的帖子、用户 API。那么
• 把这套 API 与 ActivityPub 同步层绑定
• 决定哪些内容对外发布
• 决定哪些 Activity 类型需要响应
比如:
Solar Post Create -> 生成 ActivityPub Create Note -> 发往联邦
📦 8. 测试与兼容性
8.1 与现存联邦测试
用已存在的 ActivityPub 实例测试兼容性:
• Mastodon
• Pleroma
• Lemmy 等
检查:
• 对方是否能关注 Solar 用户
• Solar 是否能接收远端内容
ActivityPub 规范W3C Recommendation有详细规范流包括
• Server to Server API
你最重要的目标是与现存实例互操作。
🧪 9. UX & 监控支持
9.1 用户显示远端内容
从 Inbox 收到内容后:
• 如何展示在 Solar UI
• 链接远端用户的展示名 / 头像
9.2 监控 & 审计
• 失败的推送
• 无法验证签名的请求
• 阻止 spam / 恶意 Activity
🏁 10. 逐步推进
建议按阶段 rollout
阶段 目标
Stage 1 实现 Actor / WebFinger / Outbox / Inbox 基本框架
Stage 2 支持 Follow / Accept / Reject Activity
Stage 3 支持 Create / Like / Announce
Stage 4 与远端实例互联测试
Stage 5 UI & Feed 统一显示本地 + 联邦内容
📌 小结
核心步骤总结1. 映射 Solar Network 数据模型到 ActivityPub 2. 实现 WebFinger + Actor JSON-LD 3. 实现 Inbox 和 Outbox endpoints 4. 管理 Actor Keys 与 HTTP Signatures 5. 处理关注/发帖/点赞等 Activity 6. 推送到远端 / 接收远端同步 7. 将远端内容存入 Solar 并展示 8. 测试与现有 Fediverse 实例互通
这套步骤覆盖了 ActivityPub 协议必须实现的点和实际联邦要处理的逻辑。
如果你想,我可以进一步展开 Solar Network 对应的具体 API 设计模板(包括 Inbox / Outbox 的 REST 定义与 JSON 输出示例),甚至帮你写 可运行的 Go / .NET 样例代码。你希望从哪一部分开始深入?

View File

@@ -0,0 +1,273 @@
# ActivityPub Implementation Summary
## What Has Been Implemented
### 1. Database Models ✅
All models located in `DysonNetwork.Shared/Models/`:
| Model | Purpose | Key Features |
|--------|---------|--------------|
| `SnFediverseInstance` | Track fediverse servers | Domain blocking, metadata, activity tracking |
| `SnFediverseActor` | Remote user profiles | Keys, inbox/outbox URLs, relationships |
| `SnFediverseContent` | Federated posts/notes | Multiple content types, attachments, mentions, tags |
| `SnFediverseActivity` | Activity tracking | All activity types, processing status, raw data |
| `SnFediverseRelationship` | Follow relationships | State machine, muting/blocking |
| `SnFediverseReaction` | Federated reactions | Likes, emoji reactions |
### 2. Database Migrations ✅
- `20251228120000_AddActivityPubModels.cs` - Core ActivityPub tables
- `20251228130000_AddPublisherMetaForActivityPubKeys.cs` - Publisher metadata for keys
### 3. Core Services ✅
#### ActivityPubKeyService
- **Location**: `DysonNetwork.Sphere/ActivityPub/ActivityPubKeyService.cs`
- **Responsibilities**:
- Generate RSA 2048-bit key pairs
- Sign data with private key
- Verify signatures with public key
- **Key Storage**: Keys stored in `SnPublisher.Meta`
#### ActivityPubSignatureService
- **Location**: `DysonNetwork.Sphere/ActivityPub/ActivityPubSignatureService.cs`
- **Responsibilities**:
- Verify incoming HTTP Signature headers
- Sign outgoing HTTP requests
- Build signing strings per ActivityPub spec
- Manage key retrieval for actors
- **Signature Algorithm**: RSA-SHA256
#### ActivityPubActivityProcessor
- **Location**: `DysonNetwork.Sphere/ActivityPub/ActivityPubActivityProcessor.cs`
- **Supported Activities**:
- ✅ Follow - Creates relationship, sends Accept
- ✅ Accept - Updates relationship to accepted
- ✅ Reject - Updates relationship to rejected
- ✅ Create - Stores federated content
- ✅ Like - Records like reaction
- ✅ Announce - Increments boost count
- ✅ Undo - Reverts previous actions
- ✅ Delete - Soft-deletes federated content
- ✅ Update - Marks content as edited
#### ActivityPubDeliveryService
- **Location**: `DysonNetwork.Sphere/ActivityPub/ActivityPubDeliveryService.cs`
- **Outgoing Activities**:
- ✅ Follow - Send to remote actors
- ✅ Accept - Respond to follow requests
- ✅ Create - Send new posts to followers
- ✅ Like - Send to remote instances
- ✅ Undo - Undo previous actions
- **Features**:
- HTTP signature signing
- Remote actor fetching
- Follower discovery
### 4. API Controllers ✅
#### WebFingerController
- **Location**: `DysonNetwork.Sphere/ActivityPub/WebFingerController.cs`
- **Endpoints**:
- `GET /.well-known/webfinger?resource=acct:<username>@<domain>`
- **Purpose**: Allow remote instances to discover local actors
#### ActivityPubController
- **Location**: `DysonNetwork.Sphere/ActivityPub/ActivityPubController.cs`
- **Endpoints**:
- `GET /activitypub/actors/{username}` - Actor profile in JSON-LD
- `GET /activitypub/actors/{username}/outbox` - Public posts
- `POST /activitypub/actors/{username}/inbox` - Receive activities
- **Features**:
- Public key in actor profile
- ActivityPub JSON-LD responses
- HTTP signature verification on inbox
- Activity processing pipeline
### 5. Model Updates ✅
- Added `Meta` field to `SnPublisher` for storing ActivityPub keys
- All models follow existing Solar Network patterns
## How It Works
### Incoming Activity Flow
```
1. Remote server sends POST to /inbox
2. HTTP Signature is verified
3. Activity type is identified
4. Specific handler processes activity:
- Follow: Create relationship, send Accept
- Create: Store content
- Like: Record reaction
- etc.
5. Database is updated
6. Response sent
```
### Outgoing Activity Flow
```
1. Local action occurs (post, like, follow)
2. Activity is created in ActivityPub format
3. Remote followers are discovered
4. HTTP request is signed with publisher's private key
5. Activity sent to each follower's inbox
6. Status logged
```
### Key Management
```
1. Publisher creates post/follows
2. Check if keys exist in Publisher.Meta
3. If not, generate RSA 2048-bit key pair
4. Store keys in Publisher.Meta
5. Use keys for signing
```
## Configuration
Add to `appsettings.json`:
```json
{
"ActivityPub": {
"Domain": "your-domain.com",
"EnableFederation": true
}
}
```
## API Endpoints
### WebFinger
```bash
GET /.well-known/webfinger?resource=acct:username@domain.com
Accept: application/jrd+json
```
### Actor Profile
```bash
GET /activitypub/actors/username
Accept: application/activity+json
```
### Outbox
```bash
GET /activitypub/actors/username/outbox
Accept: application/activity+json
```
### Inbox
```bash
POST /activitypub/actors/username/inbox
Content-Type: application/activity+json
Signature: keyId="...",algorithm="...",headers="...",signature="..."
```
## Database Schema
### Fediverse Tables
- `fediverse_instances` - Server metadata and blocking
- `fediverse_actors` - Remote actor profiles
- `fediverse_contents` - Federated posts/notes
- `fediverse_activities` - Activity tracking
- `fediverse_relationships` - Follow relationships
- `fediverse_reactions` - Federated reactions
### Publisher Enhancement
- Added `publishers.meta` JSONB column for key storage
## Next Steps
### Immediate (Ready for Testing)
- Apply database migrations
- Test WebFinger with a Mastodon instance
- Test follow/unfollow with another instance
- Test receiving posts from federated timeline
### Short Term
- Add HTTP Signature verification middleware
- Implement activity queue with retry logic
- Add background worker for processing queued activities
- Add metrics and monitoring
- Implement local content display in timelines
### Long Term
- Add Media support for federated content
- Implement content filtering
- Add moderation tools for federated content
- Support more activity types
- Implement instance block list management
## Compatibility
The implementation follows:
- ✅ [ActivityPub W3C Recommendation](https://www.w3.org/TR/activitypub/)
- ✅ [ActivityStreams 2.0](https://www.w3.org/TR/activitystreams-core/)
- ✅ [WebFinger RFC 7033](https://tools.ietf.org/html/rfc7033)
- ✅ [HTTP Signatures](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures)
## Testing
### Local Testing
```bash
# 1. Apply migrations
cd DysonNetwork.Sphere
dotnet ef database update
# 2. Test WebFinger
curl "http://localhost:5000/.well-known/webfinger?resource=acct:username@localhost"
# 3. Test Actor
curl -H "Accept: application/activity+json" http://localhost:5000/activitypub/actors/username
```
### Federation Testing
1. Set up a Mastodon instance (or use a public one)
2. Follow a Mastodon user from Solar Network
3. Create a post on Solar Network
4. Verify it appears on Mastodon timeline
## Architecture Decisions
1. **Key Storage**: Using `SnPublisher.Meta` JSONB field for flexibility
2. **Content Storage**: Federated content stored separately from local posts
3. **Relationship State**: Implemented with explicit states (Pending, Accepted, Rejected)
4. **Signature Algorithm**: RSA-SHA256 for compatibility
5. **Activity Processing**: Synchronous for now, can be made async with queue
6. **Content Types**: Support for Note, Article initially (can expand)
## Notes
- All ActivityPub communication uses HTTP Signatures
- Private keys never leave the server
- Public keys are published in actor profiles
- Soft delete is enabled on all federated models
- Failed activity deliveries are logged but not retried (future enhancement)
- Content is federated only when visibility is Public
## Files Created/Modified
### New Files
- `DysonNetwork.Shared/Models/FediverseInstance.cs`
- `DysonNetwork.Shared/Models/FediverseActor.cs`
- `DysonNetwork.Shared/Models/FediverseContent.cs`
- `DysonNetwork.Shared/Models/FediverseActivity.cs`
- `DysonNetwork.Shared/Models/FediverseRelationship.cs`
- `DysonNetwork.Shared/Models/FediverseReaction.cs`
- `DysonNetwork.Sphere/ActivityPub/WebFingerController.cs`
- `DysonNetwork.Sphere/ActivityPub/ActivityPubController.cs`
- `DysonNetwork.Sphere/ActivityPub/ActivityPubKeyService.cs`
- `DysonNetwork.Sphere/ActivityPub/ActivityPubSignatureService.cs`
- `DysonNetwork.Sphere/ActivityPub/ActivityPubActivityProcessor.cs`
- `DysonNetwork.Sphere/ActivityPub/ActivityPubDeliveryService.cs`
- `DysonNetwork.Sphere/Migrations/20251228120000_AddActivityPubModels.cs`
- `DysonNetwork.Sphere/Migrations/20251228130000_AddPublisherMetaForActivityPubKeys.cs`
### Modified Files
- `DysonNetwork.Shared/Models/Publisher.cs` - Added Meta field
- `DysonNetwork.Sphere/AppDatabase.cs` - Added DbSets for ActivityPub
- `DysonNetwork.Sphere/Startup/ServiceCollectionExtensions.cs` - Registered ActivityPub services
## References
- [ActivityPub Implementation Guide](./ACTIVITYPUB_IMPLEMENTATION.md)
- [ActivityPub Plan](./ACTIVITYPUB_PLAN.md)
- [Solar Network Architecture](./README.md)

View File

@@ -0,0 +1,820 @@
# ActivityPub Testing Guide for Solar Network
This guide will help you test the ActivityPub implementation in Solar Network, starting with a self-hosted instance and then moving to a real instance.
## Prerequisites
- ✅ Solar Network codebase with ActivityPub implementation
- ✅ Docker installed (for running Mastodon/Fediverse instances)
- ✅ PostgreSQL database running
-`.NET 10` SDK
## Part 1: Set Up a Self-Hosted Test Instance
### Option A: Using Mastodon (Recommended for Compatibility)
#### 1. Create a Docker Compose File
Create `docker-compose.mastodon-test.yml`:
```yaml
version: '3'
services:
db:
restart: always
image: postgres:14-alpine
environment:
POSTGRES_USER: mastodon
POSTGRES_PASSWORD: mastodon_password
POSTGRES_DB: mastodon
networks:
- mastodon_network
healthcheck:
test: ["CMD", "pg_isready", "-U", "mastodon"]
interval: 5s
retries: 5
redis:
restart: always
image: redis:7-alpine
networks:
- mastodon_network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
retries: 5
es:
restart: always
image: docker.elastic.co/elasticsearch:8.10.2
environment:
- "discovery.type=single-node"
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- "xpack.security.enabled=false"
networks:
- mastodon_network
healthcheck:
test: ["CMD-SHELL", "curl -silent http://localhost:9200/_cluster/health || exit 1"]
interval: 10s
retries: 10
web:
restart: always
image: tootsuite/mastodon:latest
env_file: .env.mastodon
command: bash -c "rm -f /mastodon/tmp/pids/server.pid; bundle exec rails s -p 3000"
ports:
- "3001:3000"
depends_on:
- db
- redis
- es
networks:
- mastodon_network
volumes:
- ./mastodon-data/public:/mastodon/public/system
streaming:
restart: always
image: tootsuite/mastodon:latest
env_file: .env.mastodon
command: node ./streaming
ports:
- "4000:4000"
depends_on:
- db
- redis
networks:
- mastodon_network
sidekiq:
restart: always
image: tootsuite/mastodon:latest
env_file: .env.mastodon
command: bundle exec sidekiq
depends_on:
- db
- redis
networks:
- mastodon_network
networks:
mastodon_network:
driver: bridge
```
#### 2. Create Environment File
Create `.env.mastodon`:
```bash
# Federation
LOCAL_DOMAIN=mastodon.local
LOCAL_HTTPS=false
# Database
DB_HOST=db
DB_PORT=5432
DB_USER=mastodon
DB_NAME=mastodon
DB_PASS=mastodon_password
# Redis
REDIS_HOST=redis
REDIS_PORT=6379
# Elasticsearch
ES_ENABLED=true
ES_HOST=es
ES_PORT=9200
# Secrets (generate these!)
SECRET_KEY_BASE=change_me_to_a_random_string_at_least_32_chars
OTP_SECRET=change_me_to_another_random_string
# Defaults
SINGLE_USER_MODE=false
DEFAULT_LOCALE=en
```
**Generate secrets:**
```bash
# Run these to generate random secrets
openssl rand -base64 32
```
#### 3. Start Mastodon
```bash
docker-compose -f docker-compose.mastodon-test.yml up -d
# Check logs
docker-compose -f docker-compose.mastodon-test.yml logs -f web
```
Wait for the web service to be healthy (may take 2-5 minutes).
#### 4. Create a Mastodon Account
```bash
# Run this command to create an admin account
docker-compose -f docker-compose.mastodon-test.yml exec web \
bin/tootctl accounts create \
testuser \
testuser@mastodon.local \
--email=test@example.com \
--confirmed \
--role=admin \
--approve
```
Set password: `TestPassword123!`
#### 5. Update Your /etc/hosts
```bash
sudo nano /etc/hosts
```
Add:
```
127.0.0.1 mastodon.local
127.0.0.1 solar.local
```
### Option B: Using GoToSocial (Lightweight Alternative)
Create `docker-compose.gotosocial.yml`:
```yaml
version: '3'
services:
gotosocial:
image: superseriousbusiness/gotosocial:latest
environment:
- GTS_HOST=gotosocial.local
- GTS_ACCOUNT_DOMAIN=gotosocial.local
- GTS_PROTOCOL=http
- GTS_DB_TYPE=sqlite
- GTS_DB_ADDRESS=/gotosocial/data/sqlite.db
- GTS_STORAGE_LOCAL_BASE_PATH=/gotosocial/data/storage
ports:
- "3002:8080"
volumes:
- ./gotosocial-data:/gotosocial/data
networks:
default:
```
Start it:
```bash
docker-compose -f docker-compose.gotosocial.yml up -d
```
Create account:
```bash
docker-compose -f docker-compose.gotosocial.yml exec gotosocial \
/gotosocial/gotosocial admin account create \
--username testuser \
--email test@example.com \
--password TestPassword123!
```
## Part 2: Configure Solar Network for Federation
### 1. Update appsettings.json
Edit `DysonNetwork.Sphere/appsettings.json`:
```json
{
"ActivityPub": {
"Domain": "solar.local",
"EnableFederation": true
},
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://solar.local:5000"
}
}
}
}
```
### 2. Update /etc/hosts
Add both instances:
```
127.0.0.1 mastodon.local
127.0.0.1 solar.local
127.0.0.1 gotosocial.local
```
### 3. Apply Database Migrations
```bash
cd DysonNetwork.Sphere
dotnet ef database update
```
### 4. Start Solar Network
```bash
dotnet run --project DysonNetwork.Sphere
```
Solar Network should now be running on `http://solar.local:5000`
## Part 3: Create Test Users
### In Solar Network
1. Open http://solar.local:5000 (or your web interface)
2. Create a new account/publisher named `solaruser`
3. Note down the publisher ID for later
**Or via API** (if you have an existing account):
```bash
# First, create a publisher in Solar Network
curl -X POST http://solar.local:5000/api/publishers \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"name": "solaruser",
"nick": "Solar User",
"bio": "Testing ActivityPub federation!",
"type": 0
}'
```
### In Mastodon
Open http://mastodon.local:3001 and log in with:
- Username: `testuser`
- Password: `TestPassword123!`
## Part 4: Test Federation Scenarios
### Test 1: WebFinger Discovery
**Goal**: Verify Solar Network is discoverable
```bash
# Query Solar Network's WebFinger endpoint
curl -v "http://solar.local:5000/.well-known/webfinger?resource=acct:solaruser@solar.local"
# Expected response (200 OK):
{
"subject": "acct:solaruser@solar.local",
"links": [
{
"rel": "self",
"type": "application/activity+json",
"href": "https://solar.local:5000/activitypub/actors/solaruser"
},
{
"rel": "http://webfinger.net/rel/profile-page",
"type": "text/html",
"href": "https://solar.local:5000/users/solaruser"
}
]
}
```
### Test 2: Fetch Actor Profile
**Goal**: Get ActivityPub actor JSON
```bash
# Fetch Solar Network actor from Mastodon
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/solaruser
# Expected response includes:
{
"@context": ["https://www.w3.org/ns/activitystreams"],
"id": "https://solar.local:5000/activitypub/actors/solaruser",
"type": "Person",
"preferredUsername": "solaruser",
"inbox": "https://solar.local:5000/activitypub/actors/solaruser/inbox",
"outbox": "https://solar.local:5000/activitypub/actors/solaruser/outbox",
"followers": "https://solar.local:5000/activitypub/actors/solaruser/followers",
"publicKey": {
"id": "https://solar.local:5000/activitypub/actors/solaruser#main-key",
"owner": "https://solar.local:5000/activitypub/actors/solaruser",
"publicKeyPem": "-----BEGIN PUBLIC KEY-----\n..."
}
}
```
### Test 3: Follow from Mastodon to Solar Network
**Goal**: Mastodon user follows Solar Network user
1. **In Mastodon**:
- Go to http://mastodon.local:3001
- In search bar, type: `@solaruser@solar.local`
- Click the follow button
2. **Verify in Solar Network**:
```bash
# Check database for relationship
psql -d dyson_network -c \
"SELECT * FROM fediverse_relationships WHERE is_local_actor = true;"
```
3. **Check Solar Network logs**:
Should see:
```
Processing activity type: Follow from actor: ...
Processed follow from ... to ...
```
4. **Verify Mastodon receives Accept**:
- Check Mastodon logs for Accept activity
- Verify follow appears as accepted in Mastodon
### Test 4: Follow from Solar Network to Mastodon
**Goal**: Solar Network user follows Mastodon user
You'll need to call the ActivityPub delivery service:
```bash
# Via API (you'll need to implement this endpoint):
curl -X POST http://solar.local:5000/api/activitypub/follow \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"targetActorUri": "http://mastodon.local:3001/users/testuser"
}'
```
**Or test directly with curl** (simulating a Follow activity):
```bash
# Create a Follow activity
curl -X POST http://solar.local:5000/activitypub/actors/solaruser/inbox \
-H "Content-Type: application/activity+json" \
-d '{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "http://mastodon.local:3001/test-follow-activity",
"type": "Follow",
"actor": "http://mastodon.local:3001/users/testuser",
"object": "https://solar.local:5000/activitypub/actors/solaruser"
}'
```
### Test 5: Create a Post in Solar Network
**Goal**: Post federates to Mastodon
1. **Create a post via Solar Network API**:
```bash
curl -X POST http://solar.local:5000/api/posts \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"content": "Hello fediverse! Testing ActivityPub from Solar Network! 🚀",
"visibility": 0,
"publisherId": "PUBLISHER_ID"
}'
```
2. **Wait a few seconds**
3. **Check in Mastodon**:
- Go to http://mastodon.local:3001
- The post should appear in the federated timeline
- It should show `@solaruser@solar.local` as the author
4. **Verify Solar Network logs**:
```
Successfully sent activity to http://mastodon.local:3001/inbox
```
### Test 6: Like from Mastodon
**Goal**: Mastodon user likes a Solar Network post
1. **In Mastodon**:
- Find the Solar Network post
- Click the favorite/like button
2. **Verify in Solar Network**:
```bash
psql -d dyson_network -c \
"SELECT * FROM fediverse_reactions;"
```
3. **Check Solar Network logs**:
```
Processing activity type: Like from actor: ...
Processed like from ...
```
### Test 7: Reply from Mastodon
**Goal**: Reply federates to Solar Network
1. **In Mastodon**:
- Reply to the Solar Network post
- Write: "@solaruser Nice to meet you!"
2. **Verify in Solar Network**:
```bash
psql -d dyson_network -c \
"SELECT * FROM fediverse_contents WHERE in_reply_to IS NOT NULL;"
```
## Part 5: Debugging and Troubleshooting
### Enable Detailed Logging
Edit `appsettings.json`:
```json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"DysonNetwork.Sphere.ActivityPub": "Trace"
}
}
}
```
### Check Database State
```bash
# Check actors
psql -d dyson_network -c \
"SELECT uri, username, display_name FROM fediverse_actors;"
# Check contents
psql -d dyson_network -c \
"SELECT uri, type, content FROM fediverse_contents;"
# Check relationships
psql -d dyson_network -c \
"SELECT * FROM fediverse_relationships;"
# Check activities
psql -d dyson_network -c \
"SELECT type, status, error_message FROM fediverse_activities;"
# Check failed activities
psql -d dyson_network -c \
"SELECT * FROM fediverse_activities WHERE status = 3;" # 3 = Failed
```
### Common Issues
#### Issue: "Failed to verify signature"
**Cause**: HTTP Signature verification failed
**Solutions**:
1. Check the signature header format
2. Verify public key matches actor's keyId
3. Ensure Date header is within 5 minutes
4. Check host header matches request URL
#### Issue: "Target actor or inbox not found"
**Cause**: Remote actor not fetched yet
**Solutions**:
1. Manually fetch the actor first
2. Check actor URL is correct
3. Verify remote instance is accessible
#### Issue: "Content already exists"
**Cause**: Duplicate activity received
**Solutions**:
1. This is normal - deduplication is working
2. Check if content appears correctly
#### Issue: CORS errors when testing from browser
**Cause**: Browser blocking cross-origin requests
**Solutions**:
1. Use curl for API testing
2. Or disable CORS in development
3. Test directly from Mastodon interface
### View HTTP Signatures
For debugging, you can inspect the signature:
```bash
# From Mastodon to Solar Network
curl -v -X POST http://solar.local:5000/activitypub/actors/solaruser/inbox \
-H "Content-Type: application/activity+json" \
-d '{"type":"Follow",...}'
```
Look for the `Signature` header in the output.
### Test HTTP Signature Verification Manually
Create a test script `test-signature.js`:
```javascript
const crypto = require('crypto');
// Test signature verification
const publicKey = `-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----`;
const signingString = `(request-target): post /activitypub/actors/solaruser/inbox
host: solar.local:5000
date: ${new Date().toUTCString()}
content-length: ...`;
const signature = '...';
const verify = crypto.createVerify('SHA256');
verify.update(signingString);
const isValid = verify.verify(publicKey, signature, 'base64');
console.log('Signature valid:', isValid);
```
## Part 6: Test with a Real Instance
### Preparing for Public Federation
1. **Get a real domain** (e.g., via ngrok or a VPS)
```bash
# Using ngrok for testing
ngrok http 5000
# This gives you: https://random-id.ngrok-free.app
```
2. **Update Solar Network config**:
```json
{
"ActivityPub": {
"Domain": "your-domain.com",
"EnableFederation": true
}
}
```
3. **Update DNS** (if using real domain):
- Add A record pointing to your server
- Configure HTTPS (required for production federation)
4. **Test WebFinger with your domain**:
```bash
curl "https://your-domain.com/.well-known/webfinger?resource=acct:username@your-domain.com"
```
### Test with Mastodon.social
1. **Create a Mastodon.social account**
- Go to https://mastodon.social
- Sign up for a test account
2. **Search for your Solar Network user**:
- In Mastodon.social search: `@username@your-domain.com`
- Click follow
3. **Create a post in Solar Network**
- Should appear in Mastodon.social
4. **Reply from Mastodon.social**
- Should appear in Solar Network
### Test with Other Instances
- **Pleroma**: Similar to Mastodon, good for testing
- **Lemmy**: For testing community features (later)
- **Pixelfed**: For testing media posts
- **PeerTube**: For testing video content (later)
## Part 7: Verification Checklist
### Self-Hosted Instance Tests
- [ ] WebFinger returns correct actor links
- [ ] Actor profile has all required fields
- [ ] Follow from Mastodon to Solar Network works
- [ ] Follow from Solar Network to Mastodon works
- [ ] Accept activity sent back to Mastodon
- [ ] Posts from Solar Network appear in Mastodon timeline
- [ ] Posts from Mastodon appear in Solar Network database
- [ ] Likes from Mastodon appear in Solar Network
- [ ] Replies from Mastodon appear in Solar Network
- [ ] Keys are properly generated and stored
- [ ] HTTP signatures are correctly verified
- [ ] Outbox returns public posts
### Real Instance Tests
- [ ] Domain is publicly accessible
- [ ] HTTPS is working (or HTTP for local testing)
- [ ] WebFinger works with your domain
- [ ] Actor is discoverable from other instances
- [ ] Posts federate to public instances
- [ ] Users can follow across instances
- [ ] Timelines show federated content
## Part 8: Monitoring During Tests
### Check Solar Network Logs
```bash
# Follow logs in real-time
dotnet run --project DysonNetwork.Sphere | grep -i activitypub
```
### Check Mastodon Logs
```bash
docker-compose -f docker-compose.mastodon-test.yml logs -f web | grep -i federation
```
### Monitor Database Activity
```bash
# Watch activity table
watch -n 2 'psql -d dyson_network -c "SELECT type, status, created_at FROM fediverse_activities ORDER BY created_at DESC LIMIT 10;"'
```
### Check Network Traffic
```bash
# Monitor HTTP requests
tcpdump -i lo port 5000 or port 3001 -A
```
## Part 9: Advanced Testing
### Test HTTP Signature Fallbacks
Test with various signature headers:
```bash
# With Date header
curl -H "Date: $(date -u +%a,\ %d\ %b\ %Y\ %T\ GMT)" ...
# With Digest header
curl -H "Digest: SHA-256=$(echo -n '{}' | openssl dgst -sha256 -binary | base64)" ...
# Multiple signed headers
curl -H "Signature: keyId=\"...\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest\",signature=\"...\"" ...
```
### Test Rate Limiting
Send multiple requests quickly:
```bash
for i in {1..10}; do
curl -X POST http://solar.local:5000/activitypub/actors/solaruser/inbox \
-H "Content-Type: application/activity+json" \
-d '{"type":"Create",...}'
done
```
### Test Large Posts
Send post with attachments:
```bash
curl -X POST http://solar.local:5000/api/posts \
-H "Content-Type: application/json" \
-d '{
"content": "A post with an image",
"attachments": [{"id": "file-id"}],
"visibility": 0
}'
```
## Part 10: Cleanup
### Stop Test Instances
```bash
# Stop Mastodon
docker-compose -f docker-compose.mastodon-test.yml down
# Stop GoToSocial
docker-compose -f docker-compose.gotosocial.yml down
# Remove data volumes
docker-compose -f docker-compose.mastodon-test.yml down -v
```
### Reset Solar Network Database
```bash
# Warning: This deletes all data!
cd DysonNetwork.Sphere
dotnet ef database drop
dotnet ef database update
```
### Remove /etc/hosts Entries
```bash
sudo nano /etc/hosts
# Remove these lines:
# 127.0.0.1 mastodon.local
# 127.0.0.1 solar.local
# 127.0.0.1 gotosocial.local
```
## Next Steps After Testing
1. **Fix any issues found during testing**
2. **Add retry logic for failed deliveries**
3. **Implement activity queue for async processing**
4. **Add monitoring and metrics**
5. **Test with more instances (Pleroma, Pixelfed, etc.)**
6. **Add support for more activity types**
7. **Improve error handling and logging**
8. **Add admin interface for managing federation**
## Useful Tools
### ActivityPub Testing Tools
- [ActivityPub Playground](https://swicth.github.io/activity-pub-playground/)
- [FediTest](https://feditest.com/)
- [FediVerse.net](https://fedi.net/)
### HTTP Testing
- [curl](https://curl.se/)
- [httpie](https://httpie.io/)
- [Postman](https://www.postman.com/)
### JSON Inspection
- [jq](https://stedolan.github.io/jq/)
- [jsonpath.com](https://jsonpath.com/)
### Network Debugging
- [Wireshark](https://www.wireshark.org/)
- [tcpdump](https://www.tcpdump.org/)
## References
- [ActivityPub W3C Spec](https://www.w3.org/TR/activitypub/)
- [HTTP Signatures Draft](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures)
- [WebFinger RFC 7033](https://tools.ietf.org/html/rfc7033)
- [Mastodon Federation Documentation](https://docs.joinmastodon.org/admin/federation/)

View File

@@ -0,0 +1,506 @@
# ActivityPub Testing Helper API
This document describes helper endpoints for testing ActivityPub federation.
## Purpose
These endpoints allow you to manually trigger ActivityPub activities for testing purposes without implementing the full UI federation integration yet.
## Helper Endpoints
### 1. Send Follow Activity
**Endpoint**: `POST /api/activitypub/test/follow`
**Description**: Sends a Follow activity to a remote actor
**Request Body**:
```json
{
"targetActorUri": "http://mastodon.local:3001/users/testuser"
}
```
**Response**:
```json
{
"success": true,
"activityId": "http://solar.local:5000/activitypub/activities/...",
"targetActor": "http://mastodon.local:3001/users/testuser"
}
```
### 2. Send Like Activity
**Endpoint**: `POST /api/activitypub/test/like`
**Description**: Sends a Like activity for a post (can be local or remote)
**Request Body**:
```json
{
"postId": "POST_ID",
"targetActorUri": "http://mastodon.local:3001/users/testuser"
}
```
**Response**:
```json
{
"success": true,
"activityId": "http://solar.local:5000/activitypub/activities/..."
}
```
### 3. Send Announce (Boost) Activity
**Endpoint**: `POST /api/activitypub/test/announce`
**Description**: Boosts a post to followers
**Request Body**:
```json
{
"postId": "POST_ID"
}
```
### 4. Send Undo Activity
**Endpoint**: `POST /api/activitypub/test/undo`
**Description**: Undoes a previous activity
**Request Body**:
```json
{
"activityType": "Like", // or "Follow", "Announce"
"objectUri": "http://solar.local:5000/activitypub/objects/POST_ID"
}
```
### 5. Get Federation Status
**Endpoint**: `GET /api/activitypub/test/status`
**Description**: Returns current federation statistics
**Response**:
```json
{
"actors": {
"total": 5,
"local": 1,
"remote": 4
},
"contents": {
"total": 25,
"byType": {
"Note": 20,
"Article": 5
}
},
"relationships": {
"total": 8,
"accepted": 6,
"pending": 1,
"rejected": 1
},
"activities": {
"total": 45,
"byStatus": {
"Completed": 40,
"Pending": 3,
"Failed": 2
},
"byType": {
"Create": 20,
"Follow": 8,
"Accept": 6,
"Like": 5,
"Announce": 3,
"Undo": 2,
"Delete": 1
}
}
}
```
### 6. Get Recent Activities
**Endpoint**: `GET /api/activitypub/test/activities`
**Query Parameters**:
- `limit`: Number of activities to return (default: 20)
- `type`: Filter by activity type (optional)
**Response**:
```json
{
"activities": [
{
"id": "ACTIVITY_ID",
"type": "Follow",
"status": "Completed",
"actorUri": "http://mastodon.local:3001/users/testuser",
"objectUri": "http://solar.local:5000/activitypub/actors/solaruser",
"createdAt": "2024-01-15T10:30:00Z",
"errorMessage": null
}
]
}
```
### 7. Get Actor Keys
**Endpoint**: `GET /api/activitypub/test/actors/{username}/keys`
**Description**: Returns the public/private key pair for a publisher
**Response**:
```json
{
"username": "solaruser",
"hasKeys": true,
"actorUri": "http://solar.local:5000/activitypub/actors/solaruser",
"publicKeyId": "http://solar.local:5000/activitypub/actors/solaruser#main-key",
"publicKey": "-----BEGIN PUBLIC KEY-----\n...",
"privateKeyStored": true
}
```
### 8. Test HTTP Signature
**Endpoint**: `POST /api/activitypub/test/sign`
**Description**: Test if a signature string is valid for a given public key
**Request Body**:
```json
{
"publicKey": "-----BEGIN PUBLIC KEY-----\n...",
"signingString": "(request-target): post /inbox\nhost: example.com\ndate: ...",
"signature": "..."
}
```
**Response**:
```json
{
"valid": true,
"message": "Signature is valid"
}
```
## Controller Implementation
Create `DysonNetwork.Sphere/ActivityPub/ActivityPubTestController.cs`:
```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DysonNetwork.Sphere.ActivityPub;
[ApiController]
[Route("api/activitypub/test")]
[Authorize] // Require auth for testing
public class ActivityPubTestController(
AppDatabase db,
ActivityPubDeliveryService deliveryService,
ActivityPubKeyService keyService,
ActivityPubSignatureService signatureService,
IConfiguration configuration,
ILogger<ActivityPubTestController> logger
) : ControllerBase
{
[HttpPost("follow")]
public async Task<ActionResult> TestFollow([FromBody] TestFollowRequest request)
{
var currentUser = GetCurrentUser();
var publisher = await GetPublisherForUser(currentUser.Id);
if (publisher == null)
return BadRequest("Publisher not found");
var success = await deliveryService.SendFollowActivityAsync(
publisher.Id,
request.TargetActorUri
);
return Ok(new
{
success,
targetActorUri = request.TargetActorUri,
publisherId = publisher.Id
});
}
[HttpPost("like")]
public async Task<ActionResult> TestLike([FromBody] TestLikeRequest request)
{
var currentUser = GetCurrentUser();
var publisher = await GetPublisherForUser(currentUser.Id);
var success = await deliveryService.SendLikeActivityAsync(
request.PostId,
currentUser.Id,
request.TargetActorUri
);
return Ok(new { success, postId = request.PostId });
}
[HttpPost("announce")]
public async Task<ActionResult> TestAnnounce([FromBody] TestAnnounceRequest request)
{
var post = await db.Posts.FindAsync(request.PostId);
if (post == null)
return NotFound();
var success = await deliveryService.SendCreateActivityAsync(post);
return Ok(new { success, postId = request.PostId });
}
[HttpPost("undo")]
public async Task<ActionResult> TestUndo([FromBody] TestUndoRequest request)
{
var currentUser = GetCurrentUser();
var publisher = await GetPublisherForUser(currentUser.Id);
if (publisher == null)
return BadRequest("Publisher not found");
var success = await deliveryService.SendUndoActivityAsync(
request.ActivityType,
request.ObjectUri,
publisher.Id
);
return Ok(new { success, activityType = request.ActivityType });
}
[HttpGet("status")]
public async Task<ActionResult> GetStatus()
{
var totalActors = await db.FediverseActors.CountAsync();
var localActors = await db.FediverseActors
.CountAsync(a => a.Uri.Contains("solar.local"));
var totalContents = await db.FediverseContents.CountAsync();
var relationships = await db.FediverseRelationships
.GroupBy(r => r.State)
.Select(g => new { State = g.Key, Count = g.Count() })
.ToListAsync();
var activitiesByStatus = await db.FediverseActivities
.GroupBy(a => a.Status)
.Select(g => new { Status = g.Key, Count = g.Count() })
.ToListAsync();
var activitiesByType = await db.FediverseActivities
.GroupBy(a => a.Type)
.Select(g => new { Type = g.Key, Count = g.Count() })
.ToListAsync();
return Ok(new
{
actors = new
{
total = totalActors,
local = localActors,
remote = totalActors - localActors
},
contents = new
{
total = totalContents
},
relationships = relationships.ToDictionary(r => r.State.ToString(), r => r.Count),
activities = new
{
byStatus = activitiesByStatus.ToDictionary(a => a.Status.ToString(), a => a.Count),
byType = activitiesByType.ToDictionary(a => a.Type.ToString(), a => a.Count)
}
});
}
[HttpGet("activities")]
public async Task<ActionResult> GetActivities([FromQuery] int limit = 20, [FromQuery] string? type = null)
{
var query = db.FediverseActivities
.OrderByDescending(a => a.CreatedAt);
if (!string.IsNullOrEmpty(type))
{
query = query.Where(a => a.Type.ToString() == type);
}
var activities = await query
.Take(limit)
.Select(a => new
{
a.Id,
a.Type,
a.Status,
ActorUri = a.Actor.Uri,
ObjectUri = a.ObjectUri,
a.CreatedAt,
a.ErrorMessage
})
.ToListAsync();
return Ok(new { activities });
}
[HttpGet("actors/{username}/keys")]
public async Task<ActionResult> GetActorKeys(string username)
{
var publisher = await db.Publishers
.FirstOrDefaultAsync(p => p.Name == username);
if (publisher == null)
return NotFound();
var actorUrl = $"http://solar.local:5000/activitypub/actors/{username}";
var (privateKey, publicKey) = keyService.GenerateKeyPair();
return Ok(new
{
username,
hasKeys = publisher.Meta != null,
actorUri,
publicKeyId = $"{actorUrl}#main-key",
publicKey = publicKey,
privateKeyStored = publisher.Meta != null
});
}
[HttpPost("sign")]
public ActionResult TestSignature([FromBody] TestSignatureRequest request)
{
var isValid = keyService.Verify(
request.PublicKey,
request.SigningString,
request.Signature
);
return Ok(new
{
valid = isValid,
message = isValid ? "Signature is valid" : "Signature is invalid"
});
}
private async Task<SnPublisher?> GetPublisherForUser(Guid accountId)
{
return await db.Publishers
.Include(p => p.Members)
.Where(p => p.Members.Any(m => m.AccountId == accountId))
.FirstOrDefaultAsync();
}
private Guid GetCurrentUser()
{
// Implement based on your auth system
return Guid.Empty;
}
}
public class TestFollowRequest
{
public string TargetActorUri { get; set; } = string.Empty;
}
public class TestLikeRequest
{
public Guid PostId { get; set; }
public string TargetActorUri { get; set; } = string.Empty;
}
public class TestAnnounceRequest
{
public Guid PostId { get; set; }
}
public class TestUndoRequest
{
public string ActivityType { get; set; } = string.Empty;
public string ObjectUri { get; set; } = string.Empty;
}
public class TestSignatureRequest
{
public string PublicKey { get; set; } = string.Empty;
public string SigningString { get; set; } = string.Empty;
public string Signature { get; set; } = string.Empty;
}
```
## Testing with Helper Endpoints
### 1. Test Follow
```bash
curl -X POST http://solar.local:5000/api/activitypub/test/follow \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"targetActorUri": "http://mastodon.local:3001/users/testuser"
}'
```
### 2. Test Like
```bash
curl -X POST http://solar.local:5000/api/activitypub/test/like \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"postId": "YOUR_POST_ID",
"targetActorUri": "http://mastodon.local:5000/activitypub/actors/mastodonuser"
}'
```
### 3. Check Status
```bash
curl http://solar.local:5000/api/activitypub/test/status \
-H "Authorization: Bearer YOUR_TOKEN"
```
### 4. Get Recent Activities
```bash
curl "http://solar.local:5000/api/activitypub/test/activities?limit=10" \
-H "Authorization: Bearer YOUR_TOKEN"
```
## Integration with Main Flow
These helper endpoints can be used to:
1. **Quickly test federation** without full UI integration
2. **Debug specific activity types** in isolation
3. **Verify HTTP signatures** are correct
4. **Test error handling** for various scenarios
5. **Monitor federation status** during development
## Security Notes
- All test endpoints require authentication
- Use only in development/staging environments
- Remove or disable in production
- Rate limiting recommended if exposing to public
## Cleanup
After testing, you can:
1. Remove the test controller (optional)
2. Disable test endpoints
3. Clear test activities from database
4. Reset test relationships
```sql
-- Clear test data
DELETE FROM fediverse_activities WHERE created_at < NOW() - INTERVAL '1 day';
```

View File

@@ -0,0 +1,448 @@
# ActivityPub Testing - Complete Guide
This is the complete guide for testing ActivityPub federation in Solar Network.
## 📁 File Overview
| File | Purpose | When to Use |
|------|---------|--------------|
| `setup-activitypub-test.sh` | One-command setup of test environment | First time setup |
| `test-activitypub.sh` | Quick validation of basic functionality | After setup, before detailed tests |
| `ACTIVITYPUB_TESTING_QUICKSTART.md` | Quick start reference | Getting started quickly |
| `ACTIVITYPUB_TESTING_GUIDE.md` | Comprehensive testing scenarios | Full testing workflow |
| `ACTIVITYPUB_TESTING_QUICKREF.md` | Command and query reference | Daily testing |
| `ACTIVITYPUB_TESTING_HELPER_API.md` | Helper API for testing | Programmatic testing |
| `ACTIVITYPUB_TEST_RESULTS_TEMPLATE.md` | Track test results | During testing |
| `ACTIVITYPUB_IMPLEMENTATION.md` | Implementation details | Understanding the code |
| `ACTIVITYPUB_SUMMARY.md` | Feature summary | Reviewing what's implemented |
## 🚀 Quick Start (5 Minutes)
### 1. Setup Test Environment
```bash
./setup-activitypub-test.sh
```
This will:
- ✅ Configure `/etc/hosts`
- ✅ Start Mastodon via Docker
- ✅ Create test Mastodon account
- ✅ Apply database migrations
### 2. Validate Setup
```bash
./test-activitypub.sh
```
This checks:
- ✅ WebFinger endpoint
- ✅ Actor profile
- ✅ Public keys
- ✅ Database tables
### 3. Start Solar Network
```bash
cd DysonNetwork.Sphere
dotnet run
```
### 4. Test Federation
1. Open http://mastodon.local:3001
2. Search for `@solaruser@solar.local`
3. Click Follow
4. Create a post in Solar Network
5. Verify it appears in Mastodon
## 📖 Recommended Reading Order
### For First-Time Testing
1. **Start Here**: `ACTIVITYPUB_TESTING_QUICKSTART.md`
- Overview of the setup
- Quick command reference
- Common commands
2. **Then**: `ACTIVITYPUB_TESTING_GUIDE.md`
- Detailed test scenarios
- Step-by-step instructions
- Troubleshooting
3. **Reference**: `ACTIVITYPUB_TESTING_QUICKREF.md`
- Command snippets
- Database queries
- Response codes
### During Testing
1. **Track Progress**: `ACTIVITYPUB_TEST_RESULTS_TEMPLATE.md`
- Checklists for each test
- Results tracking
- Issue logging
2. **Helper API**: `ACTIVITYPUB_TESTING_HELPER_API.md`
- Manual testing endpoints
- Debugging tools
- Status monitoring
### For Understanding
1. **Implementation**: `ACTIVITYPUB_IMPLEMENTATION.md`
- Architecture details
- Service descriptions
- Data flow diagrams
2. **Features**: `ACTIVITYPUB_SUMMARY.md`
- What's implemented
- Model relationships
- API endpoints
## 🔍 Test Scenarios Summary
### Basic Functionality (All instances must pass)
- [ ] WebFinger discovery works
- [ ] Actor profile is valid JSON-LD
- [ ] Public key is present
- [ ] Outbox returns public posts
- [ ] Inbox accepts activities
### Federation - Follow
- [ ] Remote user can follow local user
- [ ] Local user can follow remote user
- [ ] Accept activity is sent/received
- [ ] Relationship state is correct
- [ ] Unfollow works correctly
### Federation - Content
- [ ] Local posts federate to remote instances
- [ ] Remote posts appear in local database
- [ ] Post content is preserved
- [ ] Timestamps are correct
- [ ] Attachments are handled
- [ ] Content warnings are respected
### Federation - Interactions
- [ ] Likes federate correctly
- [ ] Likes appear in both instances
- [ ] Replies federate correctly
- [ ] Reply threading works
- [ ] Boosts/Announces work
- [ ] Undo activities work
### Security
- [ ] HTTP signatures are verified
- [ ] Invalid signatures are rejected
- [ ] Keys are properly stored
- [ ] Private keys never exposed
## 🐛 Common Issues & Solutions
### Issue: "Failed to verify signature"
**Causes**:
1. Signature header format is wrong
2. Public key doesn't match keyId
3. Date header is too old (>5 minutes)
4. Request body doesn't match digest
**Solutions**:
1. Check signature format: `keyId="...",algorithm="...",headers="...",signature="..."`
2. Verify keyId in actor profile
3. Ensure Date header is recent
4. Check body is exactly what was signed
### Issue: "Target actor or inbox not found"
**Causes**:
1. Actor hasn't been fetched yet
2. Actor URL is incorrect
3. Remote instance is inaccessible
**Solutions**:
1. Manually fetch actor first
2. Verify actor URL is correct
3. Test accessibility with curl
### Issue: Activities not arriving
**Causes**:
1. Network connectivity issue
2. Remote instance is down
3. Activity wasn't queued properly
**Solutions**:
1. Check network connectivity
2. Verify remote instance is running
3. Check fediverse_activities table for status
## 📊 Monitoring During Tests
### Check Logs
```bash
# Solar Network ActivityPub logs
dotnet run --project DysonNetwork.Sphere 2>&1 | grep -i activitypub
# Mastodon federation logs
docker compose -f docker-compose.mastodon-test.yml logs -f web | grep -i federation
```
### Monitor Database
```bash
# Watch activity table
watch -n 2 'psql -d dyson_network -c \
"SELECT type, status, created_at FROM fediverse_activities ORDER BY created_at DESC LIMIT 5;"'
```
### Test Network
```bash
# Test connectivity between instances
curl -v http://mastodon.local:3001
curl -v http://solar.local:5000
# Test with traceroute (if available)
traceroute mastodon.local
traceroute solar.local
```
## 🎯 Success Criteria
### Minimal Viable Federation
To consider ActivityPub implementation "working", all of these must pass:
- ✅ WebFinger returns actor links
- ✅ Actor profile has all required fields
- ✅ Follow relationships work bidirectionally
- ✅ Public posts federate to followers
- ✅ Incoming posts are stored correctly
- ✅ HTTP signatures are verified
- ✅ Basic interaction types work (Like, Reply)
### Full Production Ready
For production, also need:
- ✅ Activity queue with retry logic
- ✅ Rate limiting on outgoing deliveries
- ✅ Monitoring and alerting
- ✅ Admin interface for federation management
- ✅ Content filtering and moderation
- ✅ Instance blocking capabilities
- ✅ Performance optimization for high volume
## 🔐 Security Checklist
During testing, verify:
- [ ] Private keys are never logged
- [ ] Private keys are never returned in API responses
- [ ] Only public keys are in actor profiles
- [ ] All incoming activities are signature-verified
- [ ] Invalid signatures are rejected with 401
- [ ] TLS is used in production
- [ ] Host header is verified against request URL
## 📈 Performance Metrics
Track these during testing:
| Metric | Target | Actual |
|--------|--------|--------|
| WebFinger response time | <500ms | ___ ms |
| Actor fetch time | <1s | ___ ms |
| Signature verification time | <100ms | ___ ms |
| Activity processing time | <500ms | ___ ms |
| Outgoing delivery success rate | >95% | ___% |
| Outgoing delivery time | <5s | ___ ms |
## 🧪 Testing Checklist
### Self-Hosted Instance Tests
**Setup**:
- [ ] Setup script completed
- [ ] Mast containers running
- [ ] Solar Network running
- [ ] /etc/hosts configured
- [ ] Database migrations applied
**Basic Federation**:
- [ ] WebFinger works
- [ ] Actor profile valid
- [ ] Public key present
- [ ] Outbox accessible
**Follow Flow**:
- [ ] Mastodon → Solar follow works
- [ ] Solar → Mastodon follow works
- [ ] Accept activity sent
- [ ] Relationship state correct
**Content Flow**:
- [ ] Solar posts appear in Mastodon
- [ ] Mastodon posts appear in Solar
- [ ] Content preserved correctly
- [ ] Timestamps correct
**Interactions**:
- [ ] Likes work both ways
- [ ] Replies work both ways
- [ ] Boosts work both ways
- [ ] Undo works
**Security**:
- [ ] HTTP signatures verified
- [ ] Invalid signatures rejected
- [ ] Keys properly managed
### Real Instance Tests
**Discovery**:
- [ ] Domain publicly accessible
- [ ] WebFinger works from public internet
- [ ] Actor discoverable from public instances
**Federation**:
- [ ] Posts federate to public instances
- [ ] Follows work with public instances
- [ ] Interactions work with public instances
## 📝 Testing Notes
### What Worked Well
1. _____________________
2. _____________________
3. _____________________
### What Needs Improvement
1. _____________________
2. _____________________
3. _____________________
### Bugs Found
| # | Description | Severity | Status |
|---|-------------|----------|--------|
| 1 | _____________________ | Low/Medium/High | ☐ Open/☐ Fixed |
| 2 | _____________________ | Low/Medium/High | ☐ Open/☐ Fixed |
| 3 | _____________________ | Low/Medium/High | ☐ Open/☐ Fixed |
## 🎓 Learning Resources
### ActivityPub Specification
- [W3C ActivityPub Recommendation](https://www.w3.org/TR/activitypub/)
- [ActivityStreams 2.0](https://www.w3.org/TR/activitystreams-core/)
- [HTTP Signatures Draft](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures)
### Implementation Guides
- [Mastodon Federation Guide](https://docs.joinmastodon.org/admin/federation/)
- [ActivityPub Testing Best Practices](https://blog.joinmastodon.org/2018/06/27/how-to-implement-a-basic-activitypub-server/)
- [Federation Testing Checklist](https://docs.joinmastodon.org/spec/activitypub/)
### Tools
- [ActivityPub Playground](https://swicth.github.io/activity-pub-playground/)
- [FediTest](https://feditest.com/)
- [JSONPath Online Evaluator](https://jsonpath.com/)
## 🔄 Next Steps After Testing
### Phase 1: Fix Issues
- Address all bugs found during testing
- Improve error messages
- Add better logging
### Phase 2: Enhance Features
- Implement activity queue
- Add retry logic
- Add rate limiting
- Implement instance blocking
### Phase 3: Production Readiness
- Add monitoring and metrics
- Add admin interface
- Add content filtering
- Implement moderation tools
### Phase 4: Additional Features
- Support more activity types
- Support media attachments
- Support polls
- Support custom emojis
## 📞 Getting Help
If you encounter issues:
1. **Check logs**: See the logs section above
2. **Review troubleshooting**: See `ACTIVITYPUB_TESTING_GUIDE.md` Part 5
3. **Check database queries**: Use queries from `ACTIVITYPUB_TESTING_QUICKREF.md`
4. **Validate signatures**: Use helper API in `ACTIVITYPUB_TESTING_HELPER_API.md`
## ✨ Quick Test Commands
### All-in-One Test Sequence
```bash
# 1. Setup
./setup-activitypub-test.sh
# 2. Validate
./test-activitypub.sh
# 3. Test WebFinger
curl "http://solar.local:5000/.well-known/webfinger?resource=acct:solaruser@solar.local"
# 4. Test Actor
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/solaruser
# 5. Test Follow (from Mastodon UI)
# Open http://mastodon.local:3001 and follow @solaruser@solar.local
# 6. Check database
psql -d dyson_network -c "SELECT * FROM fediverse_relationships;"
# 7. Test Post (create in Solar Network UI)
# Should appear in http://mastodon.local:3001
# 8. Verify content
psql -d dyson_network -c "SELECT * FROM fediverse_contents;"
# 9. Test Like (like from Mastodon UI)
# Should appear in fediverse_reactions table
# 10. Check activities
psql -d dyson_network -c "SELECT type, status FROM fediverse_activities;"
```
## 🎉 Conclusion
You now have everything needed to test ActivityPub federation for Solar Network:
- ✅ Self-hosted test environment (Mastodon)
- ✅ Setup automation (setup script)
- ✅ Quick validation (test script)
- ✅ Comprehensive testing guide
- ✅ Helper API for programmatic testing
- ✅ Quick reference for daily use
- ✅ Results template for tracking progress
**Recommended workflow**:
1. Run `setup-activitypub-test.sh`
2. Run `test-activitypub.sh` for validation
3. Follow scenarios in `ACTIVITYPUB_TESTING_GUIDE.md`
4. Use `ACTIVITYPUB_TESTING_HELPER_API.md` for specific tests
5. Track results in `ACTIVITYPUB_TEST_RESULTS_TEMPLATE.md`
6. Reference `ACTIVITYPUB_TESTING_QUICKREF.md` for commands
Good luck with your federation testing! 🚀

View File

@@ -0,0 +1,356 @@
# ActivityPub Testing Quick Reference
## Quick Test Commands
### 1. Test WebFinger
```bash
curl "http://solar.local:5000/.well-known/webfinger?resource=acct:username@solar.local"
```
### 2. Fetch Actor Profile
```bash
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/username
```
### 3. Get Outbox
```bash
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/username/outbox
```
### 4. Send Test Follow (from remote)
```bash
curl -X POST http://solar.local:5000/activitypub/actors/username/inbox \
-H "Content-Type: application/activity+json" \
-d '{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "https://mastodon.local:3001/follow-123",
"type": "Follow",
"actor": "https://mastodon.local:3001/users/remoteuser",
"object": "https://solar.local:5000/activitypub/actors/username"
}'
```
### 5. Send Test Create (post)
```bash
curl -X POST http://solar.local:5000/activitypub/actors/username/inbox \
-H "Content-Type: application/activity+json" \
-d '{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "https://mastodon.local:3001/post-123",
"type": "Create",
"actor": "https://mastodon.local:3001/users/remoteuser",
"object": {
"id": "https://mastodon.local:3001/objects/post-123",
"type": "Note",
"content": "Hello from Mastodon! @username@solar.local",
"attributedTo": "https://mastodon.local:3001/users/remoteuser",
"to": ["https://www.w3.org/ns/activitystreams#Public"]
}
}'
```
### 6. Send Test Like
```bash
curl -X POST http://solar.local:5000/activitypub/actors/username/inbox \
-H "Content-Type: application/activity+json" \
-d '{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "https://mastodon.local:3001/like-123",
"type": "Like",
"actor": "https://mastodon.local:3001/users/remoteuser",
"object": "https://solar.local:5000/activitypub/objects/post-id"
}'
```
## Database Queries
### Check Actors
```sql
SELECT id, uri, username, display_name, instance_id
FROM fediverse_actors;
```
### Check Contents
```sql
SELECT id, uri, type, content, actor_id, created_at
FROM fediverse_contents
ORDER BY created_at DESC
LIMIT 20;
```
### Check Relationships
```sql
SELECT r.id, a1.uri as actor, a2.uri as target, r.state, r.is_following
FROM fediverse_relationships r
JOIN fediverse_actors a1 ON r.actor_id = a1.id
JOIN fediverse_actors a2 ON r.target_actor_id = a2.id;
```
### Check Activities
```sql
SELECT type, status, error_message, created_at
FROM fediverse_activities
ORDER BY created_at DESC
LIMIT 20;
```
### Check Reactions
```sql
SELECT r.type, c.uri as content_uri, a.uri as actor_uri
FROM fediverse_reactions r
JOIN fediverse_contents c ON r.content_id = c.id
JOIN fediverse_actors a ON r.actor_id = a.id;
```
## Check Keys in Publisher
```sql
SELECT id, name, meta
FROM publishers
WHERE meta IS NOT NULL;
```
## Docker Commands
### Start Mastodon
```bash
docker-compose -f docker-compose.mastodon-test.yml up -d
```
### View Mastodon Logs
```bash
docker-compose -f docker-compose.mastodon-test.yml logs -f web
```
### Stop Mastodon
```bash
docker-compose -f docker-compose.mastodon-test.yml down
```
### Start GoToSocial
```bash
docker-compose -f docker-compose.gotosocial.yml up -d
```
## Solar Network Commands
### Run Migrations
```bash
cd DysonNetwork.Sphere
dotnet ef database update
```
### Run with Debug Logging
```bash
dotnet run --project DysonNetwork.Sphere -- --logging:LogLevel:DysonNetwork.Sphere.ActivityPub=Trace
```
## Common Response Codes
| Code | Meaning |
|------|---------|
| 200 | Success |
| 202 | Accepted (activity queued) |
| 401 | Unauthorized (invalid signature) |
| 404 | Not found (user/post doesn't exist) |
| 400 | Bad request (invalid activity) |
## Activity Status Codes
| Status | Code | Meaning |
|--------|------|---------|
| Pending | 0 | Activity waiting to be processed |
| Processing | 1 | Activity being processed |
| Completed | 2 | Activity successfully processed |
| Failed | 3 | Activity processing failed |
## Relationship States
| State | Code | Meaning |
|--------|------|---------|
| Pending | 0 | Follow request sent, waiting for Accept |
| Accepted | 1 | Follow accepted, relationship active |
| Rejected | 2 | Follow rejected |
## Troubleshooting
### "Failed to verify signature"
**Check**: Signature header format
```bash
# Should be:
Signature: keyId="...",algorithm="rsa-sha256",headers="...",signature="..."
```
**Check**: Public key in actor profile
```bash
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/username | jq '.publicKey'
```
### "Actor not found"
**Check**: Actor exists in database
```bash
psql -d dyson_network -c \
"SELECT * FROM fediverse_actors WHERE uri = '...';"
```
**Check**: Actor URL is accessible
```bash
curl -v http://remote-instance.com/users/username
```
### "Content already exists"
This is normal behavior - the system is deduplicating.
### "Target publisher not found"
**Check**: Publisher exists
```bash
psql -d dyson_network -c \
"SELECT * FROM publishers WHERE name = '...';"
```
## Quick Test Sequence
### Full Federation Test
```bash
# 1. Start both instances
docker-compose -f docker-compose.mastodon-test.yml up -d
dotnet run --project DysonNetwork.Sphere
# 2. Test WebFinger
curl "http://solar.local:5000/.well-known/webfinger?resource=acct:solaruser@solar.local"
# 3. Get Actor
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/solaruser
# 4. Send Follow from Mastodon
# (Do this in Mastodon UI or use curl above)
# 5. Check database
psql -d dyson_network -c "SELECT * FROM fediverse_relationships;"
# 6. Send Create (post) from Mastodon
# (Use curl command above)
# 7. Check content
psql -d dyson_network -c "SELECT * FROM fediverse_contents;"
# 8. Send Like from Mastodon
# (Use curl command above)
# 9. Check reactions
psql -d dyson_network -c "SELECT * FROM fediverse_reactions;"
# 10. Check activities
psql -d dyson_network -c "SELECT type, status FROM fediverse_activities;"
```
## Test URLs
| Instance | Web | API | ActivityPub |
|----------|-----|-----|-----------|
| Solar Network | http://solar.local:5000 | http://solar.local:5000/api | http://solar.local:5000/activitypub |
| Mastodon | http://mastodon.local:3001 | http://mastodon.local:3001/api/v1 | http://mastodon.local:3001/inbox |
## Environment Variables
### Solar Network
```bash
export SOLAR_DOMAIN="solar.local"
export SOLAR_URL="http://solar.local:5000"
```
### Mastodon
```bash
export MASTODON_DOMAIN="mastodon.local"
export MASTODON_URL="http://mastodon.local:3001"
```
## Useful jq Commands
### Extract Actor ID
```bash
curl ... | jq '.id'
```
### Extract Inbox URL
```bash
curl ... | jq '.inbox'
```
### Extract Public Key
```bash
curl ... | jq '.publicKey.publicKeyPem'
```
### Pretty Print Activity
```bash
curl ... | jq '.'
```
### Extract Activity Type
```bash
curl ... | jq '.type'
```
## Network Setup
### /etc/hosts
```
127.0.0.1 solar.local
127.0.0.1 mastodon.local
127.0.0.1 gotosocial.local
```
### Ports Used
- Solar Network: 5000
- Mastodon: 3001 (web), 4000 (streaming)
- GoToSocial: 3002
- PostgreSQL: 5432
- Redis: 6379
- Elasticsearch: 9200
## File Locations
### Docker Compose Files
- `docker-compose.mastodon-test.yml`
- `docker-compose.gotosocial.yml`
### Environment Files
- `.env.mastodon`
### Data Volumes
- `./mastodon-data/`
- `./gotosocial-data/`
## Clean Up Commands
```bash
# Reset database
psql -d dyson_network <<EOF
TRUNCATE fediverse_activities CASCADE;
TRUNCATE fediverse_relationships CASCADE;
TRUNCATE fediverse_reactions CASCADE;
TRUNCATE fediverse_contents CASCADE;
TRUNCATE fediverse_actors CASCADE;
TRUNCATE fediverse_instances CASCADE;
UPDATE publishers SET meta = NULL WHERE meta IS NOT NULL;
EOF
# Reset everything
docker-compose -f docker-compose.mastodon-test.yml down -v
docker-compose -f docker-compose.gotosocial.yml down -v
psql -d dyson_network <<EOF
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
EOF
dotnet ef database drop
dotnet ef database update
```

View File

@@ -0,0 +1,289 @@
# ActivityPub Testing - Quick Start
This directory contains everything you need to test ActivityPub federation for Solar Network.
## Quick Start
### 1. Run the Setup Script
```bash
./setup-activitypub-test.sh
```
This will:
- ✅ Check prerequisites (Docker, PostgreSQL)
- ✅ Update `/etc/hosts` with test domains
- ✅ Generate Mastodon environment file
- ✅ Create Docker Compose file
- ✅ Start Mastodon containers
- ✅ Create test Mastodon account
- ✅ Apply Solar Network migrations
### 2. Start Solar Network
```bash
cd DysonNetwork.Sphere
dotnet run
```
### 3. Test Federation
Follow the scenarios in [ACTIVITYPUB_TESTING_GUIDE.md](ACTIVITYPUB_TESTING_GUIDE.md)
## Test Instances
| Service | URL | Notes |
|---------|-----|-------|
| Solar Network | http://solar.local:5000 | Your implementation |
| Mastodon | http://mastodon.local:3001 | Test instance |
| Mastodon Streaming | http://mastodon.local:4000 | WebSocket |
## Test Accounts
### Solar Network
- Create via UI or API
- Username: `solaruser` (or your choice)
### Mastodon
- Username: `testuser@mastodon.local`
- Password: `TestPassword123!`
- Role: Admin
## Quick Test Commands
### Test WebFinger
```bash
curl "http://solar.local:5000/.well-known/webfinger?resource=acct:solaruser@solar.local"
```
### Test Actor
```bash
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/solaruser
```
### Test Outbox
```bash
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/solaruser/outbox
```
### Test Follow (from Mastodon)
1. Open http://mastodon.local:3001
2. Log in as `testuser@mastodon.local`
3. Search for `@solaruser@solar.local`
4. Click Follow
### Test Follow (from Solar Network to Mastodon)
```bash
# Send Follow activity to Solar Network
curl -X POST http://solar.local:5000/activitypub/actors/solaruser/inbox \
-H "Content-Type: application/activity+json" \
-d '{
"@context": "https://www.w3.org/ns/activitystreams",
"id": "http://solar.local:5000/follow-1",
"type": "Follow",
"actor": "https://solar.local:5000/activitypub/actors/solaruser",
"object": "http://mastodon.local:3001/users/testuser"
}'
```
## Documentation Files
| File | Purpose |
|------|---------|
| `ACTIVITYPUB_TESTING_GUIDE.md` | Comprehensive testing guide |
| `ACTIVITYPUB_TESTING_QUICKREF.md` | Quick command reference |
| `ACTIVITYPUB_IMPLEMENTATION.md` | Implementation details |
| `ACTIVITYPUB_SUMMARY.md` | Feature summary |
| `ACTIVITYPUB_PLAN.md` | Original implementation plan |
## Database Checks
### Connect to Database
```bash
psql -d dyson_network
```
### View Actors
```sql
SELECT uri, username, display_name, created_at
FROM fediverse_actors;
```
### View Contents
```sql
SELECT uri, type, content, actor_id, created_at
FROM fediverse_contents
ORDER BY created_at DESC
LIMIT 10;
```
### View Relationships
```sql
SELECT state, is_following, is_followed_by, created_at
FROM fediverse_relationships;
```
### View Activities
```sql
SELECT type, status, error_message, created_at
FROM fediverse_activities
ORDER BY created_at DESC
LIMIT 10;
```
## Logs
### Solar Network Logs
```bash
# Live logs
dotnet run --project DysonNetwork.Sphere
# Follow ActivityPub activity
dotnet run --project DysonNetwork.Sphere 2>&1 | grep -i activitypub
# Debug logging
dotnet run --project DysonNetwork.Sphere --logging:LogLevel:DysonNetwork.Sphere.ActivityPub=Trace
```
### Mastodon Logs
```bash
# All services
docker compose -f docker-compose.mastodon-test.yml logs -f
# Web service only
docker compose -f docker-compose.mastodon-test.yml logs -f web
# Filter for federation
docker compose -f docker-compose.mastodon-test.yml logs -f web | grep -i federation
```
## Stopping Everything
```bash
# Stop Mastodon
docker compose -f docker-compose.mastodon-test.yml down
# Stop with volume cleanup
docker compose -f docker-compose.mastodon-test.yml down -v
# Restore /etc/hosts
sudo mv /etc/hosts.backup /etc/hosts
# Remove test databases (optional)
psql -d dyson_network <<EOF
TRUNCATE fediverse_activities CASCADE;
TRUNCATE fediverse_relationships CASCADE;
TRUNCATE fediverse_reactions CASCADE;
TRUNCATE fediverse_contents CASCADE;
TRUNCATE fediverse_actors CASCADE;
TRUNCATE fediverse_instances CASCADE;
UPDATE publishers SET meta = NULL WHERE meta IS NOT NULL;
EOF
```
## Troubleshooting
### Mastodon won't start
```bash
# Check logs
docker compose -f docker-compose.mastodon-test.yml logs -f web
# Restart
docker compose -f docker-compose.mastodon-test.yml restart
# Recreate
docker compose -f docker-compose.mastodon-test.yml down
docker compose -f docker-compose.mastodon-test.yml up -d
```
### Can't connect to Solar Network
```bash
# Check if running
curl http://solar.local:5000
# Check logs
dotnet run --project DysonNetwork.Sphere 2>&1 | grep -i error
# Restart
# Ctrl+C in terminal and run again
```
### Activities not arriving
```bash
# Check database
psql -d dyson_network -c "SELECT * FROM fediverse_activities WHERE status = 3;"
# Check signature verification logs
dotnet run --project DysonNetwork.Sphere 2>&1 | grep -i "signature"
# Verify actor keys
curl -H "Accept: application/activity+json" \
http://solar.local:5000/activitypub/actors/solaruser | jq '.publicKey'
```
## Testing Checklist
- [ ] Setup script completed successfully
- [ ] Mastodon is running and accessible
- [ ] Solar Network is running and accessible
- [ ] WebFinger returns correct data
- [ ] Actor profile includes public key
- [ ] Follow from Mastodon to Solar Network works
- [ ] Follow from Solar Network to Mastodon works
- [ ] Posts from Solar Network appear in Mastodon
- [ ] Posts from Mastodon appear in Solar Network database
- [ ] Likes federate correctly
- [ ] Replies federate correctly
- [ ] HTTP signatures are verified
- [ ] No errors in logs
- [ ] Database contains expected data
## Next Steps
1. **Test with a real instance**:
- Get a public domain or use ngrok
- Update `ActivityPub:Domain` in appsettings.json
- Test with mastodon.social or other public instances
2. **Add more features**:
- Activity queue for async processing
- Retry logic for failed deliveries
- Metrics and monitoring
- Admin interface for federation management
3. **Test with more instances**:
- Pleroma
- Pixelfed
- Lemmy
- PeerTube
## Getting Help
If something doesn't work:
1. Check the logs (see Logs section above)
2. Review the troubleshooting section in [ACTIVITYPUB_TESTING_GUIDE.md](ACTIVITYPUB_TESTING_GUIDE.md)
3. Verify all prerequisites are installed
4. Check network connectivity between instances
5. Review the [ACTIVITYPUB_IMPLEMENTATION.md](ACTIVITYPUB_IMPLEMENTATION.md) for architecture details
## Useful URLs
### Test Instances
- Mastodon: http://mastodon.local:3001
- Solar Network: http://solar.local:5000
### Documentation
- ActivityPub W3C Spec: https://www.w3.org/TR/activitypub/
- Mastodon Federation Docs: https://docs.joinmastodon.org/admin/federation/
- ActivityPub Playground: https://swicth.github.io/activity-pub-playground/
### Tools
- jq: JSON processor (https://stedolan.github.io/jq/)
- httpie: HTTP client (https://httpie.io/)
- Docker Compose: (https://docs.docker.com/compose/)

View File

@@ -0,0 +1,275 @@
# ActivityPub Testing Guide
Complete guide for testing ActivityPub federation in Solar Network.
## 📚 Documentation Files
| File | Description | Size |
|------|-------------|-------|
| `ACTIVITYPUB_TESTING_INDEX.md` | **START HERE** - Master guide with overview | 12K |
| `ACTIVITYPUB_TESTING_QUICKSTART.md` | Quick reference for common tasks | 7K |
| `ACTIVITYPUB_TESTING_GUIDE.md` | Comprehensive testing scenarios (10 parts) | 19K |
| `ACTIVITYPUB_TESTING_QUICKREF.md` | Command and query reference | 8K |
| `ACTIVITYPUB_TESTING_HELPER_API.md` | Helper API for programmatic testing | 12K |
| `ACTIVITYPUB_TESTING_RESULTS_TEMPLATE.md` | Template to track test results | 10K |
## 🚀 Quick Start
### Option A: One-Command Setup (Recommended)
```bash
# 1. Run setup script
./setup-activitypub-test.sh
# 2. Run validation
./test-activitypub.sh
# 3. Start Solar Network
cd DysonNetwork.Sphere
dotnet run
```
### Option B: Manual Setup
1. **Read**: `ACTIVITYPUB_TESTING_QUICKSTART.md`
2. **Configure**: Copy `.env.testing.example` to `.env` and adjust
3. **Follow**: Step-by-step in `ACTIVITYPUB_TESTING_GUIDE.md`
## 🎯 What You Can Test
### With Self-Hosted Instance
- ✅ WebFinger discovery
- ✅ Actor profile retrieval
- ✅ Follow relationships (bidirectional)
- ✅ Post federation (Solar → Mastodon)
- ✅ Content reception (Mastodon → Solar)
- ✅ Like interactions
- ✅ Reply threading
- ✅ HTTP signature verification
- ✅ Content deletion
### With Real Instance
- ✅ Public domain setup (via ngrok or VPS)
- ✅ Federation with public instances (mastodon.social, etc.)
- ✅ Real-world compatibility testing
- ✅ Performance under real load
## 📋 Testing Workflow
### Day 1: Basic Functionality
- Setup test environment
- Test WebFinger and Actor endpoints
- Verify HTTP signatures
- Test basic follow/unfollow
### Day 2: Content Federation
- Test post creation and delivery
- Test content reception
- Test media attachments
- Test content warnings
### Day 3: Interactions
- Test likes (both directions)
- Test replies and threading
- Test boosts/announces
- Test undo activities
### Day 4: Real Instance
- Set up public domain
- Test with mastodon.social
- Test with other instances
- Verify cross-instance compatibility
### Day 5: Edge Cases
- Test error handling
- Test failed deliveries
- Test invalid signatures
- Test malformed activities
## 🛠️ Setup Scripts
| Script | Purpose |
|--------|---------|
| `setup-activitypub-test.sh` | One-command setup of Mastodon + Solar Network |
| `test-activitypub.sh` | Quick validation of core functionality |
Both scripts are executable (`chmod +x`).
## 🔧 Configuration
### Required Tools
- ✅ Docker (for Mastodon)
- ✅ .NET 10 SDK (for Solar Network)
- ✅ PostgreSQL client (psql)
- ✅ curl (for API testing)
### Quick Setup
```bash
# 1. Install dependencies (Ubuntu/Debian)
sudo apt-get install docker.io docker-compose postgresql-client curl jq
# 2. Run setup
./setup-activitypub-test.sh
# 3. Validate
./test-activitypub.sh
```
## 📊 Progress Tracking
Use the template to track your testing progress:
```bash
# Copy the template
cp ACTIVITYPUB_TESTING_RESULTS_TEMPLATE.md my-test-results.md
# Edit as you test
nano my-test-results.md
```
## 🐛 Troubleshooting
### Quick Fixes
**Mastodon won't start**:
```bash
# Check logs
docker compose -f docker-compose.mastodon-test.yml logs -f
# Restart containers
docker compose -f docker-compose.mastodon-test.yml restart
```
**Can't reach Solar Network**:
```bash
# Check if running
curl http://solar.local:5000
# Check /etc/hosts
cat /etc/hosts | grep solar.local
```
**Activities not arriving**:
```bash
# Check database
psql -d dyson_network -c "SELECT * FROM fediverse_activities;"
# Check logs
dotnet run --project DysonNetwork.Sphere | grep -i activitypub
```
For detailed troubleshooting, see `ACTIVITYPUB_TESTING_GUIDE.md` Part 5.
## 📖 Learning Path
### For Developers
1. Read `ACTIVITYPUB_IMPLEMENTATION.md` to understand the architecture
2. Read `ACTIVITYPUB_SUMMARY.md` to see what's implemented
3. Follow test scenarios in `ACTIVITYPUB_TESTING_GUIDE.md`
4. Use helper API in `ACTIVITYPUB_TESTING_HELPER_API.md` for testing
### For Testers
1. Start with `ACTIVITYPUB_TESTING_QUICKSTART.md`
2. Use command reference in `ACTIVITYPUB_TESTING_QUICKREF.md`
3. Track results with `ACTIVITYPUB_TESTING_RESULTS_TEMPLATE.md`
4. Report issues with details from logs
## 🎓 Success Criteria
### Minimum Viable
- WebFinger works
- Actor profile valid
- Follow relationships work
- Posts federate correctly
- HTTP signatures verified
### Production Ready
- Activity queue with retry
- Rate limiting
- Monitoring/alerting
- Admin interface
- Instance blocking
- Content moderation
## 🚨 Common Pitfalls
### Don't Forget
- ✅ Update `/etc/hosts` with both instances
- ✅ Run migrations before testing
- ✅ Check both instances are accessible
- ✅ Verify PostgreSQL is running
- ✅ Check logs when something fails
### Watch Out For
- ❌ Using `localhost` instead of `solar.local`
- ❌ Forgetting to restart after config changes
- ❌ Not waiting for Mastodon to start (2-5 minutes)
- ❌ Ignoring CORS errors in browser testing
- ❌ Testing with deleted/invisible posts
## 📚 Additional Resources
### Official Specs
- [ActivityPub W3C](https://www.w3.org/TR/activitypub/)
- [ActivityStreams](https://www.w3.org/TR/activitystreams-core/)
- [HTTP Signatures](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures)
### Community Guides
- [Mastodon Federation](https://docs.joinmastodon.org/admin/federation/)
- [Federation Testing](https://docs.joinmastodon.org/spec/activitypub/)
### Tools
- [ActivityPub Playground](https://swicth.github.io/activity-pub-playground/)
- [FediTest](https://feditest.com/)
## 🆘 Support
If you encounter issues:
1. Check logs (both Solar Network and Mastodon)
2. Review troubleshooting section in the guide
3. Validate against success criteria
4. Check database state with queries
5. Review implementation docs
## ✨ Next Steps
After testing with self-hosted instance:
1. Get a public domain or use ngrok
2. Update `ActivityPub:Domain` in appsettings.json
3. Test with public Mastodon instances
4. Add more ActivityPub features (queue, retry, etc.)
5. Implement admin interface
6. Add monitoring and metrics
## 📞 File Reference
All files are in the root of the DysonNetwork project:
```
DysonNetwork/
├── ACTIVITYPUB_TESTING_INDEX.md # Start here!
├── ACTIVITYPUB_TESTING_QUICKSTART.md # Quick reference
├── ACTIVITYPUB_TESTING_GUIDE.md # Full guide
├── ACTIVITYPUB_TESTING_QUICKREF.md # Commands
├── ACTIVITYPUB_TESTING_HELPER_API.md # Test API
├── ACTIVITYPUB_TESTING_RESULTS_TEMPLATE.md
├── setup-activitypub-test.sh # Setup script
├── test-activitypub.sh # Test script
└── .env.testing.example # Config template
```
**Documentation files** (for reference):
```
DysonNetwork/
├── ACTIVITYPUB_IMPLEMENTATION.md # How it's implemented
├── ACTIVITYPUB_SUMMARY.md # Feature summary
└── ACTIVITYPUB_PLAN.md # Original plan
```
---
**Start here**: `ACTIVITYPUB_TESTING_INDEX.md`
**Good luck with your testing!** 🚀

View File

@@ -0,0 +1,282 @@
# ActivityPub Testing Results Template
Use this template to track your testing progress.
## Test Environment
**Date**: ________________
**Test Configuration**:
- Solar Network URL: `http://solar.local:5000`
- Mastodon URL: `http://mastodon.local:3001`
- Database: `dyson_network`
**Solar Network User**:
- Username: `_______________`
- Publisher ID: `_______________`
**Mastodon User**:
- Username: `testuser@mastodon.local`
- Password: `TestPassword123!`
---
## Test Results
### ✅ Part 1: Infrastructure Setup
| Test | Status | Notes |
|------|--------|-------|
| Setup script ran successfully | ☐ ☑ | |
| /etc/hosts updated | ☐ ☑ | |
| Docker containers started | ☐ ☑ | |
| Mastodon web accessible | ☐ ☑ | |
| Mastodon admin account created | ☐ ☑ | |
| Database migrations applied | ☐ ☑ | |
| Solar Network started | ☐ ☑ | |
### ✅ Part 2: WebFinger & Actor Discovery
| Test | Status | Expected | Actual |
|------|--------|---------|--------|
| WebFinger for Solar Network user | ☐ ☑ | Returns subject + links | _______________ |
| Actor profile JSON is valid | ☐ ☑ | Has id, type, inbox, outbox | _______________ |
| Public key present in actor | ☐ ☑ | publicKey.publicKeyPem exists | _______________ |
| Outbox returns public posts | ☐ ☑ | OrderedCollection with items | _______________ |
| Outbox totalItems count | ☐ ☑ | Matches public posts | _______________ |
### ✅ Part 3: Follow Relationships
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Mastodon follows Solar Network user | ☐ ☑ | Relationship created in DB | _______________ |
| Accept sent to Mastodon | ☐ ☑ | Mastodon receives Accept | _______________ |
| Solar Network follows Mastodon user | ☐ ☑ | Relationship created | _______________ |
| Follow appears in Mastodon UI | ☐ ☑ | Mastodon shows "Following" | _______________ |
| Follow appears in Solar Network DB | ☐ ☑ | is_following = true | _______________ |
| Follow state is Accepted | ☐ ☑ | state = 1 (Accepted) | _______________ |
| Unfollow works correctly | ☐ ☑ | Relationship deleted/updated | _______________ |
### ✅ Part 4: Content Federation (Create)
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Post created in Solar Network | ☐ ☑ | Post in sn_posts table | _______________ |
| Activity sent to Mastodon | ☐ ☑ | Logged as successful | _______________ |
| Post appears in Mastodon timeline | ☐ ☑ | Visible in federated timeline | _______________ |
| Post content matches | ☐ ☑ | Same text/HTML | _______________ |
| Post author is correct | ☐ ☑ | Shows Solar Network user | _______________ |
| Post timestamp is correct | ☐ ☑ | Same published time | _______________ |
| Multiple posts federate | ☐ ☑ | All posts appear | _______________ |
### ✅ Part 5: Content Reception (Incoming Create)
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Create activity received | ☐ ☑ | Activity logged in DB | _______________ |
| Content stored in fediverse_contents | ☐ ☑ | Record with correct type | _______________ |
| Content not duplicated | ☐ ☑ | Only one entry per URI | _______________ |
| Actor created/retrieved | ☐ ☑ | Actor in fediverse_actors | _______________ |
| Instance created/retrieved | ☐ ☑ | Instance in fediverse_instances | _______________ |
| Content HTML preserved | ☐ ☑ | contentHtml field populated | _______________ |
### ✅ Part 6: Reaction Federation (Like)
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Like from Mastodon to Solar post | ☐ ☑ | Like activity received | _______________ |
| Reaction stored in fediverse_reactions | ☐ ☑ | Record with type = 0 (Like) | _______________ |
| Like count incremented | ☐ ☑ | like_count increased | _______________ |
| Like appears in UI | ☐ ☑ | Visible on Solar Network | _______________ |
| Like appears in Mastodon | ☐ ☑ | Visible on Mastodon | _______________ |
| Unlike works correctly | ☐ ☑ | Like removed | _______________ |
### ✅ Part 7: Reply Federation
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Reply from Mastodon to Solar post | ☐ ☑ | Create activity with inReplyTo | _______________ |
| Reply stored with parent reference | ☐ ☑ | in_reply_to field set | _______________ |
| Reply appears in Solar Network | ☐ ☑ | Visible as comment | _______________ |
| Reply shows parent context | ☐ ☑ | Links to original post | _______________ |
### ✅ Part 8: Content Deletion
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Delete from Mastodon | ☐ ☑ | Delete activity received | _______________ |
| Content soft-deleted | ☐ ☑ | deleted_at timestamp set | _______________ |
| Content no longer visible | ☐ ☑ | Hidden from timelines | _______________ |
### ✅ Part 9: HTTP Signature Verification
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Valid signature accepted | ☐ ☑ | Activity processed | _______________ |
| Invalid signature rejected | ☐ ☑ | 401 Unauthorized | _______________ |
| Missing signature rejected | ☐ ☑ | 401 Unauthorized | _______________ |
| Signature format correct | ☐ ☑ | keyId, algorithm, headers, signature | _______________ |
| Signing string correct | ☐ ☑ | Matches HTTP-Signatures draft | _______________ |
### ✅ Part 10: Error Handling
| Test | Status | Expected Result | Actual Result |
|------|--------|----------------|---------------|
| Invalid activity type rejected | ☐ ☑ | 400 Bad Request | _______________ |
| Malformed JSON rejected | ☐ ☑ | 400 Bad Request | _______________ |
| Non-existent actor rejected | ☐ ☑ | 404 Not Found | _______________ |
| Errors logged correctly | ☐ ☑ | error_message populated | _______________ |
| Activity status = Failed | ☐ ☑ | status = 3 | _______________ |
---
## Database State After Tests
### Actors Table
```sql
SELECT COUNT(*) as total_actors,
SUM(CASE WHEN is_local_actor THEN 1 ELSE 0 END) as local,
SUM(CASE WHEN NOT is_local_actor THEN 1 ELSE 0 END) as remote
FROM fediverse_relationships;
```
- Total Actors: _______________
- Local Actors: _______________
- Remote Actors: _______________
### Contents Table
```sql
SELECT COUNT(*) as total_contents,
AVG(LENGTH(content)) as avg_content_length
FROM fediverse_contents WHERE deleted_at IS NULL;
```
- Total Contents: _______________
- Avg Content Length: _______________
### Activities Table
```sql
SELECT type, status, COUNT(*)
FROM fediverse_activities
GROUP BY type, status
ORDER BY type, status;
```
- Activities by Type/Status:
- Create: Pending ___, Completed ____, Failed ___
- Follow: Pending ___, Completed ____, Failed ___
- Like: Pending ___, Completed ____, Failed ___
- Accept: Pending ___, Completed ____, Failed ___
### Relationships Table
```sql
SELECT state, COUNT(*) as count
FROM fediverse_relationships
GROUP BY state;
```
- Pending: _______________
- Accepted: _______________
- Rejected: _______________
---
## Logs Analysis
### Solar Network Errors Found:
1. _______________
2. _______________
3. _______________
### Mastodon Errors Found:
1. _______________
2. _______________
3. _______________
### Warnings Found:
1. _______________
2. _______________
3. _______________
---
## Issues & Bugs Found
| # | Severity | Description | Status |
|---|----------|-------------|--------|
| 1 | ☐ Low/Medium/High/Critical | _____________________ | ☐ Open/☐ Fixed |
| 2 | ☐ Low/Medium/High/Critical | _____________________ | ☐ Open/☐ Fixed |
| 3 | ☐ Low/Medium/High/Critical | _____________________ | ☐ Open/☐ Fixed |
| 4 | ☐ Low/Medium/High/Critical | _____________________ | ☐ Open/☐ Fixed |
---
## Performance Notes
| Metric | Value | Notes |
|--------|-------|-------|
| Average activity processing time | __________ ms | |
| Average HTTP signature verification time | __________ ms | |
| Outgoing delivery success rate | __________% | |
| Average WebFinger response time | __________ ms | |
| Database query performance | __________ | |
---
## Compatibility Notes
| Instance | Version | Works | Notes |
|----------|---------|--------|-------|
| Mastodon (self-hosted) | latest | ☐ ☑ | |
| Mastodon.social | ~4.0 | ☐ ☑ | |
| Pleroma | ~2.5 | ☐ ☑ | |
| GoToSocial | ~0.15 | ☐ ☑ | |
---
## Recommendations
### What Worked Well:
1. _____________________
2. _____________________
3. _____________________
### What Needs Improvement:
1. _____________________
2. _____________________
3. _____________________
### Features to Add:
1. _____________________
2. _____________________
3. _____________________
---
## Next Testing Phase
- [ ] Test with public Mastodon instance
- [ ] Test with Pleroma instance
- [ ] Test media attachment federation
- [ ] Test with high-volume posts
- [ ] Test concurrent activity processing
- [ ] Test with different visibility levels
- [ ] Test with long posts (>500 chars)
- [ ] Test with special characters/emojis
---
## Sign-off
**Tested By**: _____________________
**Test Date**: _____________________
**Overall Result**: ☐ Pass / ☐ Fail
**Ready for Production**: ☐ Yes / ☐ No
**Notes**: ___________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

View File

@@ -0,0 +1,425 @@
# Follow Feature - User Guide
## Quick Start: How to Follow Fediverse Users
### Method 1: Via Search (Recommended)
1. Go to the search bar in Solar Network
2. Type the user's full address: `@username@domain.com`
- Example: `@alice@mastodon.social`
- Example: `@bob@pleroma.site`
3. Click on their profile in search results
4. Click the "Follow" button
5. Wait for acceptance (usually immediate)
6. ✅ Done! Their posts will now appear in your timeline
### Method 2: Via Profile URL
1. If you know their profile URL, visit it directly:
- Example: `https://mastodon.social/@alice`
2. Look for the "Follow" button on their profile
3. Click it to follow
4. ✅ You're now following them!
## What Happens When You Follow Someone
### The Technical Flow
```
You click "Follow"
Solar Network creates Follow Activity
Follow Activity is signed with your private key
Solar Network sends Follow to their instance's inbox
Their instance verifies your signature
Their instance processes the Follow
Their instance sends Accept Activity back
Solar Network receives and processes Accept
Relationship is stored in database
Their public posts federate to Solar Network
```
### What You'll See
-**"Following..."** (while waiting for acceptance)
-**"Following" ✓** (when accepted)
-**Their posts** in your home timeline
-**Their likes, replies, boosts** on your posts
## Different Types of Accounts
### Regular Users
- Full ActivityPub support
- Follows work both ways
- Content federates normally
- Example: `@alice@mastodon.social`
### Locked Accounts
- User must manually approve followers
- You'll see "Pending" after clicking follow
- User receives notification to approve/deny
- Example: `@private@pleroma.site`
### Bot/Service Accounts
- Automated content accounts
- Often auto-accept follows
- Example: `@newsbot@botsin.space`
### Organizational Accounts
- Group or team accounts
- Example: `@team@company.social`
## Managing Your Follows
### View Who You're Following
**Go to**: Following page or `GET /api/activitypub/following`
You'll see:
- Username
- Display name
- Profile picture
- When you followed them
- Their instance (e.g., "Mastodon")
### Unfollowing Someone
**Method 1: Via UI**
1. Go to their profile
2. Click "Following" button (shows as active)
3. Click to unfollow
**Method 2: Via API**
```bash
curl -X POST http://solar.local:5000/api/activitypub/unfollow \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"targetActorUri": "https://mastodon.social/users/alice"
}'
```
**Response**:
```json
{
"success": true,
"message": "Unfollowed successfully"
}
```
### View Your Followers
**Go to**: Followers page or `GET /api/activitypub/followers`
You'll see:
- Users following you
- Their instance
- When they started following
- Whether they're local or from another instance
## Searching Fediverse Users
### How Search Works
1. **Type in search bar**: `@username@domain.com`
2. **Solar Network queries their instance**:
- Fetches their actor profile
- Checks if they're discoverable
3. **Shows results**:
- Profile picture
- Display name
- Bio
- Instance name
### Supported Search Formats
| Format | Example | Works? |
|--------|---------|--------|
| Full handle | `@alice@mastodon.social` | ✅ Yes |
| Username only | `alice` | ⚠️ May search local users first |
| Full URL | `https://mastodon.social/@alice` | ✅ Yes |
## Privacy Considerations
### Public Posts
- **What**: Posts visible to everyone
- **Federation**: ✅ Federates to all followers
- **Timeline**: Visible in public federated timelines
- **Example**: General updates, thoughts, content you want to share
### Private Posts
- **What**: Posts only visible to followers
- **Federation**: ✅ Federates to followers (including remote)
- **Timeline**: Only visible to your followers
- **Example**: Personal updates, questions
### Unlisted Posts
- **What**: Posts not in public timelines
- **Federation**: ✅ Federates but marked unlisted
- **Timeline**: Only followers see it
- **Example**: Limited audience content
### Followers-Only Posts
- **What**: Posts only to followers, no federated boost
- **Federation**: ⚠️ May not federate fully
- **Timeline**: Only your followers
- **Example**: Very sensitive content
## Following Etiquette
### Best Practices
1. **Check before following**:
- Read their bio and recent posts
- Make sure they're who you think they are
- Check if their content aligns with your interests
2. **Start with interactions**:
- Like a few posts first
- Reply thoughtfully
- Share interesting content
- Then follow if you want to see more
3. **Respect instance culture**:
- Each instance has its own norms
- Read their community guidelines
- Be mindful of local rules
4. **Don't spam**:
- Don't mass-follow users
- Don't send unwanted DMs
- Don't repeatedly like old posts
5. **Use appropriate post visibility**:
- Public for general content
- Unlisted for updates to followers
- Private for sensitive topics
### Red Flags to Watch
1. **Suspicious accounts**:
- Newly created with generic content
- Only posting promotional links
- Unusual following patterns
2. **Instances with poor moderation**:
- Lots of spam in public timelines
- Harassment goes unaddressed
- You may want to block the instance
3. **Content warnings not respected**:
- Users posting unmarked sensitive content
- You can report/block these users
## Troubleshooting
### "Follow button doesn't work"
**Possible causes**:
1. User doesn't exist
2. Instance is down
3. Network connectivity issue
**What to do**:
1. Verify the username/domain is correct
2. Try searching for them again
3. Check your internet connection
4. Try again in a few minutes
### "User doesn't appear in Following list"
**Possible causes**:
1. Follow was rejected (locked account)
2. Follow is still pending
3. Error in federation
**What to do**:
1. Check if their account is locked
2. Wait a few minutes for acceptance
3. Check your ActivityPub logs
4. Try following again
### "Can't find a user via search"
**Possible causes**:
1. Username/domain is wrong
2. User's instance is blocking your instance
3. User's profile is not discoverable
**What to do**:
1. Double-check the spelling
2. Try their full URL: `https://instance.com/@username`
3. Check if they're from a blocked instance
4. Contact them directly for their handle
## API Reference
### Follow a Remote User
**Endpoint**: `POST /api/activitypub/follow`
**Request**:
```json
{
"targetActorUri": "https://mastodon.social/users/alice"
}
```
**Success Response**:
```json
{
"success": true,
"message": "Follow request sent. Waiting for acceptance.",
"targetActorUri": "https://mastodon.social/users/alice"
}
```
### Get Your Following
**Endpoint**: `GET /api/activitypub/following?limit=50`
**Response**:
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "I love tech!",
"avatarUrl": "https://...",
"followedAt": "2024-01-15T10:30:00Z",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
### Get Your Followers
**Endpoint**: `GET /api/activitypub/followers?limit=50`
**Response**:
```json
{
"users": [
{
"actorUri": "https://pleroma.site/users/bob",
"username": "bob",
"displayName": "Bob Jones",
"bio": "Federated user following me",
"avatarUrl": "https://...",
"followedAt": "2024-01-10T14:20:00Z",
"isLocal": false,
"instanceDomain": "pleroma.site"
}
]
}
```
### Search Users
**Endpoint**: `GET /api/activitypub/search?query=@alice@domain.com&limit=20`
**Response**:
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "Tech enthusiast",
"avatarUrl": "https://...",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
## Real Examples
### Example 1: Following a Mastodon User
**What you do**:
1. Search for `@alice@mastodon.social`
2. Click on Alice's profile
3. Click "Follow" button
4. Wait 1-2 seconds
5. ✅ Alice appears in your "Following" list
6. ✅ Alice's public posts appear in your timeline
**What happens technically**:
- Solar Network sends Follow to Alice's Mastodon instance
- Alice's Mastodon auto-accepts (unless locked)
- Mastodon sends Accept back to Solar Network
- Relationship stored in both databases
- Alice's future posts federate to Solar Network
### Example 2: Following a Locked Account
**What you do**:
1. Search for `@private@pleroma.site`
2. Click "Follow" button
3. ✅ See "Following..." (pending)
4. Wait for user to approve
**What happens technically**:
- Solar Network sends Follow to private@pleroma.site
- Private user receives notification
- Private user manually approves the request
- Private user's instance sends Accept
- ✅ Now following!
### Example 3: Following a Bot Account
**What you do**:
1. Search for `@news@botsin.space`
2. Click "Follow" button
3. ✅ Immediately following (bots auto-accept)
**What happens technically**:
- Follow is auto-accepted
- News posts appear in your timeline
- Regular updates from the bot
## Key Differences from Traditional Social Media
| Aspect | Traditional Social | ActivityPub |
|---------|------------------|-------------|
| Central server | ❌ No | ✅ Yes (per instance) |
| Multiple platforms | ❌ No | ✅ Yes (Mastodon, Pleroma, etc.) |
| Data ownership | ❌ On their servers | ✅ On your server |
| Blocking | ❌ One platform | ✅ Per instance |
| Migration | ❌ Difficult | ✅ Use your own domain |
| Federation | ❌ No | ✅ Built-in |
## Getting Help
If you have issues following users:
1. **Check the main guide**: See `HOW_TO_FOLLOW_FEDIVERSE_USERS.md`
2. **Check your logs**: Look for ActivityPub errors
3. **Test the API**: Use curl to test follow endpoints directly
4. **Verify the user**: Make sure the user exists on their instance
## Summary
Following fediverse users in Solar Network:
1. **Simple**: Just search and click "Follow"
2. **Works both ways**: You can follow them, they can follow you
3. **Works across instances**: Mastodon, Pleroma, Lemmy, etc.
4. **Federated content**: Their posts appear in your timeline
5. **Full interactions**: Like, reply, boost their posts
It works just like following on any other social platform, but with the added benefit of being able to follow users on completely different services! 🌍

View File

@@ -0,0 +1,406 @@
# How to Follow (Subscribe to) Fediverse Users in Solar Network
## Overview
In ActivityPub terminology, "subscribing" to a user is called **"following"**. This guide explains how users in Solar Network can follow users from other federated services (Mastodon, Pleroma, etc.).
## User Guide: How to Follow Fediverse Users
### Method 1: Via Search (Recommended)
1. **Search for the user**:
- Type their full address in the search bar: `@username@domain.com`
- Example: `@alice@mastodon.social`
- Example: `@bob@pleroma.site`
2. **View their profile**:
- Click on the search result
- You'll see their profile, bio, and recent posts
3. **Click "Follow" button**:
- Solar Network sends a Follow activity to their instance
- The remote instance will send back an Accept
- The user now appears in your "Following" list
### Method 2: Via Profile URL
1. **Visit their profile directly**:
- If you know their profile URL, visit it directly
- Example: `https://mastodon.social/@alice`
2. **Look for "Follow" button**:
- Click it to follow
3. **Confirm the follow**:
- Solar Network will send the follow request
- Wait for acceptance (usually immediate)
## What Happens Behind the Scenes
### The Follow Flow
```
User clicks "Follow"
Solar Network creates Follow Activity
Solar Network signs with publisher's private key
Solar Network sends to remote user's inbox
Remote instance verifies signature
Remote instance processes the Follow
Remote instance sends Accept Activity back
Solar Network receives and processes Accept
Relationship is established!
```
### Timeline Integration
Once you're following a user:
- ✅ Their public posts appear in your "Home" timeline
- ✅ Their posts are federated to your followers
- ✅ Their likes, replies, and boosts are visible
- ✅ You can interact with their content
## Following Different Types of Accounts
### Individual Users
- **What**: Regular users like you
- **Example**: `@alice@mastodon.social`
- **Works**: ✅ Full support
### Organizational/Bot Accounts
- **What**: Groups, bots, or organizations
- **Example**: `@official@newsbot.site`
- **Works**: ✅ Full support
### Locked Accounts
- **What**: Users who manually approve followers
- **Example**: `@private@pleroma.site`
- **Works**: ✅ Follow request sent, waits for approval
## Managing Your Follows
### View Who You're Following
**API Endpoint**: `GET /api/activitypub/following`
**Response Example**:
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "I love tech and coffee! ☕",
"avatarUrl": "https://cdn.mastodon.social/avatars/...",
"followedAt": "2024-01-15T10:30:00Z",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
### Unfollowing Someone
**API Endpoint**: `POST /api/activitypub/unfollow`
**Request Body**:
```json
{
"targetActorUri": "https://mastodon.social/users/alice"
}
```
**Response**:
```json
{
"success": true,
"message": "Unfollowed successfully"
}
```
## Searching Fediverse Users
**API Endpoint**: `GET /api/activitypub/search?query=@username@domain.com`
**Response Example**:
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "Software developer | Mastodon user",
"avatarUrl": "https://cdn.mastodon.social/avatars/...",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
## Follow States
| State | Meaning | What User Sees |
|--------|---------|----------------|
| Pending | Follow request sent, waiting for response | "Following..." (loading) |
| Accepted | Remote user accepted | "Following" ✓ |
| Rejected | Remote user declined | "Follow" button available again |
| Failed | Error occurred | "Error following" message |
## Privacy & Visibility
### Public Posts
- ✅ Federate to your followers automatically
- ✅ Appear in remote instances' timelines
- ✅ Can be boosted/liked by remote users
### Private Posts
- ❌ Do not federate
- ❌ Only visible to your local followers
- ❌ Not sent to remote instances
### Unlisted Posts
- ⚠️ Federate but not in public timelines
- ⚠️ Only visible to followers
## Best Practices for Users
### When Following Someone
1. **Check their profile first**:
- Make sure they're who you think they are
- Read their bio to understand their content
2. **Start with a few interactions**:
- Like a few posts
- Reply to something interesting
- Don't overwhelm their timeline
3. **Respect their instance's rules**:
- Each instance has its own guidelines
- Read community rules before interacting
4. **Report spam/harassment**:
- Use instance blocking features
- Report to instance admins
### Following Across Instances
1. **Use their full address**:
- `@username@instance.com`
- This helps identify which instance they're on
2. **Be aware of instance culture**:
- Each instance has its own norms
- Some are more technical, others more casual
3. **Check if they're from your instance**:
- Local users show `isLocal: true`
- Usually faster interaction
## Troubleshooting
### "Follow button doesn't work"
**Possible Causes**:
1. User doesn't exist
2. Instance is down
3. Network issue
**Solutions**:
1. Verify the user's address is correct
2. Check if the instance is accessible
3. Check your internet connection
4. Try again in a few minutes
### "User doesn't appear in Following list"
**Possible Causes**:
1. Follow was rejected
2. Still waiting for acceptance (locked accounts)
3. Error in federation
**Solutions**:
1. Check the follow status via API
2. Try following again
3. Check if their account is locked
4. Contact support if issue persists
### "Can't find a user"
**Possible Causes**:
1. Wrong username or domain
2. User doesn't exist
3. Instance blocking your instance
**Solutions**:
1. Double-check the address
2. Try searching from a different instance
3. Contact the user directly for their handle
## API Reference
### Follow a Remote User
**Endpoint**: `POST /api/activitypub/follow`
**Request**:
```json
{
"targetActorUri": "https://mastodon.social/users/alice"
}
```
**Response**: `200 OK`
```json
{
"success": true,
"message": "Follow request sent. Waiting for acceptance.",
"targetActorUri": "https://mastodon.social/users/alice"
}
```
### Get Following List
**Endpoint**: `GET /api/activitypub/following?limit=50`
**Response**: `200 OK`
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "...",
"avatarUrl": "...",
"followedAt": "2024-01-15T10:30:00Z",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
### Get Followers List
**Endpoint**: `GET /api/activitypub/followers?limit=50`
**Response**: `200 OK`
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "...",
"avatarUrl": "...",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
### Search Users
**Endpoint**: `GET /api/activitypub/search?query=alice&limit=20`
**Response**: `200 OK`
```json
{
"users": [
{
"actorUri": "https://mastodon.social/users/alice",
"username": "alice",
"displayName": "Alice Smith",
"bio": "...",
"avatarUrl": "...",
"isLocal": false,
"instanceDomain": "mastodon.social"
}
]
}
```
## What's Different About ActivityPub Following?
Unlike traditional social media:
| Feature | Traditional Social | ActivityPub |
|---------|------------------|-------------|
| Central server | ✅ Yes | ❌ No - federated |
| All users on same platform | ✅ Yes | ❌ No - multiple platforms |
| Blocked instances | ❌ No | ✅ Yes - instance blocking |
| Following across platforms | ❌ No | ✅ Yes - works with Mastodon, Pleroma, etc. |
| Your data stays on your server | ❌ Maybe | ✅ Yes - you control your data |
## User Experience Considerations
### Making It Easy
1. **Auto-discovery**:
- When users search for `@username`, suggest `@username@domain.com`
- Offer to search the fediverse
2. **Clear UI feedback**:
- Show "Follow request sent..."
- Show "They accepted!" notification
- Show "Follow request rejected" message
3. **Helpful tooltips**:
- Explain what ActivityPub is
- Show which instance a user is from
- Explain locked accounts
4. **Profile badges**:
- Show instance icon/logo
- Show if user is from same instance
- Show if user is verified
## Examples
### Following a Mastodon User
**User searches**: `@alice@mastodon.social`
**What happens**:
1. Solar Network fetches Alice's actor profile
2. Solar Network stores Alice in `fediverse_actors`
3. Solar Network sends Follow to Alice's inbox
4. Alice's instance accepts
5. Solar Network stores relationship in `fediverse_relationships`
6. Alice's posts now appear in user's timeline
### Following a Local User
**User searches**: `@bob`
**What happens**:
1. Solar Network finds Bob's publisher
2. Relationship created locally (no federation needed)
3. Bob's posts appear in user's timeline immediately
4. Same as traditional social media following
## Summary
Following fediverse users in Solar Network:
1. **Search by `@username@domain.com`** - Works for any ActivityPub instance
2. **Click "Follow"** - Sends federated follow request
3. **Wait for acceptance** - Remote user can approve or auto-accept
4. **See their posts in your timeline** - Content federates to you
5. **Interact normally** - Like, reply, boost, etc.
All of this is handled automatically by the ActivityPub implementation!

View File

@@ -0,0 +1,298 @@
# ActivityPub UI Implementation
## Overview
Complete UI implementation for ActivityPub features in Solian client, including search, following, and followers screens.
## Created Files
### 1. Widgets (`lib/widgets/activitypub/`)
#### `activitypub.dart`
- **Purpose**: Export file for ActivityPub widgets
- **Exports**: `ActivityPubUserListItem`
#### `user_list_item.dart`
- **Purpose**: Reusable list item widget for displaying ActivityPub users
- **Features**:
- Avatar with remote instance indicator (public icon)
- Display name with instance badge (e.g., "mastodon.social")
- Bio with truncation (max 2 lines)
- Followed at timestamp (relative time)
- Follow/Unfollow buttons with loading states
- Tap callback for navigation to profile
### 2. Screens (`lib/screens/activitypub/`)
#### `activitypub.dart`
- **Purpose**: Export file for ActivityPub screens
- **Exports**: `ActivityPubSearchScreen`, `ActivityPubListScreen`
#### `search.dart`
- **Purpose**: Search and follow ActivityPub users from other instances
- **Features**:
- Search bar with 500ms debounce
- Real-time search results
- Instant follow/unfollow actions
- Local tracking of followed users
- Empty states for no search and no results
- Refresh support via pull-to-refresh
- User feedback via snack bars
- **User Flow**:
1. User enters search query (e.g., `@alice@mastodon.social`)
2. Results appear after debounce
3. User taps "Follow" → Follow request sent
4. Success message shown
5. Button updates to "Unfollow"
#### `list.dart`
- **Purpose**: Display following/followers lists
- **Features**:
- Reusable for both Following and Followers
- Local state management
- Per-user loading states during actions
- Empty states with helpful hints
- Refresh support
- Auto-update lists when actions occur
- **Types**:
- `ActivityPubListType.following`: Shows users you follow
- `ActivityPubListType.followers`: Shows users who follow you
- **User Flow**:
1. User opens Following/Followers screen
2. List loads from API
3. User can unfollow (Following tab) or follow (Followers tab)
4. List updates automatically
5. Success/error messages shown
## Design Patterns
### Follows Project Conventions
1. **Material 3 Design**: All widgets use Material 3 components
2. **Styled Widget Package**: Used for `.padding()`, `.textColor()`, etc.
3. **Riverpod State Management**: Hooks for local state, providers for global state
4. **Error Handling**: `showErrorAlert()` from `alert.dart` for user feedback
5. **Success Feedback**: `showSnackBar()` for quick notifications
6. **Localization**: All strings use `.tr()` with placeholder args
### Color Scheme & Theming
- **Remote Badge**: Uses `Theme.colorScheme.primary` for indicator
- **Instance Tag**: Uses `Theme.colorScheme.secondaryContainer`
- **Text Colors**: Adaptive based on theme (dark/light)
- **States**: Loading indicators with standard `CircularProgressIndicator`
### Spacing & Layout
- **List Item Padding**: `EdgeInsets.only(left: 16, right: 12)`
- **Avatar Size**: 24px radius (48px diameter)
- **Badge Size**: Small (10px font) with 6px horizontal padding
- **Button Size**: Minimum 88px width, 36px height
## Translations Added
### New Keys in `assets/i18n/en-US.json`
```json
{
"searchFediverse": "Search Fediverse",
"searchFediverseHint": "Search by address, e.g. {}",
"searchFediverseEmpty": "Search for users on other ActivityPub instances",
"searchFediverseNoResults": "No users found for this search",
"following": "Following",
"followers": "Followers",
"follow": "Follow",
"unfollow": "Unfollow",
"followedUser": "Followed @{}",
"unfollowedUser": "Unfollowed @{}",
"followingEmpty": "You're not following anyone yet",
"followersEmpty": "No followers yet",
"followingEmptyHint": "Start by searching for users or explore other instances"
}
```
## Usage Examples
### Using Search Screen
```dart
import 'package:go_router/go_router.dart';
import 'package:island/screens/activitypub/activitypub.dart';
// In navigation or route
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ActivityPubSearchScreen(),
),
);
// Or using go_router
context.push('/activitypub/search');
```
### Using List Screen
```dart
// Following
ActivityPubListScreen(
type: ActivityPubListType.following,
);
// Followers
ActivityPubListScreen(
type: ActivityPubListType.followers,
);
```
### Using User List Item Widget
```dart
ActivityPubUserListItem(
user: user,
isFollowing: isFollowing,
isLoading: isLoading,
onFollow: () => handleFollow(user),
onUnfollow: () => handleUnfollow(user),
onTap: () => navigateToProfile(user),
);
```
## Integration Points
### Navigation Integration
To add ActivityPub screens to navigation:
1. **Option A**: Add to existing tab/navigation structure
2. **Option B**: Add as standalone routes in `go_router`
3. **Option C**: Add to profile menu overflow menu
### Service Integration
All screens use `activityPubServiceProvider`:
```dart
import 'package:island/services/activitypub_service.dart';
final service = ref.read(activityPubServiceProvider);
```
### Error Handling
All errors are caught and displayed using:
```dart
try {
// API call
} catch (err) {
showErrorAlert(err);
}
```
## Testing Checklist
- [ ] Search for existing Mastodon user
- [ ] Search for Pleroma user
- [ ] Follow a user
- [ ] Unfollow a user
- [ ] View following list
- [ ] View followers list
- [ ] Test empty states
- [ ] Test loading states
- [ ] Test error handling
- [ ] Test dark mode
- [ ] Test RTL languages (if supported)
## Technical Details
### Dependencies
**Already in project**:
-`cached_network_image` - For avatar images
-`easy_localization` - For translations
-`hooks_riverpod` - For state management
-`flutter_hooks` - For hooks (useState, useEffect, etc.)
-`material_symbols_icons` - For icons
-`relative_time` - For timestamp formatting
-`island/services/activitypub_service.dart` - API service (created earlier)
-`island/widgets/alert.dart` - Error/success dialogs
-`island/models/activitypub.dart` - Data models (created earlier)
### Performance Considerations
1. **Debounced Search**: 500ms delay prevents excessive API calls
2. **Local State Tracking**: `followingUris` Set prevents duplicate API calls
3. **Conditional Rebuilds**: Widget only rebuilds when necessary
4. **Image Caching**: Uses `CachedNetworkImageProvider` for avatars
### Accessibility
1. **Semantic Labels**: All ListTile widgets have proper content
2. **Touch Targets**: Minimum 44px touch targets for buttons
3. **Color Contrast**: Follows Material 3 color guidelines
4. **Loading Indicators**: Visual feedback during async operations
## Future Enhancements
### Potential Additions
1. **Profile Integration**: Show ActivityPub profile details
2. **Post Timeline**: Show federated posts from followed users
3. **Instance Blocking**: Block entire ActivityPub instances
4. **Advanced Search**: Filter by instance, user type, etc.
5. **Batch Actions**: Follow/unfollow multiple users at once
6. **Suggested Users**: Show recommended users to follow
7. **Recent Activity**: Show recent interactions
8. **Notifications**: Follow/unfollow notifications
### Localization
Need to add same keys to other language files:
- `es-ES.json`
- `ja-JP.json`
- `ko-KR.json`
- etc.
## Browser Testing
Test with real ActivityPub instances:
- mastodon.social
- pixelfed.social
- lemmy.world
- pleroma.site
- fosstodon.org
## Troubleshooting
### Common Issues
1. **Search returns no results**
- Check if user exists on remote instance
- Verify instance is accessible
- Try full URL instead of handle
2. **Follow button not working**
- Check if user is already following
- Verify server is online
- Check API logs
3. **Avatar not loading**
- Check remote avatar URL
- Verify network connection
- Check image cache
## Summary
**Fully functional ActivityPub UI** with:
- Search screen for discovering fediverse users
- Following/Followers list screens
- Reusable user list item component
- Proper error handling and user feedback
- Material 3 design
- Responsive layout
- Local state management
- Debounced search
- Empty states and loading indicators
**Ready for integration into main app navigation!** 🎉

View File

@@ -34,7 +34,7 @@ class NotifyDelegate: UIResponder, UNUserNotificationCenterDelegate {
}
let serverUrl = UserDefaults.standard.getServerUrl()
let url = "\(serverUrl)/sphere/chat/\(metadata["room_id"] ?? "")/messages"
let url = "\(serverUrl)/messager/chat/\(metadata["room_id"] ?? "")/messages"
let parameters: [String: Any?] = [
"content": textResponse.userText,

View File

@@ -261,7 +261,7 @@ class NetworkService {
guard let baseURL = URL(string: serverUrl) else {
throw URLError(.badURL)
}
let url = baseURL.appendingPathComponent("/sphere/chat")
let url = baseURL.appendingPathComponent("/messager/chat")
var request = URLRequest(url: url)
request.httpMethod = "GET"
@@ -283,7 +283,7 @@ class NetworkService {
guard let baseURL = URL(string: serverUrl) else {
throw URLError(.badURL)
}
let url = baseURL.appendingPathComponent("/sphere/chat/\(identifier)")
let url = baseURL.appendingPathComponent("/messager/chat/\(identifier)")
var request = URLRequest(url: url)
request.httpMethod = "GET"
@@ -308,7 +308,7 @@ class NetworkService {
guard let baseURL = URL(string: serverUrl) else {
throw URLError(.badURL)
}
let url = baseURL.appendingPathComponent("/sphere/chat/invites")
let url = baseURL.appendingPathComponent("/messager/chat/invites")
var request = URLRequest(url: url)
request.httpMethod = "GET"
@@ -330,7 +330,7 @@ class NetworkService {
guard let baseURL = URL(string: serverUrl) else {
throw URLError(.badURL)
}
let url = baseURL.appendingPathComponent("/sphere/chat/invites/\(chatRoomId)/accept")
let url = baseURL.appendingPathComponent("/messager/chat/invites/\(chatRoomId)/accept")
var request = URLRequest(url: url)
request.httpMethod = "POST"
@@ -351,7 +351,7 @@ class NetworkService {
guard let baseURL = URL(string: serverUrl) else {
throw URLError(.badURL)
}
let url = baseURL.appendingPathComponent("/sphere/chat/invites/\(chatRoomId)/decline")
let url = baseURL.appendingPathComponent("/messager/chat/invites/\(chatRoomId)/decline")
var request = URLRequest(url: url)
request.httpMethod = "POST"
@@ -375,9 +375,9 @@ class NetworkService {
throw URLError(.badURL)
}
// Try a different pattern: /sphere/chat/messages with roomId as query param
// Try a different pattern: /messager/chat/messages with roomId as query param
var components = URLComponents(
url: baseURL.appendingPathComponent("/sphere/chat/\(chatRoomId)/messages"),
url: baseURL.appendingPathComponent("/messager/chat/\(chatRoomId)/messages"),
resolvingAgainstBaseURL: false
)!
var queryItems = [

View File

@@ -455,7 +455,7 @@ struct ChatRoomView: View {
]
// Create the URL
guard let url = URL(string: "\(serverUrl)/sphere/chat/\(room.id)/messages") else {
guard let url = URL(string: "\(serverUrl)/messager/chat/\(room.id)/messages") else {
throw URLError(.badURL)
}

View File

@@ -10,7 +10,8 @@ sealed class SnNotableDay with _$SnNotableDay {
required DateTime date,
required String localName,
required String globalName,
required String countryCode,
required String? countryCode,
required String? localizableKey,
required List<int> holidays,
}) = _SnNotableDay;

View File

@@ -15,7 +15,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$SnNotableDay {
DateTime get date; String get localName; String get globalName; String get countryCode; List<int> get holidays;
DateTime get date; String get localName; String get globalName; String? get countryCode; String? get localizableKey; List<int> get holidays;
/// Create a copy of SnNotableDay
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -28,16 +28,16 @@ $SnNotableDayCopyWith<SnNotableDay> get copyWith => _$SnNotableDayCopyWithImpl<S
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnNotableDay&&(identical(other.date, date) || other.date == date)&&(identical(other.localName, localName) || other.localName == localName)&&(identical(other.globalName, globalName) || other.globalName == globalName)&&(identical(other.countryCode, countryCode) || other.countryCode == countryCode)&&const DeepCollectionEquality().equals(other.holidays, holidays));
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnNotableDay&&(identical(other.date, date) || other.date == date)&&(identical(other.localName, localName) || other.localName == localName)&&(identical(other.globalName, globalName) || other.globalName == globalName)&&(identical(other.countryCode, countryCode) || other.countryCode == countryCode)&&(identical(other.localizableKey, localizableKey) || other.localizableKey == localizableKey)&&const DeepCollectionEquality().equals(other.holidays, holidays));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,date,localName,globalName,countryCode,const DeepCollectionEquality().hash(holidays));
int get hashCode => Object.hash(runtimeType,date,localName,globalName,countryCode,localizableKey,const DeepCollectionEquality().hash(holidays));
@override
String toString() {
return 'SnNotableDay(date: $date, localName: $localName, globalName: $globalName, countryCode: $countryCode, holidays: $holidays)';
return 'SnNotableDay(date: $date, localName: $localName, globalName: $globalName, countryCode: $countryCode, localizableKey: $localizableKey, holidays: $holidays)';
}
@@ -48,7 +48,7 @@ abstract mixin class $SnNotableDayCopyWith<$Res> {
factory $SnNotableDayCopyWith(SnNotableDay value, $Res Function(SnNotableDay) _then) = _$SnNotableDayCopyWithImpl;
@useResult
$Res call({
DateTime date, String localName, String globalName, String countryCode, List<int> holidays
DateTime date, String localName, String globalName, String? countryCode, String? localizableKey, List<int> holidays
});
@@ -65,13 +65,14 @@ class _$SnNotableDayCopyWithImpl<$Res>
/// Create a copy of SnNotableDay
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? date = null,Object? localName = null,Object? globalName = null,Object? countryCode = null,Object? holidays = null,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? date = null,Object? localName = null,Object? globalName = null,Object? countryCode = freezed,Object? localizableKey = freezed,Object? holidays = null,}) {
return _then(_self.copyWith(
date: null == date ? _self.date : date // ignore: cast_nullable_to_non_nullable
as DateTime,localName: null == localName ? _self.localName : localName // ignore: cast_nullable_to_non_nullable
as String,globalName: null == globalName ? _self.globalName : globalName // ignore: cast_nullable_to_non_nullable
as String,countryCode: null == countryCode ? _self.countryCode : countryCode // ignore: cast_nullable_to_non_nullable
as String,holidays: null == holidays ? _self.holidays : holidays // ignore: cast_nullable_to_non_nullable
as String,countryCode: freezed == countryCode ? _self.countryCode : countryCode // ignore: cast_nullable_to_non_nullable
as String?,localizableKey: freezed == localizableKey ? _self.localizableKey : localizableKey // ignore: cast_nullable_to_non_nullable
as String?,holidays: null == holidays ? _self.holidays : holidays // ignore: cast_nullable_to_non_nullable
as List<int>,
));
}
@@ -154,10 +155,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( DateTime date, String localName, String globalName, String countryCode, List<int> holidays)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( DateTime date, String localName, String globalName, String? countryCode, String? localizableKey, List<int> holidays)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnNotableDay() when $default != null:
return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_that.holidays);case _:
return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_that.localizableKey,_that.holidays);case _:
return orElse();
}
@@ -175,10 +176,10 @@ return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_t
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( DateTime date, String localName, String globalName, String countryCode, List<int> holidays) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( DateTime date, String localName, String globalName, String? countryCode, String? localizableKey, List<int> holidays) $default,) {final _that = this;
switch (_that) {
case _SnNotableDay():
return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_that.holidays);}
return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_that.localizableKey,_that.holidays);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -192,10 +193,10 @@ return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_t
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( DateTime date, String localName, String globalName, String countryCode, List<int> holidays)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( DateTime date, String localName, String globalName, String? countryCode, String? localizableKey, List<int> holidays)? $default,) {final _that = this;
switch (_that) {
case _SnNotableDay() when $default != null:
return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_that.holidays);case _:
return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_that.localizableKey,_that.holidays);case _:
return null;
}
@@ -207,13 +208,14 @@ return $default(_that.date,_that.localName,_that.globalName,_that.countryCode,_t
@JsonSerializable()
class _SnNotableDay implements SnNotableDay {
const _SnNotableDay({required this.date, required this.localName, required this.globalName, required this.countryCode, required final List<int> holidays}): _holidays = holidays;
const _SnNotableDay({required this.date, required this.localName, required this.globalName, required this.countryCode, required this.localizableKey, required final List<int> holidays}): _holidays = holidays;
factory _SnNotableDay.fromJson(Map<String, dynamic> json) => _$SnNotableDayFromJson(json);
@override final DateTime date;
@override final String localName;
@override final String globalName;
@override final String countryCode;
@override final String? countryCode;
@override final String? localizableKey;
final List<int> _holidays;
@override List<int> get holidays {
if (_holidays is EqualUnmodifiableListView) return _holidays;
@@ -235,16 +237,16 @@ Map<String, dynamic> toJson() {
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnNotableDay&&(identical(other.date, date) || other.date == date)&&(identical(other.localName, localName) || other.localName == localName)&&(identical(other.globalName, globalName) || other.globalName == globalName)&&(identical(other.countryCode, countryCode) || other.countryCode == countryCode)&&const DeepCollectionEquality().equals(other._holidays, _holidays));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnNotableDay&&(identical(other.date, date) || other.date == date)&&(identical(other.localName, localName) || other.localName == localName)&&(identical(other.globalName, globalName) || other.globalName == globalName)&&(identical(other.countryCode, countryCode) || other.countryCode == countryCode)&&(identical(other.localizableKey, localizableKey) || other.localizableKey == localizableKey)&&const DeepCollectionEquality().equals(other._holidays, _holidays));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,date,localName,globalName,countryCode,const DeepCollectionEquality().hash(_holidays));
int get hashCode => Object.hash(runtimeType,date,localName,globalName,countryCode,localizableKey,const DeepCollectionEquality().hash(_holidays));
@override
String toString() {
return 'SnNotableDay(date: $date, localName: $localName, globalName: $globalName, countryCode: $countryCode, holidays: $holidays)';
return 'SnNotableDay(date: $date, localName: $localName, globalName: $globalName, countryCode: $countryCode, localizableKey: $localizableKey, holidays: $holidays)';
}
@@ -255,7 +257,7 @@ abstract mixin class _$SnNotableDayCopyWith<$Res> implements $SnNotableDayCopyWi
factory _$SnNotableDayCopyWith(_SnNotableDay value, $Res Function(_SnNotableDay) _then) = __$SnNotableDayCopyWithImpl;
@override @useResult
$Res call({
DateTime date, String localName, String globalName, String countryCode, List<int> holidays
DateTime date, String localName, String globalName, String? countryCode, String? localizableKey, List<int> holidays
});
@@ -272,13 +274,14 @@ class __$SnNotableDayCopyWithImpl<$Res>
/// Create a copy of SnNotableDay
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? date = null,Object? localName = null,Object? globalName = null,Object? countryCode = null,Object? holidays = null,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? date = null,Object? localName = null,Object? globalName = null,Object? countryCode = freezed,Object? localizableKey = freezed,Object? holidays = null,}) {
return _then(_SnNotableDay(
date: null == date ? _self.date : date // ignore: cast_nullable_to_non_nullable
as DateTime,localName: null == localName ? _self.localName : localName // ignore: cast_nullable_to_non_nullable
as String,globalName: null == globalName ? _self.globalName : globalName // ignore: cast_nullable_to_non_nullable
as String,countryCode: null == countryCode ? _self.countryCode : countryCode // ignore: cast_nullable_to_non_nullable
as String,holidays: null == holidays ? _self._holidays : holidays // ignore: cast_nullable_to_non_nullable
as String,countryCode: freezed == countryCode ? _self.countryCode : countryCode // ignore: cast_nullable_to_non_nullable
as String?,localizableKey: freezed == localizableKey ? _self.localizableKey : localizableKey // ignore: cast_nullable_to_non_nullable
as String?,holidays: null == holidays ? _self._holidays : holidays // ignore: cast_nullable_to_non_nullable
as List<int>,
));
}

View File

@@ -11,7 +11,8 @@ _SnNotableDay _$SnNotableDayFromJson(Map<String, dynamic> json) =>
date: DateTime.parse(json['date'] as String),
localName: json['local_name'] as String,
globalName: json['global_name'] as String,
countryCode: json['country_code'] as String,
countryCode: json['country_code'] as String?,
localizableKey: json['localizable_key'] as String?,
holidays: (json['holidays'] as List<dynamic>)
.map((e) => (e as num).toInt())
.toList(),
@@ -23,6 +24,7 @@ Map<String, dynamic> _$SnNotableDayToJson(_SnNotableDay instance) =>
'local_name': instance.localName,
'global_name': instance.globalName,
'country_code': instance.countryCode,
'localizable_key': instance.localizableKey,
'holidays': instance.holidays,
};

108
lib/models/activitypub.dart Normal file
View File

@@ -0,0 +1,108 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'activitypub.freezed.dart';
part 'activitypub.g.dart';
@freezed
sealed class SnActivityPubInstance with _$SnActivityPubInstance {
const factory SnActivityPubInstance({
required String id,
required String domain,
String? name,
String? description,
String? software,
String? version,
String? iconUrl,
String? thumbnailUrl,
String? contactEmail,
String? contactAccountUsername,
int? activeUsers,
@Default(false) bool isBlocked,
@Default(false) bool isSilenced,
String? blockReason,
Map<String, dynamic>? metadata,
DateTime? lastFetchedAt,
DateTime? lastActivityAt,
DateTime? metadataFetchedAt,
}) = _SnActivityPubInstance;
factory SnActivityPubInstance.fromJson(Map<String, dynamic> json) =>
_$SnActivityPubInstanceFromJson(json);
}
@freezed
sealed class SnActivityPubUser with _$SnActivityPubUser {
const factory SnActivityPubUser({
required String actorUri,
required String username,
required String displayName,
required String bio,
required String avatarUrl,
required DateTime followedAt,
required bool isLocal,
required String instanceDomain,
}) = _SnActivityPubUser;
factory SnActivityPubUser.fromJson(Map<String, dynamic> json) =>
_$SnActivityPubUserFromJson(json);
}
@freezed
sealed class SnActivityPubActor with _$SnActivityPubActor {
const factory SnActivityPubActor({
required String id,
required String uri,
@Default('') String type,
String? displayName,
String? username,
String? summary,
String? inboxUri,
String? outboxUri,
String? followersUri,
String? followingUri,
String? featuredUri,
String? avatarUrl,
String? headerUrl,
String? publicKeyId,
String? publicKey,
@Default(false) bool isBot,
@Default(false) bool isLocked,
@Default(true) bool discoverable,
@Default(false) bool manuallyApprovesFollowers,
Map<String, dynamic>? endpoints,
Map<String, dynamic>? publicKeyData,
Map<String, dynamic>? metadata,
DateTime? lastFetchedAt,
DateTime? lastActivityAt,
required SnActivityPubInstance instance,
required String instanceId,
bool? isFollowing,
}) = _SnActivityPubActor;
factory SnActivityPubActor.fromJson(Map<String, dynamic> json) =>
_$SnActivityPubActorFromJson(json);
}
@freezed
sealed class SnActivityPubFollowResponse with _$SnActivityPubFollowResponse {
const factory SnActivityPubFollowResponse({
required bool success,
required String message,
}) = _SnActivityPubFollowResponse;
factory SnActivityPubFollowResponse.fromJson(Map<String, dynamic> json) =>
_$SnActivityPubFollowResponseFromJson(json);
}
@freezed
sealed class SnActorStatusResponse with _$SnActorStatusResponse {
const factory SnActorStatusResponse({
required bool enabled,
@Default(0) int followerCount,
SnActivityPubActor? actor,
String? actorUri,
}) = _SnActorStatusResponse;
factory SnActorStatusResponse.fromJson(Map<String, dynamic> json) =>
_$SnActorStatusResponseFromJson(json);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,186 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'activitypub.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_SnActivityPubInstance _$SnActivityPubInstanceFromJson(
Map<String, dynamic> json,
) => _SnActivityPubInstance(
id: json['id'] as String,
domain: json['domain'] as String,
name: json['name'] as String?,
description: json['description'] as String?,
software: json['software'] as String?,
version: json['version'] as String?,
iconUrl: json['icon_url'] as String?,
thumbnailUrl: json['thumbnail_url'] as String?,
contactEmail: json['contact_email'] as String?,
contactAccountUsername: json['contact_account_username'] as String?,
activeUsers: (json['active_users'] as num?)?.toInt(),
isBlocked: json['is_blocked'] as bool? ?? false,
isSilenced: json['is_silenced'] as bool? ?? false,
blockReason: json['block_reason'] as String?,
metadata: json['metadata'] as Map<String, dynamic>?,
lastFetchedAt: json['last_fetched_at'] == null
? null
: DateTime.parse(json['last_fetched_at'] as String),
lastActivityAt: json['last_activity_at'] == null
? null
: DateTime.parse(json['last_activity_at'] as String),
metadataFetchedAt: json['metadata_fetched_at'] == null
? null
: DateTime.parse(json['metadata_fetched_at'] as String),
);
Map<String, dynamic> _$SnActivityPubInstanceToJson(
_SnActivityPubInstance instance,
) => <String, dynamic>{
'id': instance.id,
'domain': instance.domain,
'name': instance.name,
'description': instance.description,
'software': instance.software,
'version': instance.version,
'icon_url': instance.iconUrl,
'thumbnail_url': instance.thumbnailUrl,
'contact_email': instance.contactEmail,
'contact_account_username': instance.contactAccountUsername,
'active_users': instance.activeUsers,
'is_blocked': instance.isBlocked,
'is_silenced': instance.isSilenced,
'block_reason': instance.blockReason,
'metadata': instance.metadata,
'last_fetched_at': instance.lastFetchedAt?.toIso8601String(),
'last_activity_at': instance.lastActivityAt?.toIso8601String(),
'metadata_fetched_at': instance.metadataFetchedAt?.toIso8601String(),
};
_SnActivityPubUser _$SnActivityPubUserFromJson(Map<String, dynamic> json) =>
_SnActivityPubUser(
actorUri: json['actor_uri'] as String,
username: json['username'] as String,
displayName: json['display_name'] as String,
bio: json['bio'] as String,
avatarUrl: json['avatar_url'] as String,
followedAt: DateTime.parse(json['followed_at'] as String),
isLocal: json['is_local'] as bool,
instanceDomain: json['instance_domain'] as String,
);
Map<String, dynamic> _$SnActivityPubUserToJson(_SnActivityPubUser instance) =>
<String, dynamic>{
'actor_uri': instance.actorUri,
'username': instance.username,
'display_name': instance.displayName,
'bio': instance.bio,
'avatar_url': instance.avatarUrl,
'followed_at': instance.followedAt.toIso8601String(),
'is_local': instance.isLocal,
'instance_domain': instance.instanceDomain,
};
_SnActivityPubActor _$SnActivityPubActorFromJson(Map<String, dynamic> json) =>
_SnActivityPubActor(
id: json['id'] as String,
uri: json['uri'] as String,
type: json['type'] as String? ?? '',
displayName: json['display_name'] as String?,
username: json['username'] as String?,
summary: json['summary'] as String?,
inboxUri: json['inbox_uri'] as String?,
outboxUri: json['outbox_uri'] as String?,
followersUri: json['followers_uri'] as String?,
followingUri: json['following_uri'] as String?,
featuredUri: json['featured_uri'] as String?,
avatarUrl: json['avatar_url'] as String?,
headerUrl: json['header_url'] as String?,
publicKeyId: json['public_key_id'] as String?,
publicKey: json['public_key'] as String?,
isBot: json['is_bot'] as bool? ?? false,
isLocked: json['is_locked'] as bool? ?? false,
discoverable: json['discoverable'] as bool? ?? true,
manuallyApprovesFollowers:
json['manually_approves_followers'] as bool? ?? false,
endpoints: json['endpoints'] as Map<String, dynamic>?,
publicKeyData: json['public_key_data'] as Map<String, dynamic>?,
metadata: json['metadata'] as Map<String, dynamic>?,
lastFetchedAt: json['last_fetched_at'] == null
? null
: DateTime.parse(json['last_fetched_at'] as String),
lastActivityAt: json['last_activity_at'] == null
? null
: DateTime.parse(json['last_activity_at'] as String),
instance: SnActivityPubInstance.fromJson(
json['instance'] as Map<String, dynamic>,
),
instanceId: json['instance_id'] as String,
isFollowing: json['is_following'] as bool?,
);
Map<String, dynamic> _$SnActivityPubActorToJson(_SnActivityPubActor instance) =>
<String, dynamic>{
'id': instance.id,
'uri': instance.uri,
'type': instance.type,
'display_name': instance.displayName,
'username': instance.username,
'summary': instance.summary,
'inbox_uri': instance.inboxUri,
'outbox_uri': instance.outboxUri,
'followers_uri': instance.followersUri,
'following_uri': instance.followingUri,
'featured_uri': instance.featuredUri,
'avatar_url': instance.avatarUrl,
'header_url': instance.headerUrl,
'public_key_id': instance.publicKeyId,
'public_key': instance.publicKey,
'is_bot': instance.isBot,
'is_locked': instance.isLocked,
'discoverable': instance.discoverable,
'manually_approves_followers': instance.manuallyApprovesFollowers,
'endpoints': instance.endpoints,
'public_key_data': instance.publicKeyData,
'metadata': instance.metadata,
'last_fetched_at': instance.lastFetchedAt?.toIso8601String(),
'last_activity_at': instance.lastActivityAt?.toIso8601String(),
'instance': instance.instance.toJson(),
'instance_id': instance.instanceId,
'is_following': instance.isFollowing,
};
_SnActivityPubFollowResponse _$SnActivityPubFollowResponseFromJson(
Map<String, dynamic> json,
) => _SnActivityPubFollowResponse(
success: json['success'] as bool,
message: json['message'] as String,
);
Map<String, dynamic> _$SnActivityPubFollowResponseToJson(
_SnActivityPubFollowResponse instance,
) => <String, dynamic>{
'success': instance.success,
'message': instance.message,
};
_SnActorStatusResponse _$SnActorStatusResponseFromJson(
Map<String, dynamic> json,
) => _SnActorStatusResponse(
enabled: json['enabled'] as bool,
followerCount: (json['follower_count'] as num?)?.toInt() ?? 0,
actor: json['actor'] == null
? null
: SnActivityPubActor.fromJson(json['actor'] as Map<String, dynamic>),
actorUri: json['actor_uri'] as String?,
);
Map<String, dynamic> _$SnActorStatusResponseToJson(
_SnActorStatusResponse instance,
) => <String, dynamic>{
'enabled': instance.enabled,
'follower_count': instance.followerCount,
'actor': instance.actor?.toJson(),
'actor_uri': instance.actorUri,
};

View File

@@ -55,6 +55,7 @@ sealed class SnCloudFile with _$SnCloudFile {
required DateTime createdAt,
required DateTime updatedAt,
required DateTime? deletedAt,
String? url,
}) = _SnCloudFile;
factory SnCloudFile.fromJson(Map<String, dynamic> json) =>

View File

@@ -281,7 +281,7 @@ as String?,
/// @nodoc
mixin _$SnCloudFile {
String get id; String get name; String? get description; Map<String, dynamic>? get fileMeta; Map<String, dynamic>? get userMeta; SnFilePool? get pool; List<int> get sensitiveMarks; String? get mimeType; String? get hash; int get size; DateTime? get uploadedAt; String? get uploadedTo; DateTime get createdAt; DateTime get updatedAt; DateTime? get deletedAt;
String get id; String get name; String? get description; Map<String, dynamic>? get fileMeta; Map<String, dynamic>? get userMeta; SnFilePool? get pool; List<int> get sensitiveMarks; String? get mimeType; String? get hash; int get size; DateTime? get uploadedAt; String? get uploadedTo; DateTime get createdAt; DateTime get updatedAt; DateTime? get deletedAt; String? get url;
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -294,16 +294,16 @@ $SnCloudFileCopyWith<SnCloudFile> get copyWith => _$SnCloudFileCopyWithImpl<SnCl
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other.fileMeta, fileMeta)&&const DeepCollectionEquality().equals(other.userMeta, userMeta)&&(identical(other.pool, pool) || other.pool == pool)&&const DeepCollectionEquality().equals(other.sensitiveMarks, sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.uploadedTo, uploadedTo) || other.uploadedTo == uploadedTo)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other.fileMeta, fileMeta)&&const DeepCollectionEquality().equals(other.userMeta, userMeta)&&(identical(other.pool, pool) || other.pool == pool)&&const DeepCollectionEquality().equals(other.sensitiveMarks, sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.uploadedTo, uploadedTo) || other.uploadedTo == uploadedTo)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.url, url) || other.url == url));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(fileMeta),const DeepCollectionEquality().hash(userMeta),pool,const DeepCollectionEquality().hash(sensitiveMarks),mimeType,hash,size,uploadedAt,uploadedTo,createdAt,updatedAt,deletedAt);
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(fileMeta),const DeepCollectionEquality().hash(userMeta),pool,const DeepCollectionEquality().hash(sensitiveMarks),mimeType,hash,size,uploadedAt,uploadedTo,createdAt,updatedAt,deletedAt,url);
@override
String toString() {
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, pool: $pool, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, uploadedTo: $uploadedTo, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, pool: $pool, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, uploadedTo: $uploadedTo, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, url: $url)';
}
@@ -314,7 +314,7 @@ abstract mixin class $SnCloudFileCopyWith<$Res> {
factory $SnCloudFileCopyWith(SnCloudFile value, $Res Function(SnCloudFile) _then) = _$SnCloudFileCopyWithImpl;
@useResult
$Res call({
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url
});
@@ -331,7 +331,7 @@ class _$SnCloudFileCopyWithImpl<$Res>
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? pool = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? uploadedTo = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? pool = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? uploadedTo = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,Object? url = freezed,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
@@ -348,7 +348,8 @@ as DateTime?,uploadedTo: freezed == uploadedTo ? _self.uploadedTo : uploadedTo /
as String?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
as DateTime?,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String?,
));
}
/// Create a copy of SnCloudFile
@@ -442,10 +443,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnCloudFile() when $default != null:
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);case _:
return orElse();
}
@@ -463,10 +464,10 @@ return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userM
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url) $default,) {final _that = this;
switch (_that) {
case _SnCloudFile():
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt);}
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -480,10 +481,10 @@ return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userM
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url)? $default,) {final _that = this;
switch (_that) {
case _SnCloudFile() when $default != null:
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);case _:
return null;
}
@@ -495,7 +496,7 @@ return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userM
@JsonSerializable()
class _SnCloudFile implements SnCloudFile {
const _SnCloudFile({required this.id, required this.name, required this.description, required final Map<String, dynamic>? fileMeta, required final Map<String, dynamic>? userMeta, required this.pool, final List<int> sensitiveMarks = const [], required this.mimeType, required this.hash, required this.size, required this.uploadedAt, required this.uploadedTo, required this.createdAt, required this.updatedAt, required this.deletedAt}): _fileMeta = fileMeta,_userMeta = userMeta,_sensitiveMarks = sensitiveMarks;
const _SnCloudFile({required this.id, required this.name, required this.description, required final Map<String, dynamic>? fileMeta, required final Map<String, dynamic>? userMeta, required this.pool, final List<int> sensitiveMarks = const [], required this.mimeType, required this.hash, required this.size, required this.uploadedAt, required this.uploadedTo, required this.createdAt, required this.updatedAt, required this.deletedAt, this.url}): _fileMeta = fileMeta,_userMeta = userMeta,_sensitiveMarks = sensitiveMarks;
factory _SnCloudFile.fromJson(Map<String, dynamic> json) => _$SnCloudFileFromJson(json);
@override final String id;
@@ -535,6 +536,7 @@ class _SnCloudFile implements SnCloudFile {
@override final DateTime createdAt;
@override final DateTime updatedAt;
@override final DateTime? deletedAt;
@override final String? url;
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@@ -549,16 +551,16 @@ Map<String, dynamic> toJson() {
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other._fileMeta, _fileMeta)&&const DeepCollectionEquality().equals(other._userMeta, _userMeta)&&(identical(other.pool, pool) || other.pool == pool)&&const DeepCollectionEquality().equals(other._sensitiveMarks, _sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.uploadedTo, uploadedTo) || other.uploadedTo == uploadedTo)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other._fileMeta, _fileMeta)&&const DeepCollectionEquality().equals(other._userMeta, _userMeta)&&(identical(other.pool, pool) || other.pool == pool)&&const DeepCollectionEquality().equals(other._sensitiveMarks, _sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.uploadedTo, uploadedTo) || other.uploadedTo == uploadedTo)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.url, url) || other.url == url));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(_fileMeta),const DeepCollectionEquality().hash(_userMeta),pool,const DeepCollectionEquality().hash(_sensitiveMarks),mimeType,hash,size,uploadedAt,uploadedTo,createdAt,updatedAt,deletedAt);
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(_fileMeta),const DeepCollectionEquality().hash(_userMeta),pool,const DeepCollectionEquality().hash(_sensitiveMarks),mimeType,hash,size,uploadedAt,uploadedTo,createdAt,updatedAt,deletedAt,url);
@override
String toString() {
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, pool: $pool, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, uploadedTo: $uploadedTo, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, pool: $pool, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, uploadedTo: $uploadedTo, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, url: $url)';
}
@@ -569,7 +571,7 @@ abstract mixin class _$SnCloudFileCopyWith<$Res> implements $SnCloudFileCopyWith
factory _$SnCloudFileCopyWith(_SnCloudFile value, $Res Function(_SnCloudFile) _then) = __$SnCloudFileCopyWithImpl;
@override @useResult
$Res call({
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url
});
@@ -586,7 +588,7 @@ class __$SnCloudFileCopyWithImpl<$Res>
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? pool = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? uploadedTo = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? pool = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? uploadedTo = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,Object? url = freezed,}) {
return _then(_SnCloudFile(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
@@ -603,7 +605,8 @@ as DateTime?,uploadedTo: freezed == uploadedTo ? _self.uploadedTo : uploadedTo /
as String?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
as DateTime?,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String?,
));
}

View File

@@ -55,6 +55,7 @@ _SnCloudFile _$SnCloudFileFromJson(Map<String, dynamic> json) => _SnCloudFile(
deletedAt: json['deleted_at'] == null
? null
: DateTime.parse(json['deleted_at'] as String),
url: json['url'] as String?,
);
Map<String, dynamic> _$SnCloudFileToJson(_SnCloudFile instance) =>
@@ -74,6 +75,7 @@ Map<String, dynamic> _$SnCloudFileToJson(_SnCloudFile instance) =>
'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt.toIso8601String(),
'deleted_at': instance.deletedAt?.toIso8601String(),
'url': instance.url,
};
_SnCloudFileIndex _$SnCloudFileIndexFromJson(Map<String, dynamic> json) =>

16
lib/models/fortune.dart Normal file
View File

@@ -0,0 +1,16 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'fortune.g.dart';
part 'fortune.freezed.dart';
@freezed
sealed class SnFortuneSaying with _$SnFortuneSaying {
const factory SnFortuneSaying({
required String content,
required String source,
required String language,
}) = _SnFortuneSaying;
factory SnFortuneSaying.fromJson(Map<String, dynamic> json) =>
_$SnFortuneSayingFromJson(json);
}

View File

@@ -0,0 +1,277 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'fortune.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$SnFortuneSaying {
String get content; String get source; String get language;
/// Create a copy of SnFortuneSaying
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SnFortuneSayingCopyWith<SnFortuneSaying> get copyWith => _$SnFortuneSayingCopyWithImpl<SnFortuneSaying>(this as SnFortuneSaying, _$identity);
/// Serializes this SnFortuneSaying to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnFortuneSaying&&(identical(other.content, content) || other.content == content)&&(identical(other.source, source) || other.source == source)&&(identical(other.language, language) || other.language == language));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,content,source,language);
@override
String toString() {
return 'SnFortuneSaying(content: $content, source: $source, language: $language)';
}
}
/// @nodoc
abstract mixin class $SnFortuneSayingCopyWith<$Res> {
factory $SnFortuneSayingCopyWith(SnFortuneSaying value, $Res Function(SnFortuneSaying) _then) = _$SnFortuneSayingCopyWithImpl;
@useResult
$Res call({
String content, String source, String language
});
}
/// @nodoc
class _$SnFortuneSayingCopyWithImpl<$Res>
implements $SnFortuneSayingCopyWith<$Res> {
_$SnFortuneSayingCopyWithImpl(this._self, this._then);
final SnFortuneSaying _self;
final $Res Function(SnFortuneSaying) _then;
/// Create a copy of SnFortuneSaying
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? content = null,Object? source = null,Object? language = null,}) {
return _then(_self.copyWith(
content: null == content ? _self.content : content // ignore: cast_nullable_to_non_nullable
as String,source: null == source ? _self.source : source // ignore: cast_nullable_to_non_nullable
as String,language: null == language ? _self.language : language // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// Adds pattern-matching-related methods to [SnFortuneSaying].
extension SnFortuneSayingPatterns on SnFortuneSaying {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _SnFortuneSaying value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _SnFortuneSaying() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _SnFortuneSaying value) $default,){
final _that = this;
switch (_that) {
case _SnFortuneSaying():
return $default(_that);}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _SnFortuneSaying value)? $default,){
final _that = this;
switch (_that) {
case _SnFortuneSaying() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String content, String source, String language)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnFortuneSaying() when $default != null:
return $default(_that.content,_that.source,_that.language);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String content, String source, String language) $default,) {final _that = this;
switch (_that) {
case _SnFortuneSaying():
return $default(_that.content,_that.source,_that.language);}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String content, String source, String language)? $default,) {final _that = this;
switch (_that) {
case _SnFortuneSaying() when $default != null:
return $default(_that.content,_that.source,_that.language);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _SnFortuneSaying implements SnFortuneSaying {
const _SnFortuneSaying({required this.content, required this.source, required this.language});
factory _SnFortuneSaying.fromJson(Map<String, dynamic> json) => _$SnFortuneSayingFromJson(json);
@override final String content;
@override final String source;
@override final String language;
/// Create a copy of SnFortuneSaying
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SnFortuneSayingCopyWith<_SnFortuneSaying> get copyWith => __$SnFortuneSayingCopyWithImpl<_SnFortuneSaying>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$SnFortuneSayingToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnFortuneSaying&&(identical(other.content, content) || other.content == content)&&(identical(other.source, source) || other.source == source)&&(identical(other.language, language) || other.language == language));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,content,source,language);
@override
String toString() {
return 'SnFortuneSaying(content: $content, source: $source, language: $language)';
}
}
/// @nodoc
abstract mixin class _$SnFortuneSayingCopyWith<$Res> implements $SnFortuneSayingCopyWith<$Res> {
factory _$SnFortuneSayingCopyWith(_SnFortuneSaying value, $Res Function(_SnFortuneSaying) _then) = __$SnFortuneSayingCopyWithImpl;
@override @useResult
$Res call({
String content, String source, String language
});
}
/// @nodoc
class __$SnFortuneSayingCopyWithImpl<$Res>
implements _$SnFortuneSayingCopyWith<$Res> {
__$SnFortuneSayingCopyWithImpl(this._self, this._then);
final _SnFortuneSaying _self;
final $Res Function(_SnFortuneSaying) _then;
/// Create a copy of SnFortuneSaying
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? content = null,Object? source = null,Object? language = null,}) {
return _then(_SnFortuneSaying(
content: null == content ? _self.content : content // ignore: cast_nullable_to_non_nullable
as String,source: null == source ? _self.source : source // ignore: cast_nullable_to_non_nullable
as String,language: null == language ? _self.language : language // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
// dart format on

21
lib/models/fortune.g.dart Normal file
View File

@@ -0,0 +1,21 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'fortune.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_SnFortuneSaying _$SnFortuneSayingFromJson(Map<String, dynamic> json) =>
_SnFortuneSaying(
content: json['content'] as String,
source: json['source'] as String,
language: json['language'] as String,
);
Map<String, dynamic> _$SnFortuneSayingToJson(_SnFortuneSaying instance) =>
<String, dynamic>{
'content': instance.content,
'source': instance.source,
'language': instance.language,
};

View File

@@ -1,5 +1,6 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:island/models/account.dart';
import 'package:island/models/activitypub.dart';
import 'package:island/models/file.dart';
import 'package:island/models/post_category.dart';
import 'package:island/models/post_tag.dart';
@@ -39,8 +40,14 @@ sealed class SnPost with _$SnPost {
SnPost? forwardedPost,
String? realmId,
SnRealm? realm,
String? publisherId,
SnPublisher? publisher,
String? actorid,
SnActivityPubActor? actor,
String? fediverseUri,
int? fediverseType,
@Default(0) int contentType,
@Default([]) List<SnCloudFile> attachments,
required SnPublisher publisher,
@Default({}) Map<String, int> reactionsCount,
@Default({}) Map<String, bool> reactionsMade,
@Default([]) List<dynamic> reactions,
@@ -155,10 +162,12 @@ sealed class SnPostReaction with _$SnPostReaction {
required String symbol,
required int attitude,
required String postId,
required String accountId,
required DateTime createdAt,
required DateTime updatedAt,
@Default(null) SnAccount? account,
String? actorId,
SnActivityPubActor? actor,
String? accountId,
SnAccount? account,
DateTime? deletedAt,
}) = _SnPostReaction;

View File

@@ -15,7 +15,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$SnPost {
String get id; String? get title; String? get description; String? get language; DateTime? get editedAt; DateTime? get publishedAt; int get visibility; String? get content; String? get slug; int get type; Map<String, dynamic>? get meta; SnPostEmbedView? get embedView; int get viewsUnique; int get viewsTotal; int get upvotes; int get downvotes; int get repliesCount; int get awardedScore; int? get pinMode; String? get threadedPostId; SnPost? get threadedPost; String? get repliedPostId; SnPost? get repliedPost; String? get forwardedPostId; SnPost? get forwardedPost; String? get realmId; SnRealm? get realm; List<SnCloudFile> get attachments; SnPublisher get publisher; Map<String, int> get reactionsCount; Map<String, bool> get reactionsMade; List<dynamic> get reactions; List<SnPostTag> get tags; List<SnPostCategory> get categories; List<dynamic> get collections; List<SnPostFeaturedRecord> get featuredRecords; DateTime? get createdAt; DateTime? get updatedAt; DateTime? get deletedAt; bool get repliedGone; bool get forwardedGone; bool get isTruncated;
String get id; String? get title; String? get description; String? get language; DateTime? get editedAt; DateTime? get publishedAt; int get visibility; String? get content; String? get slug; int get type; Map<String, dynamic>? get meta; SnPostEmbedView? get embedView; int get viewsUnique; int get viewsTotal; int get upvotes; int get downvotes; int get repliesCount; int get awardedScore; int? get pinMode; String? get threadedPostId; SnPost? get threadedPost; String? get repliedPostId; SnPost? get repliedPost; String? get forwardedPostId; SnPost? get forwardedPost; String? get realmId; SnRealm? get realm; String? get publisherId; SnPublisher? get publisher; String? get actorid; SnActivityPubActor? get actor; String? get fediverseUri; int? get fediverseType; int get contentType; List<SnCloudFile> get attachments; Map<String, int> get reactionsCount; Map<String, bool> get reactionsMade; List<dynamic> get reactions; List<SnPostTag> get tags; List<SnPostCategory> get categories; List<dynamic> get collections; List<SnPostFeaturedRecord> get featuredRecords; DateTime? get createdAt; DateTime? get updatedAt; DateTime? get deletedAt; bool get repliedGone; bool get forwardedGone; bool get isTruncated;
/// Create a copy of SnPost
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -28,16 +28,16 @@ $SnPostCopyWith<SnPost> get copyWith => _$SnPostCopyWithImpl<SnPost>(this as SnP
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnPost&&(identical(other.id, id) || other.id == id)&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.language, language) || other.language == language)&&(identical(other.editedAt, editedAt) || other.editedAt == editedAt)&&(identical(other.publishedAt, publishedAt) || other.publishedAt == publishedAt)&&(identical(other.visibility, visibility) || other.visibility == visibility)&&(identical(other.content, content) || other.content == content)&&(identical(other.slug, slug) || other.slug == slug)&&(identical(other.type, type) || other.type == type)&&const DeepCollectionEquality().equals(other.meta, meta)&&(identical(other.embedView, embedView) || other.embedView == embedView)&&(identical(other.viewsUnique, viewsUnique) || other.viewsUnique == viewsUnique)&&(identical(other.viewsTotal, viewsTotal) || other.viewsTotal == viewsTotal)&&(identical(other.upvotes, upvotes) || other.upvotes == upvotes)&&(identical(other.downvotes, downvotes) || other.downvotes == downvotes)&&(identical(other.repliesCount, repliesCount) || other.repliesCount == repliesCount)&&(identical(other.awardedScore, awardedScore) || other.awardedScore == awardedScore)&&(identical(other.pinMode, pinMode) || other.pinMode == pinMode)&&(identical(other.threadedPostId, threadedPostId) || other.threadedPostId == threadedPostId)&&(identical(other.threadedPost, threadedPost) || other.threadedPost == threadedPost)&&(identical(other.repliedPostId, repliedPostId) || other.repliedPostId == repliedPostId)&&(identical(other.repliedPost, repliedPost) || other.repliedPost == repliedPost)&&(identical(other.forwardedPostId, forwardedPostId) || other.forwardedPostId == forwardedPostId)&&(identical(other.forwardedPost, forwardedPost) || other.forwardedPost == forwardedPost)&&(identical(other.realmId, realmId) || other.realmId == realmId)&&(identical(other.realm, realm) || other.realm == realm)&&const DeepCollectionEquality().equals(other.attachments, attachments)&&(identical(other.publisher, publisher) || other.publisher == publisher)&&const DeepCollectionEquality().equals(other.reactionsCount, reactionsCount)&&const DeepCollectionEquality().equals(other.reactionsMade, reactionsMade)&&const DeepCollectionEquality().equals(other.reactions, reactions)&&const DeepCollectionEquality().equals(other.tags, tags)&&const DeepCollectionEquality().equals(other.categories, categories)&&const DeepCollectionEquality().equals(other.collections, collections)&&const DeepCollectionEquality().equals(other.featuredRecords, featuredRecords)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.repliedGone, repliedGone) || other.repliedGone == repliedGone)&&(identical(other.forwardedGone, forwardedGone) || other.forwardedGone == forwardedGone)&&(identical(other.isTruncated, isTruncated) || other.isTruncated == isTruncated));
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnPost&&(identical(other.id, id) || other.id == id)&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.language, language) || other.language == language)&&(identical(other.editedAt, editedAt) || other.editedAt == editedAt)&&(identical(other.publishedAt, publishedAt) || other.publishedAt == publishedAt)&&(identical(other.visibility, visibility) || other.visibility == visibility)&&(identical(other.content, content) || other.content == content)&&(identical(other.slug, slug) || other.slug == slug)&&(identical(other.type, type) || other.type == type)&&const DeepCollectionEquality().equals(other.meta, meta)&&(identical(other.embedView, embedView) || other.embedView == embedView)&&(identical(other.viewsUnique, viewsUnique) || other.viewsUnique == viewsUnique)&&(identical(other.viewsTotal, viewsTotal) || other.viewsTotal == viewsTotal)&&(identical(other.upvotes, upvotes) || other.upvotes == upvotes)&&(identical(other.downvotes, downvotes) || other.downvotes == downvotes)&&(identical(other.repliesCount, repliesCount) || other.repliesCount == repliesCount)&&(identical(other.awardedScore, awardedScore) || other.awardedScore == awardedScore)&&(identical(other.pinMode, pinMode) || other.pinMode == pinMode)&&(identical(other.threadedPostId, threadedPostId) || other.threadedPostId == threadedPostId)&&(identical(other.threadedPost, threadedPost) || other.threadedPost == threadedPost)&&(identical(other.repliedPostId, repliedPostId) || other.repliedPostId == repliedPostId)&&(identical(other.repliedPost, repliedPost) || other.repliedPost == repliedPost)&&(identical(other.forwardedPostId, forwardedPostId) || other.forwardedPostId == forwardedPostId)&&(identical(other.forwardedPost, forwardedPost) || other.forwardedPost == forwardedPost)&&(identical(other.realmId, realmId) || other.realmId == realmId)&&(identical(other.realm, realm) || other.realm == realm)&&(identical(other.publisherId, publisherId) || other.publisherId == publisherId)&&(identical(other.publisher, publisher) || other.publisher == publisher)&&(identical(other.actorid, actorid) || other.actorid == actorid)&&(identical(other.actor, actor) || other.actor == actor)&&(identical(other.fediverseUri, fediverseUri) || other.fediverseUri == fediverseUri)&&(identical(other.fediverseType, fediverseType) || other.fediverseType == fediverseType)&&(identical(other.contentType, contentType) || other.contentType == contentType)&&const DeepCollectionEquality().equals(other.attachments, attachments)&&const DeepCollectionEquality().equals(other.reactionsCount, reactionsCount)&&const DeepCollectionEquality().equals(other.reactionsMade, reactionsMade)&&const DeepCollectionEquality().equals(other.reactions, reactions)&&const DeepCollectionEquality().equals(other.tags, tags)&&const DeepCollectionEquality().equals(other.categories, categories)&&const DeepCollectionEquality().equals(other.collections, collections)&&const DeepCollectionEquality().equals(other.featuredRecords, featuredRecords)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.repliedGone, repliedGone) || other.repliedGone == repliedGone)&&(identical(other.forwardedGone, forwardedGone) || other.forwardedGone == forwardedGone)&&(identical(other.isTruncated, isTruncated) || other.isTruncated == isTruncated));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hashAll([runtimeType,id,title,description,language,editedAt,publishedAt,visibility,content,slug,type,const DeepCollectionEquality().hash(meta),embedView,viewsUnique,viewsTotal,upvotes,downvotes,repliesCount,awardedScore,pinMode,threadedPostId,threadedPost,repliedPostId,repliedPost,forwardedPostId,forwardedPost,realmId,realm,const DeepCollectionEquality().hash(attachments),publisher,const DeepCollectionEquality().hash(reactionsCount),const DeepCollectionEquality().hash(reactionsMade),const DeepCollectionEquality().hash(reactions),const DeepCollectionEquality().hash(tags),const DeepCollectionEquality().hash(categories),const DeepCollectionEquality().hash(collections),const DeepCollectionEquality().hash(featuredRecords),createdAt,updatedAt,deletedAt,repliedGone,forwardedGone,isTruncated]);
int get hashCode => Object.hashAll([runtimeType,id,title,description,language,editedAt,publishedAt,visibility,content,slug,type,const DeepCollectionEquality().hash(meta),embedView,viewsUnique,viewsTotal,upvotes,downvotes,repliesCount,awardedScore,pinMode,threadedPostId,threadedPost,repliedPostId,repliedPost,forwardedPostId,forwardedPost,realmId,realm,publisherId,publisher,actorid,actor,fediverseUri,fediverseType,contentType,const DeepCollectionEquality().hash(attachments),const DeepCollectionEquality().hash(reactionsCount),const DeepCollectionEquality().hash(reactionsMade),const DeepCollectionEquality().hash(reactions),const DeepCollectionEquality().hash(tags),const DeepCollectionEquality().hash(categories),const DeepCollectionEquality().hash(collections),const DeepCollectionEquality().hash(featuredRecords),createdAt,updatedAt,deletedAt,repliedGone,forwardedGone,isTruncated]);
@override
String toString() {
return 'SnPost(id: $id, title: $title, description: $description, language: $language, editedAt: $editedAt, publishedAt: $publishedAt, visibility: $visibility, content: $content, slug: $slug, type: $type, meta: $meta, embedView: $embedView, viewsUnique: $viewsUnique, viewsTotal: $viewsTotal, upvotes: $upvotes, downvotes: $downvotes, repliesCount: $repliesCount, awardedScore: $awardedScore, pinMode: $pinMode, threadedPostId: $threadedPostId, threadedPost: $threadedPost, repliedPostId: $repliedPostId, repliedPost: $repliedPost, forwardedPostId: $forwardedPostId, forwardedPost: $forwardedPost, realmId: $realmId, realm: $realm, attachments: $attachments, publisher: $publisher, reactionsCount: $reactionsCount, reactionsMade: $reactionsMade, reactions: $reactions, tags: $tags, categories: $categories, collections: $collections, featuredRecords: $featuredRecords, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, repliedGone: $repliedGone, forwardedGone: $forwardedGone, isTruncated: $isTruncated)';
return 'SnPost(id: $id, title: $title, description: $description, language: $language, editedAt: $editedAt, publishedAt: $publishedAt, visibility: $visibility, content: $content, slug: $slug, type: $type, meta: $meta, embedView: $embedView, viewsUnique: $viewsUnique, viewsTotal: $viewsTotal, upvotes: $upvotes, downvotes: $downvotes, repliesCount: $repliesCount, awardedScore: $awardedScore, pinMode: $pinMode, threadedPostId: $threadedPostId, threadedPost: $threadedPost, repliedPostId: $repliedPostId, repliedPost: $repliedPost, forwardedPostId: $forwardedPostId, forwardedPost: $forwardedPost, realmId: $realmId, realm: $realm, publisherId: $publisherId, publisher: $publisher, actorid: $actorid, actor: $actor, fediverseUri: $fediverseUri, fediverseType: $fediverseType, contentType: $contentType, attachments: $attachments, reactionsCount: $reactionsCount, reactionsMade: $reactionsMade, reactions: $reactions, tags: $tags, categories: $categories, collections: $collections, featuredRecords: $featuredRecords, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, repliedGone: $repliedGone, forwardedGone: $forwardedGone, isTruncated: $isTruncated)';
}
@@ -48,11 +48,11 @@ abstract mixin class $SnPostCopyWith<$Res> {
factory $SnPostCopyWith(SnPost value, $Res Function(SnPost) _then) = _$SnPostCopyWithImpl;
@useResult
$Res call({
String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, List<SnCloudFile> attachments, SnPublisher publisher, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated
String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, String? publisherId, SnPublisher? publisher, String? actorid, SnActivityPubActor? actor, String? fediverseUri, int? fediverseType, int contentType, List<SnCloudFile> attachments, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated
});
$SnPostEmbedViewCopyWith<$Res>? get embedView;$SnPostCopyWith<$Res>? get threadedPost;$SnPostCopyWith<$Res>? get repliedPost;$SnPostCopyWith<$Res>? get forwardedPost;$SnRealmCopyWith<$Res>? get realm;$SnPublisherCopyWith<$Res> get publisher;
$SnPostEmbedViewCopyWith<$Res>? get embedView;$SnPostCopyWith<$Res>? get threadedPost;$SnPostCopyWith<$Res>? get repliedPost;$SnPostCopyWith<$Res>? get forwardedPost;$SnRealmCopyWith<$Res>? get realm;$SnPublisherCopyWith<$Res>? get publisher;$SnActivityPubActorCopyWith<$Res>? get actor;
}
/// @nodoc
@@ -65,7 +65,7 @@ class _$SnPostCopyWithImpl<$Res>
/// Create a copy of SnPost
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? title = freezed,Object? description = freezed,Object? language = freezed,Object? editedAt = freezed,Object? publishedAt = freezed,Object? visibility = null,Object? content = freezed,Object? slug = freezed,Object? type = null,Object? meta = freezed,Object? embedView = freezed,Object? viewsUnique = null,Object? viewsTotal = null,Object? upvotes = null,Object? downvotes = null,Object? repliesCount = null,Object? awardedScore = null,Object? pinMode = freezed,Object? threadedPostId = freezed,Object? threadedPost = freezed,Object? repliedPostId = freezed,Object? repliedPost = freezed,Object? forwardedPostId = freezed,Object? forwardedPost = freezed,Object? realmId = freezed,Object? realm = freezed,Object? attachments = null,Object? publisher = null,Object? reactionsCount = null,Object? reactionsMade = null,Object? reactions = null,Object? tags = null,Object? categories = null,Object? collections = null,Object? featuredRecords = null,Object? createdAt = freezed,Object? updatedAt = freezed,Object? deletedAt = freezed,Object? repliedGone = null,Object? forwardedGone = null,Object? isTruncated = null,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? title = freezed,Object? description = freezed,Object? language = freezed,Object? editedAt = freezed,Object? publishedAt = freezed,Object? visibility = null,Object? content = freezed,Object? slug = freezed,Object? type = null,Object? meta = freezed,Object? embedView = freezed,Object? viewsUnique = null,Object? viewsTotal = null,Object? upvotes = null,Object? downvotes = null,Object? repliesCount = null,Object? awardedScore = null,Object? pinMode = freezed,Object? threadedPostId = freezed,Object? threadedPost = freezed,Object? repliedPostId = freezed,Object? repliedPost = freezed,Object? forwardedPostId = freezed,Object? forwardedPost = freezed,Object? realmId = freezed,Object? realm = freezed,Object? publisherId = freezed,Object? publisher = freezed,Object? actorid = freezed,Object? actor = freezed,Object? fediverseUri = freezed,Object? fediverseType = freezed,Object? contentType = null,Object? attachments = null,Object? reactionsCount = null,Object? reactionsMade = null,Object? reactions = null,Object? tags = null,Object? categories = null,Object? collections = null,Object? featuredRecords = null,Object? createdAt = freezed,Object? updatedAt = freezed,Object? deletedAt = freezed,Object? repliedGone = null,Object? forwardedGone = null,Object? isTruncated = null,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,title: freezed == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
@@ -94,9 +94,15 @@ as SnPost?,forwardedPostId: freezed == forwardedPostId ? _self.forwardedPostId :
as String?,forwardedPost: freezed == forwardedPost ? _self.forwardedPost : forwardedPost // ignore: cast_nullable_to_non_nullable
as SnPost?,realmId: freezed == realmId ? _self.realmId : realmId // ignore: cast_nullable_to_non_nullable
as String?,realm: freezed == realm ? _self.realm : realm // ignore: cast_nullable_to_non_nullable
as SnRealm?,attachments: null == attachments ? _self.attachments : attachments // ignore: cast_nullable_to_non_nullable
as List<SnCloudFile>,publisher: null == publisher ? _self.publisher : publisher // ignore: cast_nullable_to_non_nullable
as SnPublisher,reactionsCount: null == reactionsCount ? _self.reactionsCount : reactionsCount // ignore: cast_nullable_to_non_nullable
as SnRealm?,publisherId: freezed == publisherId ? _self.publisherId : publisherId // ignore: cast_nullable_to_non_nullable
as String?,publisher: freezed == publisher ? _self.publisher : publisher // ignore: cast_nullable_to_non_nullable
as SnPublisher?,actorid: freezed == actorid ? _self.actorid : actorid // ignore: cast_nullable_to_non_nullable
as String?,actor: freezed == actor ? _self.actor : actor // ignore: cast_nullable_to_non_nullable
as SnActivityPubActor?,fediverseUri: freezed == fediverseUri ? _self.fediverseUri : fediverseUri // ignore: cast_nullable_to_non_nullable
as String?,fediverseType: freezed == fediverseType ? _self.fediverseType : fediverseType // ignore: cast_nullable_to_non_nullable
as int?,contentType: null == contentType ? _self.contentType : contentType // ignore: cast_nullable_to_non_nullable
as int,attachments: null == attachments ? _self.attachments : attachments // ignore: cast_nullable_to_non_nullable
as List<SnCloudFile>,reactionsCount: null == reactionsCount ? _self.reactionsCount : reactionsCount // ignore: cast_nullable_to_non_nullable
as Map<String, int>,reactionsMade: null == reactionsMade ? _self.reactionsMade : reactionsMade // ignore: cast_nullable_to_non_nullable
as Map<String, bool>,reactions: null == reactions ? _self.reactions : reactions // ignore: cast_nullable_to_non_nullable
as List<dynamic>,tags: null == tags ? _self.tags : tags // ignore: cast_nullable_to_non_nullable
@@ -176,11 +182,26 @@ $SnRealmCopyWith<$Res>? get realm {
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnPublisherCopyWith<$Res> get publisher {
return $SnPublisherCopyWith<$Res>(_self.publisher, (value) {
$SnPublisherCopyWith<$Res>? get publisher {
if (_self.publisher == null) {
return null;
}
return $SnPublisherCopyWith<$Res>(_self.publisher!, (value) {
return _then(_self.copyWith(publisher: value));
});
}/// Create a copy of SnPost
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnActivityPubActorCopyWith<$Res>? get actor {
if (_self.actor == null) {
return null;
}
return $SnActivityPubActorCopyWith<$Res>(_self.actor!, (value) {
return _then(_self.copyWith(actor: value));
});
}
}
@@ -260,10 +281,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, List<SnCloudFile> attachments, SnPublisher publisher, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, String? publisherId, SnPublisher? publisher, String? actorid, SnActivityPubActor? actor, String? fediverseUri, int? fediverseType, int contentType, List<SnCloudFile> attachments, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnPost() when $default != null:
return $default(_that.id,_that.title,_that.description,_that.language,_that.editedAt,_that.publishedAt,_that.visibility,_that.content,_that.slug,_that.type,_that.meta,_that.embedView,_that.viewsUnique,_that.viewsTotal,_that.upvotes,_that.downvotes,_that.repliesCount,_that.awardedScore,_that.pinMode,_that.threadedPostId,_that.threadedPost,_that.repliedPostId,_that.repliedPost,_that.forwardedPostId,_that.forwardedPost,_that.realmId,_that.realm,_that.attachments,_that.publisher,_that.reactionsCount,_that.reactionsMade,_that.reactions,_that.tags,_that.categories,_that.collections,_that.featuredRecords,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.repliedGone,_that.forwardedGone,_that.isTruncated);case _:
return $default(_that.id,_that.title,_that.description,_that.language,_that.editedAt,_that.publishedAt,_that.visibility,_that.content,_that.slug,_that.type,_that.meta,_that.embedView,_that.viewsUnique,_that.viewsTotal,_that.upvotes,_that.downvotes,_that.repliesCount,_that.awardedScore,_that.pinMode,_that.threadedPostId,_that.threadedPost,_that.repliedPostId,_that.repliedPost,_that.forwardedPostId,_that.forwardedPost,_that.realmId,_that.realm,_that.publisherId,_that.publisher,_that.actorid,_that.actor,_that.fediverseUri,_that.fediverseType,_that.contentType,_that.attachments,_that.reactionsCount,_that.reactionsMade,_that.reactions,_that.tags,_that.categories,_that.collections,_that.featuredRecords,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.repliedGone,_that.forwardedGone,_that.isTruncated);case _:
return orElse();
}
@@ -281,10 +302,10 @@ return $default(_that.id,_that.title,_that.description,_that.language,_that.edit
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, List<SnCloudFile> attachments, SnPublisher publisher, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, String? publisherId, SnPublisher? publisher, String? actorid, SnActivityPubActor? actor, String? fediverseUri, int? fediverseType, int contentType, List<SnCloudFile> attachments, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated) $default,) {final _that = this;
switch (_that) {
case _SnPost():
return $default(_that.id,_that.title,_that.description,_that.language,_that.editedAt,_that.publishedAt,_that.visibility,_that.content,_that.slug,_that.type,_that.meta,_that.embedView,_that.viewsUnique,_that.viewsTotal,_that.upvotes,_that.downvotes,_that.repliesCount,_that.awardedScore,_that.pinMode,_that.threadedPostId,_that.threadedPost,_that.repliedPostId,_that.repliedPost,_that.forwardedPostId,_that.forwardedPost,_that.realmId,_that.realm,_that.attachments,_that.publisher,_that.reactionsCount,_that.reactionsMade,_that.reactions,_that.tags,_that.categories,_that.collections,_that.featuredRecords,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.repliedGone,_that.forwardedGone,_that.isTruncated);}
return $default(_that.id,_that.title,_that.description,_that.language,_that.editedAt,_that.publishedAt,_that.visibility,_that.content,_that.slug,_that.type,_that.meta,_that.embedView,_that.viewsUnique,_that.viewsTotal,_that.upvotes,_that.downvotes,_that.repliesCount,_that.awardedScore,_that.pinMode,_that.threadedPostId,_that.threadedPost,_that.repliedPostId,_that.repliedPost,_that.forwardedPostId,_that.forwardedPost,_that.realmId,_that.realm,_that.publisherId,_that.publisher,_that.actorid,_that.actor,_that.fediverseUri,_that.fediverseType,_that.contentType,_that.attachments,_that.reactionsCount,_that.reactionsMade,_that.reactions,_that.tags,_that.categories,_that.collections,_that.featuredRecords,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.repliedGone,_that.forwardedGone,_that.isTruncated);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -298,10 +319,10 @@ return $default(_that.id,_that.title,_that.description,_that.language,_that.edit
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, List<SnCloudFile> attachments, SnPublisher publisher, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, String? publisherId, SnPublisher? publisher, String? actorid, SnActivityPubActor? actor, String? fediverseUri, int? fediverseType, int contentType, List<SnCloudFile> attachments, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated)? $default,) {final _that = this;
switch (_that) {
case _SnPost() when $default != null:
return $default(_that.id,_that.title,_that.description,_that.language,_that.editedAt,_that.publishedAt,_that.visibility,_that.content,_that.slug,_that.type,_that.meta,_that.embedView,_that.viewsUnique,_that.viewsTotal,_that.upvotes,_that.downvotes,_that.repliesCount,_that.awardedScore,_that.pinMode,_that.threadedPostId,_that.threadedPost,_that.repliedPostId,_that.repliedPost,_that.forwardedPostId,_that.forwardedPost,_that.realmId,_that.realm,_that.attachments,_that.publisher,_that.reactionsCount,_that.reactionsMade,_that.reactions,_that.tags,_that.categories,_that.collections,_that.featuredRecords,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.repliedGone,_that.forwardedGone,_that.isTruncated);case _:
return $default(_that.id,_that.title,_that.description,_that.language,_that.editedAt,_that.publishedAt,_that.visibility,_that.content,_that.slug,_that.type,_that.meta,_that.embedView,_that.viewsUnique,_that.viewsTotal,_that.upvotes,_that.downvotes,_that.repliesCount,_that.awardedScore,_that.pinMode,_that.threadedPostId,_that.threadedPost,_that.repliedPostId,_that.repliedPost,_that.forwardedPostId,_that.forwardedPost,_that.realmId,_that.realm,_that.publisherId,_that.publisher,_that.actorid,_that.actor,_that.fediverseUri,_that.fediverseType,_that.contentType,_that.attachments,_that.reactionsCount,_that.reactionsMade,_that.reactions,_that.tags,_that.categories,_that.collections,_that.featuredRecords,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.repliedGone,_that.forwardedGone,_that.isTruncated);case _:
return null;
}
@@ -313,7 +334,7 @@ return $default(_that.id,_that.title,_that.description,_that.language,_that.edit
@JsonSerializable()
class _SnPost implements SnPost {
const _SnPost({required this.id, this.title, this.description, this.language, this.editedAt, this.publishedAt = null, this.visibility = 0, this.content, this.slug, this.type = 0, final Map<String, dynamic>? meta, this.embedView, this.viewsUnique = 0, this.viewsTotal = 0, this.upvotes = 0, this.downvotes = 0, this.repliesCount = 0, this.awardedScore = 0, this.pinMode, this.threadedPostId, this.threadedPost, this.repliedPostId, this.repliedPost, this.forwardedPostId, this.forwardedPost, this.realmId, this.realm, final List<SnCloudFile> attachments = const [], required this.publisher, final Map<String, int> reactionsCount = const {}, final Map<String, bool> reactionsMade = const {}, final List<dynamic> reactions = const [], final List<SnPostTag> tags = const [], final List<SnPostCategory> categories = const [], final List<dynamic> collections = const [], final List<SnPostFeaturedRecord> featuredRecords = const [], this.createdAt = null, this.updatedAt = null, this.deletedAt, this.repliedGone = false, this.forwardedGone = false, this.isTruncated = false}): _meta = meta,_attachments = attachments,_reactionsCount = reactionsCount,_reactionsMade = reactionsMade,_reactions = reactions,_tags = tags,_categories = categories,_collections = collections,_featuredRecords = featuredRecords;
const _SnPost({required this.id, this.title, this.description, this.language, this.editedAt, this.publishedAt = null, this.visibility = 0, this.content, this.slug, this.type = 0, final Map<String, dynamic>? meta, this.embedView, this.viewsUnique = 0, this.viewsTotal = 0, this.upvotes = 0, this.downvotes = 0, this.repliesCount = 0, this.awardedScore = 0, this.pinMode, this.threadedPostId, this.threadedPost, this.repliedPostId, this.repliedPost, this.forwardedPostId, this.forwardedPost, this.realmId, this.realm, this.publisherId, this.publisher, this.actorid, this.actor, this.fediverseUri, this.fediverseType, this.contentType = 0, final List<SnCloudFile> attachments = const [], final Map<String, int> reactionsCount = const {}, final Map<String, bool> reactionsMade = const {}, final List<dynamic> reactions = const [], final List<SnPostTag> tags = const [], final List<SnPostCategory> categories = const [], final List<dynamic> collections = const [], final List<SnPostFeaturedRecord> featuredRecords = const [], this.createdAt = null, this.updatedAt = null, this.deletedAt, this.repliedGone = false, this.forwardedGone = false, this.isTruncated = false}): _meta = meta,_attachments = attachments,_reactionsCount = reactionsCount,_reactionsMade = reactionsMade,_reactions = reactions,_tags = tags,_categories = categories,_collections = collections,_featuredRecords = featuredRecords;
factory _SnPost.fromJson(Map<String, dynamic> json) => _$SnPostFromJson(json);
@override final String id;
@@ -351,6 +372,13 @@ class _SnPost implements SnPost {
@override final SnPost? forwardedPost;
@override final String? realmId;
@override final SnRealm? realm;
@override final String? publisherId;
@override final SnPublisher? publisher;
@override final String? actorid;
@override final SnActivityPubActor? actor;
@override final String? fediverseUri;
@override final int? fediverseType;
@override@JsonKey() final int contentType;
final List<SnCloudFile> _attachments;
@override@JsonKey() List<SnCloudFile> get attachments {
if (_attachments is EqualUnmodifiableListView) return _attachments;
@@ -358,7 +386,6 @@ class _SnPost implements SnPost {
return EqualUnmodifiableListView(_attachments);
}
@override final SnPublisher publisher;
final Map<String, int> _reactionsCount;
@override@JsonKey() Map<String, int> get reactionsCount {
if (_reactionsCount is EqualUnmodifiableMapView) return _reactionsCount;
@@ -428,16 +455,16 @@ Map<String, dynamic> toJson() {
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnPost&&(identical(other.id, id) || other.id == id)&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.language, language) || other.language == language)&&(identical(other.editedAt, editedAt) || other.editedAt == editedAt)&&(identical(other.publishedAt, publishedAt) || other.publishedAt == publishedAt)&&(identical(other.visibility, visibility) || other.visibility == visibility)&&(identical(other.content, content) || other.content == content)&&(identical(other.slug, slug) || other.slug == slug)&&(identical(other.type, type) || other.type == type)&&const DeepCollectionEquality().equals(other._meta, _meta)&&(identical(other.embedView, embedView) || other.embedView == embedView)&&(identical(other.viewsUnique, viewsUnique) || other.viewsUnique == viewsUnique)&&(identical(other.viewsTotal, viewsTotal) || other.viewsTotal == viewsTotal)&&(identical(other.upvotes, upvotes) || other.upvotes == upvotes)&&(identical(other.downvotes, downvotes) || other.downvotes == downvotes)&&(identical(other.repliesCount, repliesCount) || other.repliesCount == repliesCount)&&(identical(other.awardedScore, awardedScore) || other.awardedScore == awardedScore)&&(identical(other.pinMode, pinMode) || other.pinMode == pinMode)&&(identical(other.threadedPostId, threadedPostId) || other.threadedPostId == threadedPostId)&&(identical(other.threadedPost, threadedPost) || other.threadedPost == threadedPost)&&(identical(other.repliedPostId, repliedPostId) || other.repliedPostId == repliedPostId)&&(identical(other.repliedPost, repliedPost) || other.repliedPost == repliedPost)&&(identical(other.forwardedPostId, forwardedPostId) || other.forwardedPostId == forwardedPostId)&&(identical(other.forwardedPost, forwardedPost) || other.forwardedPost == forwardedPost)&&(identical(other.realmId, realmId) || other.realmId == realmId)&&(identical(other.realm, realm) || other.realm == realm)&&const DeepCollectionEquality().equals(other._attachments, _attachments)&&(identical(other.publisher, publisher) || other.publisher == publisher)&&const DeepCollectionEquality().equals(other._reactionsCount, _reactionsCount)&&const DeepCollectionEquality().equals(other._reactionsMade, _reactionsMade)&&const DeepCollectionEquality().equals(other._reactions, _reactions)&&const DeepCollectionEquality().equals(other._tags, _tags)&&const DeepCollectionEquality().equals(other._categories, _categories)&&const DeepCollectionEquality().equals(other._collections, _collections)&&const DeepCollectionEquality().equals(other._featuredRecords, _featuredRecords)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.repliedGone, repliedGone) || other.repliedGone == repliedGone)&&(identical(other.forwardedGone, forwardedGone) || other.forwardedGone == forwardedGone)&&(identical(other.isTruncated, isTruncated) || other.isTruncated == isTruncated));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnPost&&(identical(other.id, id) || other.id == id)&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.language, language) || other.language == language)&&(identical(other.editedAt, editedAt) || other.editedAt == editedAt)&&(identical(other.publishedAt, publishedAt) || other.publishedAt == publishedAt)&&(identical(other.visibility, visibility) || other.visibility == visibility)&&(identical(other.content, content) || other.content == content)&&(identical(other.slug, slug) || other.slug == slug)&&(identical(other.type, type) || other.type == type)&&const DeepCollectionEquality().equals(other._meta, _meta)&&(identical(other.embedView, embedView) || other.embedView == embedView)&&(identical(other.viewsUnique, viewsUnique) || other.viewsUnique == viewsUnique)&&(identical(other.viewsTotal, viewsTotal) || other.viewsTotal == viewsTotal)&&(identical(other.upvotes, upvotes) || other.upvotes == upvotes)&&(identical(other.downvotes, downvotes) || other.downvotes == downvotes)&&(identical(other.repliesCount, repliesCount) || other.repliesCount == repliesCount)&&(identical(other.awardedScore, awardedScore) || other.awardedScore == awardedScore)&&(identical(other.pinMode, pinMode) || other.pinMode == pinMode)&&(identical(other.threadedPostId, threadedPostId) || other.threadedPostId == threadedPostId)&&(identical(other.threadedPost, threadedPost) || other.threadedPost == threadedPost)&&(identical(other.repliedPostId, repliedPostId) || other.repliedPostId == repliedPostId)&&(identical(other.repliedPost, repliedPost) || other.repliedPost == repliedPost)&&(identical(other.forwardedPostId, forwardedPostId) || other.forwardedPostId == forwardedPostId)&&(identical(other.forwardedPost, forwardedPost) || other.forwardedPost == forwardedPost)&&(identical(other.realmId, realmId) || other.realmId == realmId)&&(identical(other.realm, realm) || other.realm == realm)&&(identical(other.publisherId, publisherId) || other.publisherId == publisherId)&&(identical(other.publisher, publisher) || other.publisher == publisher)&&(identical(other.actorid, actorid) || other.actorid == actorid)&&(identical(other.actor, actor) || other.actor == actor)&&(identical(other.fediverseUri, fediverseUri) || other.fediverseUri == fediverseUri)&&(identical(other.fediverseType, fediverseType) || other.fediverseType == fediverseType)&&(identical(other.contentType, contentType) || other.contentType == contentType)&&const DeepCollectionEquality().equals(other._attachments, _attachments)&&const DeepCollectionEquality().equals(other._reactionsCount, _reactionsCount)&&const DeepCollectionEquality().equals(other._reactionsMade, _reactionsMade)&&const DeepCollectionEquality().equals(other._reactions, _reactions)&&const DeepCollectionEquality().equals(other._tags, _tags)&&const DeepCollectionEquality().equals(other._categories, _categories)&&const DeepCollectionEquality().equals(other._collections, _collections)&&const DeepCollectionEquality().equals(other._featuredRecords, _featuredRecords)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.repliedGone, repliedGone) || other.repliedGone == repliedGone)&&(identical(other.forwardedGone, forwardedGone) || other.forwardedGone == forwardedGone)&&(identical(other.isTruncated, isTruncated) || other.isTruncated == isTruncated));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hashAll([runtimeType,id,title,description,language,editedAt,publishedAt,visibility,content,slug,type,const DeepCollectionEquality().hash(_meta),embedView,viewsUnique,viewsTotal,upvotes,downvotes,repliesCount,awardedScore,pinMode,threadedPostId,threadedPost,repliedPostId,repliedPost,forwardedPostId,forwardedPost,realmId,realm,const DeepCollectionEquality().hash(_attachments),publisher,const DeepCollectionEquality().hash(_reactionsCount),const DeepCollectionEquality().hash(_reactionsMade),const DeepCollectionEquality().hash(_reactions),const DeepCollectionEquality().hash(_tags),const DeepCollectionEquality().hash(_categories),const DeepCollectionEquality().hash(_collections),const DeepCollectionEquality().hash(_featuredRecords),createdAt,updatedAt,deletedAt,repliedGone,forwardedGone,isTruncated]);
int get hashCode => Object.hashAll([runtimeType,id,title,description,language,editedAt,publishedAt,visibility,content,slug,type,const DeepCollectionEquality().hash(_meta),embedView,viewsUnique,viewsTotal,upvotes,downvotes,repliesCount,awardedScore,pinMode,threadedPostId,threadedPost,repliedPostId,repliedPost,forwardedPostId,forwardedPost,realmId,realm,publisherId,publisher,actorid,actor,fediverseUri,fediverseType,contentType,const DeepCollectionEquality().hash(_attachments),const DeepCollectionEquality().hash(_reactionsCount),const DeepCollectionEquality().hash(_reactionsMade),const DeepCollectionEquality().hash(_reactions),const DeepCollectionEquality().hash(_tags),const DeepCollectionEquality().hash(_categories),const DeepCollectionEquality().hash(_collections),const DeepCollectionEquality().hash(_featuredRecords),createdAt,updatedAt,deletedAt,repliedGone,forwardedGone,isTruncated]);
@override
String toString() {
return 'SnPost(id: $id, title: $title, description: $description, language: $language, editedAt: $editedAt, publishedAt: $publishedAt, visibility: $visibility, content: $content, slug: $slug, type: $type, meta: $meta, embedView: $embedView, viewsUnique: $viewsUnique, viewsTotal: $viewsTotal, upvotes: $upvotes, downvotes: $downvotes, repliesCount: $repliesCount, awardedScore: $awardedScore, pinMode: $pinMode, threadedPostId: $threadedPostId, threadedPost: $threadedPost, repliedPostId: $repliedPostId, repliedPost: $repliedPost, forwardedPostId: $forwardedPostId, forwardedPost: $forwardedPost, realmId: $realmId, realm: $realm, attachments: $attachments, publisher: $publisher, reactionsCount: $reactionsCount, reactionsMade: $reactionsMade, reactions: $reactions, tags: $tags, categories: $categories, collections: $collections, featuredRecords: $featuredRecords, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, repliedGone: $repliedGone, forwardedGone: $forwardedGone, isTruncated: $isTruncated)';
return 'SnPost(id: $id, title: $title, description: $description, language: $language, editedAt: $editedAt, publishedAt: $publishedAt, visibility: $visibility, content: $content, slug: $slug, type: $type, meta: $meta, embedView: $embedView, viewsUnique: $viewsUnique, viewsTotal: $viewsTotal, upvotes: $upvotes, downvotes: $downvotes, repliesCount: $repliesCount, awardedScore: $awardedScore, pinMode: $pinMode, threadedPostId: $threadedPostId, threadedPost: $threadedPost, repliedPostId: $repliedPostId, repliedPost: $repliedPost, forwardedPostId: $forwardedPostId, forwardedPost: $forwardedPost, realmId: $realmId, realm: $realm, publisherId: $publisherId, publisher: $publisher, actorid: $actorid, actor: $actor, fediverseUri: $fediverseUri, fediverseType: $fediverseType, contentType: $contentType, attachments: $attachments, reactionsCount: $reactionsCount, reactionsMade: $reactionsMade, reactions: $reactions, tags: $tags, categories: $categories, collections: $collections, featuredRecords: $featuredRecords, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, repliedGone: $repliedGone, forwardedGone: $forwardedGone, isTruncated: $isTruncated)';
}
@@ -448,11 +475,11 @@ abstract mixin class _$SnPostCopyWith<$Res> implements $SnPostCopyWith<$Res> {
factory _$SnPostCopyWith(_SnPost value, $Res Function(_SnPost) _then) = __$SnPostCopyWithImpl;
@override @useResult
$Res call({
String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, List<SnCloudFile> attachments, SnPublisher publisher, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated
String id, String? title, String? description, String? language, DateTime? editedAt, DateTime? publishedAt, int visibility, String? content, String? slug, int type, Map<String, dynamic>? meta, SnPostEmbedView? embedView, int viewsUnique, int viewsTotal, int upvotes, int downvotes, int repliesCount, int awardedScore, int? pinMode, String? threadedPostId, SnPost? threadedPost, String? repliedPostId, SnPost? repliedPost, String? forwardedPostId, SnPost? forwardedPost, String? realmId, SnRealm? realm, String? publisherId, SnPublisher? publisher, String? actorid, SnActivityPubActor? actor, String? fediverseUri, int? fediverseType, int contentType, List<SnCloudFile> attachments, Map<String, int> reactionsCount, Map<String, bool> reactionsMade, List<dynamic> reactions, List<SnPostTag> tags, List<SnPostCategory> categories, List<dynamic> collections, List<SnPostFeaturedRecord> featuredRecords, DateTime? createdAt, DateTime? updatedAt, DateTime? deletedAt, bool repliedGone, bool forwardedGone, bool isTruncated
});
@override $SnPostEmbedViewCopyWith<$Res>? get embedView;@override $SnPostCopyWith<$Res>? get threadedPost;@override $SnPostCopyWith<$Res>? get repliedPost;@override $SnPostCopyWith<$Res>? get forwardedPost;@override $SnRealmCopyWith<$Res>? get realm;@override $SnPublisherCopyWith<$Res> get publisher;
@override $SnPostEmbedViewCopyWith<$Res>? get embedView;@override $SnPostCopyWith<$Res>? get threadedPost;@override $SnPostCopyWith<$Res>? get repliedPost;@override $SnPostCopyWith<$Res>? get forwardedPost;@override $SnRealmCopyWith<$Res>? get realm;@override $SnPublisherCopyWith<$Res>? get publisher;@override $SnActivityPubActorCopyWith<$Res>? get actor;
}
/// @nodoc
@@ -465,7 +492,7 @@ class __$SnPostCopyWithImpl<$Res>
/// Create a copy of SnPost
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? title = freezed,Object? description = freezed,Object? language = freezed,Object? editedAt = freezed,Object? publishedAt = freezed,Object? visibility = null,Object? content = freezed,Object? slug = freezed,Object? type = null,Object? meta = freezed,Object? embedView = freezed,Object? viewsUnique = null,Object? viewsTotal = null,Object? upvotes = null,Object? downvotes = null,Object? repliesCount = null,Object? awardedScore = null,Object? pinMode = freezed,Object? threadedPostId = freezed,Object? threadedPost = freezed,Object? repliedPostId = freezed,Object? repliedPost = freezed,Object? forwardedPostId = freezed,Object? forwardedPost = freezed,Object? realmId = freezed,Object? realm = freezed,Object? attachments = null,Object? publisher = null,Object? reactionsCount = null,Object? reactionsMade = null,Object? reactions = null,Object? tags = null,Object? categories = null,Object? collections = null,Object? featuredRecords = null,Object? createdAt = freezed,Object? updatedAt = freezed,Object? deletedAt = freezed,Object? repliedGone = null,Object? forwardedGone = null,Object? isTruncated = null,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? title = freezed,Object? description = freezed,Object? language = freezed,Object? editedAt = freezed,Object? publishedAt = freezed,Object? visibility = null,Object? content = freezed,Object? slug = freezed,Object? type = null,Object? meta = freezed,Object? embedView = freezed,Object? viewsUnique = null,Object? viewsTotal = null,Object? upvotes = null,Object? downvotes = null,Object? repliesCount = null,Object? awardedScore = null,Object? pinMode = freezed,Object? threadedPostId = freezed,Object? threadedPost = freezed,Object? repliedPostId = freezed,Object? repliedPost = freezed,Object? forwardedPostId = freezed,Object? forwardedPost = freezed,Object? realmId = freezed,Object? realm = freezed,Object? publisherId = freezed,Object? publisher = freezed,Object? actorid = freezed,Object? actor = freezed,Object? fediverseUri = freezed,Object? fediverseType = freezed,Object? contentType = null,Object? attachments = null,Object? reactionsCount = null,Object? reactionsMade = null,Object? reactions = null,Object? tags = null,Object? categories = null,Object? collections = null,Object? featuredRecords = null,Object? createdAt = freezed,Object? updatedAt = freezed,Object? deletedAt = freezed,Object? repliedGone = null,Object? forwardedGone = null,Object? isTruncated = null,}) {
return _then(_SnPost(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,title: freezed == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
@@ -494,9 +521,15 @@ as SnPost?,forwardedPostId: freezed == forwardedPostId ? _self.forwardedPostId :
as String?,forwardedPost: freezed == forwardedPost ? _self.forwardedPost : forwardedPost // ignore: cast_nullable_to_non_nullable
as SnPost?,realmId: freezed == realmId ? _self.realmId : realmId // ignore: cast_nullable_to_non_nullable
as String?,realm: freezed == realm ? _self.realm : realm // ignore: cast_nullable_to_non_nullable
as SnRealm?,attachments: null == attachments ? _self._attachments : attachments // ignore: cast_nullable_to_non_nullable
as List<SnCloudFile>,publisher: null == publisher ? _self.publisher : publisher // ignore: cast_nullable_to_non_nullable
as SnPublisher,reactionsCount: null == reactionsCount ? _self._reactionsCount : reactionsCount // ignore: cast_nullable_to_non_nullable
as SnRealm?,publisherId: freezed == publisherId ? _self.publisherId : publisherId // ignore: cast_nullable_to_non_nullable
as String?,publisher: freezed == publisher ? _self.publisher : publisher // ignore: cast_nullable_to_non_nullable
as SnPublisher?,actorid: freezed == actorid ? _self.actorid : actorid // ignore: cast_nullable_to_non_nullable
as String?,actor: freezed == actor ? _self.actor : actor // ignore: cast_nullable_to_non_nullable
as SnActivityPubActor?,fediverseUri: freezed == fediverseUri ? _self.fediverseUri : fediverseUri // ignore: cast_nullable_to_non_nullable
as String?,fediverseType: freezed == fediverseType ? _self.fediverseType : fediverseType // ignore: cast_nullable_to_non_nullable
as int?,contentType: null == contentType ? _self.contentType : contentType // ignore: cast_nullable_to_non_nullable
as int,attachments: null == attachments ? _self._attachments : attachments // ignore: cast_nullable_to_non_nullable
as List<SnCloudFile>,reactionsCount: null == reactionsCount ? _self._reactionsCount : reactionsCount // ignore: cast_nullable_to_non_nullable
as Map<String, int>,reactionsMade: null == reactionsMade ? _self._reactionsMade : reactionsMade // ignore: cast_nullable_to_non_nullable
as Map<String, bool>,reactions: null == reactions ? _self._reactions : reactions // ignore: cast_nullable_to_non_nullable
as List<dynamic>,tags: null == tags ? _self._tags : tags // ignore: cast_nullable_to_non_nullable
@@ -577,11 +610,26 @@ $SnRealmCopyWith<$Res>? get realm {
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnPublisherCopyWith<$Res> get publisher {
return $SnPublisherCopyWith<$Res>(_self.publisher, (value) {
$SnPublisherCopyWith<$Res>? get publisher {
if (_self.publisher == null) {
return null;
}
return $SnPublisherCopyWith<$Res>(_self.publisher!, (value) {
return _then(_self.copyWith(publisher: value));
});
}/// Create a copy of SnPost
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnActivityPubActorCopyWith<$Res>? get actor {
if (_self.actor == null) {
return null;
}
return $SnActivityPubActorCopyWith<$Res>(_self.actor!, (value) {
return _then(_self.copyWith(actor: value));
});
}
}
@@ -1937,7 +1985,7 @@ as DateTime?,
/// @nodoc
mixin _$SnPostReaction {
String get id; String get symbol; int get attitude; String get postId; String get accountId; DateTime get createdAt; DateTime get updatedAt; SnAccount? get account; DateTime? get deletedAt;
String get id; String get symbol; int get attitude; String get postId; DateTime get createdAt; DateTime get updatedAt; String? get actorId; SnActivityPubActor? get actor; String? get accountId; SnAccount? get account; DateTime? get deletedAt;
/// Create a copy of SnPostReaction
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -1950,16 +1998,16 @@ $SnPostReactionCopyWith<SnPostReaction> get copyWith => _$SnPostReactionCopyWith
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnPostReaction&&(identical(other.id, id) || other.id == id)&&(identical(other.symbol, symbol) || other.symbol == symbol)&&(identical(other.attitude, attitude) || other.attitude == attitude)&&(identical(other.postId, postId) || other.postId == postId)&&(identical(other.accountId, accountId) || other.accountId == accountId)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.account, account) || other.account == account)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnPostReaction&&(identical(other.id, id) || other.id == id)&&(identical(other.symbol, symbol) || other.symbol == symbol)&&(identical(other.attitude, attitude) || other.attitude == attitude)&&(identical(other.postId, postId) || other.postId == postId)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.actorId, actorId) || other.actorId == actorId)&&(identical(other.actor, actor) || other.actor == actor)&&(identical(other.accountId, accountId) || other.accountId == accountId)&&(identical(other.account, account) || other.account == account)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,symbol,attitude,postId,accountId,createdAt,updatedAt,account,deletedAt);
int get hashCode => Object.hash(runtimeType,id,symbol,attitude,postId,createdAt,updatedAt,actorId,actor,accountId,account,deletedAt);
@override
String toString() {
return 'SnPostReaction(id: $id, symbol: $symbol, attitude: $attitude, postId: $postId, accountId: $accountId, createdAt: $createdAt, updatedAt: $updatedAt, account: $account, deletedAt: $deletedAt)';
return 'SnPostReaction(id: $id, symbol: $symbol, attitude: $attitude, postId: $postId, createdAt: $createdAt, updatedAt: $updatedAt, actorId: $actorId, actor: $actor, accountId: $accountId, account: $account, deletedAt: $deletedAt)';
}
@@ -1970,11 +2018,11 @@ abstract mixin class $SnPostReactionCopyWith<$Res> {
factory $SnPostReactionCopyWith(SnPostReaction value, $Res Function(SnPostReaction) _then) = _$SnPostReactionCopyWithImpl;
@useResult
$Res call({
String id, String symbol, int attitude, String postId, String accountId, DateTime createdAt, DateTime updatedAt, SnAccount? account, DateTime? deletedAt
String id, String symbol, int attitude, String postId, DateTime createdAt, DateTime updatedAt, String? actorId, SnActivityPubActor? actor, String? accountId, SnAccount? account, DateTime? deletedAt
});
$SnAccountCopyWith<$Res>? get account;
$SnActivityPubActorCopyWith<$Res>? get actor;$SnAccountCopyWith<$Res>? get account;
}
/// @nodoc
@@ -1987,16 +2035,18 @@ class _$SnPostReactionCopyWithImpl<$Res>
/// Create a copy of SnPostReaction
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? symbol = null,Object? attitude = null,Object? postId = null,Object? accountId = null,Object? createdAt = null,Object? updatedAt = null,Object? account = freezed,Object? deletedAt = freezed,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? symbol = null,Object? attitude = null,Object? postId = null,Object? createdAt = null,Object? updatedAt = null,Object? actorId = freezed,Object? actor = freezed,Object? accountId = freezed,Object? account = freezed,Object? deletedAt = freezed,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,symbol: null == symbol ? _self.symbol : symbol // ignore: cast_nullable_to_non_nullable
as String,attitude: null == attitude ? _self.attitude : attitude // ignore: cast_nullable_to_non_nullable
as int,postId: null == postId ? _self.postId : postId // ignore: cast_nullable_to_non_nullable
as String,accountId: null == accountId ? _self.accountId : accountId // ignore: cast_nullable_to_non_nullable
as String,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,account: freezed == account ? _self.account : account // ignore: cast_nullable_to_non_nullable
as DateTime,actorId: freezed == actorId ? _self.actorId : actorId // ignore: cast_nullable_to_non_nullable
as String?,actor: freezed == actor ? _self.actor : actor // ignore: cast_nullable_to_non_nullable
as SnActivityPubActor?,accountId: freezed == accountId ? _self.accountId : accountId // ignore: cast_nullable_to_non_nullable
as String?,account: freezed == account ? _self.account : account // ignore: cast_nullable_to_non_nullable
as SnAccount?,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
@@ -2005,6 +2055,18 @@ as DateTime?,
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnActivityPubActorCopyWith<$Res>? get actor {
if (_self.actor == null) {
return null;
}
return $SnActivityPubActorCopyWith<$Res>(_self.actor!, (value) {
return _then(_self.copyWith(actor: value));
});
}/// Create a copy of SnPostReaction
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnAccountCopyWith<$Res>? get account {
if (_self.account == null) {
return null;
@@ -2092,10 +2154,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String symbol, int attitude, String postId, String accountId, DateTime createdAt, DateTime updatedAt, SnAccount? account, DateTime? deletedAt)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String symbol, int attitude, String postId, DateTime createdAt, DateTime updatedAt, String? actorId, SnActivityPubActor? actor, String? accountId, SnAccount? account, DateTime? deletedAt)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnPostReaction() when $default != null:
return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.accountId,_that.createdAt,_that.updatedAt,_that.account,_that.deletedAt);case _:
return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.createdAt,_that.updatedAt,_that.actorId,_that.actor,_that.accountId,_that.account,_that.deletedAt);case _:
return orElse();
}
@@ -2113,10 +2175,10 @@ return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.accountI
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String symbol, int attitude, String postId, String accountId, DateTime createdAt, DateTime updatedAt, SnAccount? account, DateTime? deletedAt) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String symbol, int attitude, String postId, DateTime createdAt, DateTime updatedAt, String? actorId, SnActivityPubActor? actor, String? accountId, SnAccount? account, DateTime? deletedAt) $default,) {final _that = this;
switch (_that) {
case _SnPostReaction():
return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.accountId,_that.createdAt,_that.updatedAt,_that.account,_that.deletedAt);}
return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.createdAt,_that.updatedAt,_that.actorId,_that.actor,_that.accountId,_that.account,_that.deletedAt);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -2130,10 +2192,10 @@ return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.accountI
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String symbol, int attitude, String postId, String accountId, DateTime createdAt, DateTime updatedAt, SnAccount? account, DateTime? deletedAt)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String symbol, int attitude, String postId, DateTime createdAt, DateTime updatedAt, String? actorId, SnActivityPubActor? actor, String? accountId, SnAccount? account, DateTime? deletedAt)? $default,) {final _that = this;
switch (_that) {
case _SnPostReaction() when $default != null:
return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.accountId,_that.createdAt,_that.updatedAt,_that.account,_that.deletedAt);case _:
return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.createdAt,_that.updatedAt,_that.actorId,_that.actor,_that.accountId,_that.account,_that.deletedAt);case _:
return null;
}
@@ -2145,17 +2207,19 @@ return $default(_that.id,_that.symbol,_that.attitude,_that.postId,_that.accountI
@JsonSerializable()
class _SnPostReaction implements SnPostReaction {
const _SnPostReaction({required this.id, required this.symbol, required this.attitude, required this.postId, required this.accountId, required this.createdAt, required this.updatedAt, this.account = null, this.deletedAt});
const _SnPostReaction({required this.id, required this.symbol, required this.attitude, required this.postId, required this.createdAt, required this.updatedAt, this.actorId, this.actor, this.accountId, this.account, this.deletedAt});
factory _SnPostReaction.fromJson(Map<String, dynamic> json) => _$SnPostReactionFromJson(json);
@override final String id;
@override final String symbol;
@override final int attitude;
@override final String postId;
@override final String accountId;
@override final DateTime createdAt;
@override final DateTime updatedAt;
@override@JsonKey() final SnAccount? account;
@override final String? actorId;
@override final SnActivityPubActor? actor;
@override final String? accountId;
@override final SnAccount? account;
@override final DateTime? deletedAt;
/// Create a copy of SnPostReaction
@@ -2171,16 +2235,16 @@ Map<String, dynamic> toJson() {
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnPostReaction&&(identical(other.id, id) || other.id == id)&&(identical(other.symbol, symbol) || other.symbol == symbol)&&(identical(other.attitude, attitude) || other.attitude == attitude)&&(identical(other.postId, postId) || other.postId == postId)&&(identical(other.accountId, accountId) || other.accountId == accountId)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.account, account) || other.account == account)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnPostReaction&&(identical(other.id, id) || other.id == id)&&(identical(other.symbol, symbol) || other.symbol == symbol)&&(identical(other.attitude, attitude) || other.attitude == attitude)&&(identical(other.postId, postId) || other.postId == postId)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.actorId, actorId) || other.actorId == actorId)&&(identical(other.actor, actor) || other.actor == actor)&&(identical(other.accountId, accountId) || other.accountId == accountId)&&(identical(other.account, account) || other.account == account)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,symbol,attitude,postId,accountId,createdAt,updatedAt,account,deletedAt);
int get hashCode => Object.hash(runtimeType,id,symbol,attitude,postId,createdAt,updatedAt,actorId,actor,accountId,account,deletedAt);
@override
String toString() {
return 'SnPostReaction(id: $id, symbol: $symbol, attitude: $attitude, postId: $postId, accountId: $accountId, createdAt: $createdAt, updatedAt: $updatedAt, account: $account, deletedAt: $deletedAt)';
return 'SnPostReaction(id: $id, symbol: $symbol, attitude: $attitude, postId: $postId, createdAt: $createdAt, updatedAt: $updatedAt, actorId: $actorId, actor: $actor, accountId: $accountId, account: $account, deletedAt: $deletedAt)';
}
@@ -2191,11 +2255,11 @@ abstract mixin class _$SnPostReactionCopyWith<$Res> implements $SnPostReactionCo
factory _$SnPostReactionCopyWith(_SnPostReaction value, $Res Function(_SnPostReaction) _then) = __$SnPostReactionCopyWithImpl;
@override @useResult
$Res call({
String id, String symbol, int attitude, String postId, String accountId, DateTime createdAt, DateTime updatedAt, SnAccount? account, DateTime? deletedAt
String id, String symbol, int attitude, String postId, DateTime createdAt, DateTime updatedAt, String? actorId, SnActivityPubActor? actor, String? accountId, SnAccount? account, DateTime? deletedAt
});
@override $SnAccountCopyWith<$Res>? get account;
@override $SnActivityPubActorCopyWith<$Res>? get actor;@override $SnAccountCopyWith<$Res>? get account;
}
/// @nodoc
@@ -2208,16 +2272,18 @@ class __$SnPostReactionCopyWithImpl<$Res>
/// Create a copy of SnPostReaction
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? symbol = null,Object? attitude = null,Object? postId = null,Object? accountId = null,Object? createdAt = null,Object? updatedAt = null,Object? account = freezed,Object? deletedAt = freezed,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? symbol = null,Object? attitude = null,Object? postId = null,Object? createdAt = null,Object? updatedAt = null,Object? actorId = freezed,Object? actor = freezed,Object? accountId = freezed,Object? account = freezed,Object? deletedAt = freezed,}) {
return _then(_SnPostReaction(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,symbol: null == symbol ? _self.symbol : symbol // ignore: cast_nullable_to_non_nullable
as String,attitude: null == attitude ? _self.attitude : attitude // ignore: cast_nullable_to_non_nullable
as int,postId: null == postId ? _self.postId : postId // ignore: cast_nullable_to_non_nullable
as String,accountId: null == accountId ? _self.accountId : accountId // ignore: cast_nullable_to_non_nullable
as String,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,account: freezed == account ? _self.account : account // ignore: cast_nullable_to_non_nullable
as DateTime,actorId: freezed == actorId ? _self.actorId : actorId // ignore: cast_nullable_to_non_nullable
as String?,actor: freezed == actor ? _self.actor : actor // ignore: cast_nullable_to_non_nullable
as SnActivityPubActor?,accountId: freezed == accountId ? _self.accountId : accountId // ignore: cast_nullable_to_non_nullable
as String?,account: freezed == account ? _self.account : account // ignore: cast_nullable_to_non_nullable
as SnAccount?,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
@@ -2227,6 +2293,18 @@ as DateTime?,
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnActivityPubActorCopyWith<$Res>? get actor {
if (_self.actor == null) {
return null;
}
return $SnActivityPubActorCopyWith<$Res>(_self.actor!, (value) {
return _then(_self.copyWith(actor: value));
});
}/// Create a copy of SnPostReaction
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnAccountCopyWith<$Res>? get account {
if (_self.account == null) {
return null;

View File

@@ -48,12 +48,22 @@ _SnPost _$SnPostFromJson(Map<String, dynamic> json) => _SnPost(
realm: json['realm'] == null
? null
: SnRealm.fromJson(json['realm'] as Map<String, dynamic>),
publisherId: json['publisher_id'] as String?,
publisher: json['publisher'] == null
? null
: SnPublisher.fromJson(json['publisher'] as Map<String, dynamic>),
actorid: json['actorid'] as String?,
actor: json['actor'] == null
? null
: SnActivityPubActor.fromJson(json['actor'] as Map<String, dynamic>),
fediverseUri: json['fediverse_uri'] as String?,
fediverseType: (json['fediverse_type'] as num?)?.toInt(),
contentType: (json['content_type'] as num?)?.toInt() ?? 0,
attachments:
(json['attachments'] as List<dynamic>?)
?.map((e) => SnCloudFile.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
publisher: SnPublisher.fromJson(json['publisher'] as Map<String, dynamic>),
reactionsCount:
(json['reactions_count'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, (e as num).toInt()),
@@ -123,8 +133,14 @@ Map<String, dynamic> _$SnPostToJson(_SnPost instance) => <String, dynamic>{
'forwarded_post': instance.forwardedPost?.toJson(),
'realm_id': instance.realmId,
'realm': instance.realm?.toJson(),
'publisher_id': instance.publisherId,
'publisher': instance.publisher?.toJson(),
'actorid': instance.actorid,
'actor': instance.actor?.toJson(),
'fediverse_uri': instance.fediverseUri,
'fediverse_type': instance.fediverseType,
'content_type': instance.contentType,
'attachments': instance.attachments.map((e) => e.toJson()).toList(),
'publisher': instance.publisher.toJson(),
'reactions_count': instance.reactionsCount,
'reactions_made': instance.reactionsMade,
'reactions': instance.reactions,
@@ -232,9 +248,13 @@ _SnPostReaction _$SnPostReactionFromJson(Map<String, dynamic> json) =>
symbol: json['symbol'] as String,
attitude: (json['attitude'] as num).toInt(),
postId: json['post_id'] as String,
accountId: json['account_id'] as String,
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: DateTime.parse(json['updated_at'] as String),
actorId: json['actor_id'] as String?,
actor: json['actor'] == null
? null
: SnActivityPubActor.fromJson(json['actor'] as Map<String, dynamic>),
accountId: json['account_id'] as String?,
account: json['account'] == null
? null
: SnAccount.fromJson(json['account'] as Map<String, dynamic>),
@@ -249,9 +269,11 @@ Map<String, dynamic> _$SnPostReactionToJson(_SnPostReaction instance) =>
'symbol': instance.symbol,
'attitude': instance.attitude,
'post_id': instance.postId,
'account_id': instance.accountId,
'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt.toIso8601String(),
'actor_id': instance.actorId,
'actor': instance.actor?.toJson(),
'account_id': instance.accountId,
'account': instance.account?.toJson(),
'deleted_at': instance.deletedAt?.toIso8601String(),
};

View File

@@ -16,6 +16,8 @@ import 'package:island/talker.dart';
part 'call.g.dart';
part 'call.freezed.dart';
enum ViewMode { grid, stage }
String formatDuration(Duration duration) {
String negativeSign = duration.isNegative ? '-' : '';
String twoDigits(int n) => n.toString().padLeft(2, "0");
@@ -33,6 +35,7 @@ sealed class CallState with _$CallState {
required bool isScreenSharing,
required bool isSpeakerphone,
@Default(Duration(seconds: 0)) Duration duration,
@Default(ViewMode.grid) ViewMode viewMode,
String? error,
}) = _CallState;
}
@@ -84,6 +87,7 @@ class CallNotifier extends _$CallNotifier {
isCameraEnabled: false,
isScreenSharing: false,
isSpeakerphone: true,
viewMode: ViewMode.grid,
);
}
@@ -241,7 +245,7 @@ class CallNotifier extends _$CallNotifier {
final apiClient = ref.read(apiClientProvider);
final ongoingCall = await ref.read(ongoingCallProvider(roomId).future);
final response = await apiClient.get(
'/sphere/chat/realtime/$roomId/join',
'/messager/chat/realtime/$roomId/join',
);
if (response.statusCode == 200 && response.data != null) {
final data = response.data;
@@ -258,8 +262,8 @@ class CallNotifier extends _$CallNotifier {
duration: Duration(
milliseconds:
(DateTime.now().millisecondsSinceEpoch -
(ongoingCall?.createdAt.millisecondsSinceEpoch ??
DateTime.now().millisecondsSinceEpoch)),
(ongoingCall?.createdAt.millisecondsSinceEpoch ??
DateTime.now().millisecondsSinceEpoch)),
),
);
});
@@ -418,6 +422,14 @@ class CallNotifier extends _$CallNotifier {
return participantsVolumes[live.remoteParticipant.sid] ?? 1;
}
void toggleViewMode() {
state = state.copyWith(
viewMode: state.viewMode == ViewMode.grid
? ViewMode.stage
: ViewMode.grid,
);
}
void dispose() {
state = state.copyWith(
error: null,

View File

@@ -14,7 +14,7 @@ T _$identity<T>(T value) => value;
/// @nodoc
mixin _$CallState implements DiagnosticableTreeMixin {
bool get isConnected; bool get isMicrophoneEnabled; bool get isCameraEnabled; bool get isScreenSharing; bool get isSpeakerphone; Duration get duration; String? get error;
bool get isConnected; bool get isMicrophoneEnabled; bool get isCameraEnabled; bool get isScreenSharing; bool get isSpeakerphone; Duration get duration; ViewMode get viewMode; String? get error;
/// Create a copy of CallState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -26,21 +26,21 @@ $CallStateCopyWith<CallState> get copyWith => _$CallStateCopyWithImpl<CallState>
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'CallState'))
..add(DiagnosticsProperty('isConnected', isConnected))..add(DiagnosticsProperty('isMicrophoneEnabled', isMicrophoneEnabled))..add(DiagnosticsProperty('isCameraEnabled', isCameraEnabled))..add(DiagnosticsProperty('isScreenSharing', isScreenSharing))..add(DiagnosticsProperty('isSpeakerphone', isSpeakerphone))..add(DiagnosticsProperty('duration', duration))..add(DiagnosticsProperty('error', error));
..add(DiagnosticsProperty('isConnected', isConnected))..add(DiagnosticsProperty('isMicrophoneEnabled', isMicrophoneEnabled))..add(DiagnosticsProperty('isCameraEnabled', isCameraEnabled))..add(DiagnosticsProperty('isScreenSharing', isScreenSharing))..add(DiagnosticsProperty('isSpeakerphone', isSpeakerphone))..add(DiagnosticsProperty('duration', duration))..add(DiagnosticsProperty('viewMode', viewMode))..add(DiagnosticsProperty('error', error));
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is CallState&&(identical(other.isConnected, isConnected) || other.isConnected == isConnected)&&(identical(other.isMicrophoneEnabled, isMicrophoneEnabled) || other.isMicrophoneEnabled == isMicrophoneEnabled)&&(identical(other.isCameraEnabled, isCameraEnabled) || other.isCameraEnabled == isCameraEnabled)&&(identical(other.isScreenSharing, isScreenSharing) || other.isScreenSharing == isScreenSharing)&&(identical(other.isSpeakerphone, isSpeakerphone) || other.isSpeakerphone == isSpeakerphone)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.error, error) || other.error == error));
return identical(this, other) || (other.runtimeType == runtimeType&&other is CallState&&(identical(other.isConnected, isConnected) || other.isConnected == isConnected)&&(identical(other.isMicrophoneEnabled, isMicrophoneEnabled) || other.isMicrophoneEnabled == isMicrophoneEnabled)&&(identical(other.isCameraEnabled, isCameraEnabled) || other.isCameraEnabled == isCameraEnabled)&&(identical(other.isScreenSharing, isScreenSharing) || other.isScreenSharing == isScreenSharing)&&(identical(other.isSpeakerphone, isSpeakerphone) || other.isSpeakerphone == isSpeakerphone)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.viewMode, viewMode) || other.viewMode == viewMode)&&(identical(other.error, error) || other.error == error));
}
@override
int get hashCode => Object.hash(runtimeType,isConnected,isMicrophoneEnabled,isCameraEnabled,isScreenSharing,isSpeakerphone,duration,error);
int get hashCode => Object.hash(runtimeType,isConnected,isMicrophoneEnabled,isCameraEnabled,isScreenSharing,isSpeakerphone,duration,viewMode,error);
@override
String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
return 'CallState(isConnected: $isConnected, isMicrophoneEnabled: $isMicrophoneEnabled, isCameraEnabled: $isCameraEnabled, isScreenSharing: $isScreenSharing, isSpeakerphone: $isSpeakerphone, duration: $duration, error: $error)';
return 'CallState(isConnected: $isConnected, isMicrophoneEnabled: $isMicrophoneEnabled, isCameraEnabled: $isCameraEnabled, isScreenSharing: $isScreenSharing, isSpeakerphone: $isSpeakerphone, duration: $duration, viewMode: $viewMode, error: $error)';
}
@@ -51,7 +51,7 @@ abstract mixin class $CallStateCopyWith<$Res> {
factory $CallStateCopyWith(CallState value, $Res Function(CallState) _then) = _$CallStateCopyWithImpl;
@useResult
$Res call({
bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, String? error
bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, ViewMode viewMode, String? error
});
@@ -68,7 +68,7 @@ class _$CallStateCopyWithImpl<$Res>
/// Create a copy of CallState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? isConnected = null,Object? isMicrophoneEnabled = null,Object? isCameraEnabled = null,Object? isScreenSharing = null,Object? isSpeakerphone = null,Object? duration = null,Object? error = freezed,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? isConnected = null,Object? isMicrophoneEnabled = null,Object? isCameraEnabled = null,Object? isScreenSharing = null,Object? isSpeakerphone = null,Object? duration = null,Object? viewMode = null,Object? error = freezed,}) {
return _then(_self.copyWith(
isConnected: null == isConnected ? _self.isConnected : isConnected // ignore: cast_nullable_to_non_nullable
as bool,isMicrophoneEnabled: null == isMicrophoneEnabled ? _self.isMicrophoneEnabled : isMicrophoneEnabled // ignore: cast_nullable_to_non_nullable
@@ -76,7 +76,8 @@ as bool,isCameraEnabled: null == isCameraEnabled ? _self.isCameraEnabled : isCam
as bool,isScreenSharing: null == isScreenSharing ? _self.isScreenSharing : isScreenSharing // ignore: cast_nullable_to_non_nullable
as bool,isSpeakerphone: null == isSpeakerphone ? _self.isSpeakerphone : isSpeakerphone // ignore: cast_nullable_to_non_nullable
as bool,duration: null == duration ? _self.duration : duration // ignore: cast_nullable_to_non_nullable
as Duration,error: freezed == error ? _self.error : error // ignore: cast_nullable_to_non_nullable
as Duration,viewMode: null == viewMode ? _self.viewMode : viewMode // ignore: cast_nullable_to_non_nullable
as ViewMode,error: freezed == error ? _self.error : error // ignore: cast_nullable_to_non_nullable
as String?,
));
}
@@ -159,10 +160,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, String? error)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, ViewMode viewMode, String? error)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _CallState() when $default != null:
return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnabled,_that.isScreenSharing,_that.isSpeakerphone,_that.duration,_that.error);case _:
return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnabled,_that.isScreenSharing,_that.isSpeakerphone,_that.duration,_that.viewMode,_that.error);case _:
return orElse();
}
@@ -180,10 +181,10 @@ return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnable
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, String? error) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, ViewMode viewMode, String? error) $default,) {final _that = this;
switch (_that) {
case _CallState():
return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnabled,_that.isScreenSharing,_that.isSpeakerphone,_that.duration,_that.error);}
return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnabled,_that.isScreenSharing,_that.isSpeakerphone,_that.duration,_that.viewMode,_that.error);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -197,10 +198,10 @@ return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnable
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, String? error)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, ViewMode viewMode, String? error)? $default,) {final _that = this;
switch (_that) {
case _CallState() when $default != null:
return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnabled,_that.isScreenSharing,_that.isSpeakerphone,_that.duration,_that.error);case _:
return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnabled,_that.isScreenSharing,_that.isSpeakerphone,_that.duration,_that.viewMode,_that.error);case _:
return null;
}
@@ -212,7 +213,7 @@ return $default(_that.isConnected,_that.isMicrophoneEnabled,_that.isCameraEnable
class _CallState with DiagnosticableTreeMixin implements CallState {
const _CallState({required this.isConnected, required this.isMicrophoneEnabled, required this.isCameraEnabled, required this.isScreenSharing, required this.isSpeakerphone, this.duration = const Duration(seconds: 0), this.error});
const _CallState({required this.isConnected, required this.isMicrophoneEnabled, required this.isCameraEnabled, required this.isScreenSharing, required this.isSpeakerphone, this.duration = const Duration(seconds: 0), this.viewMode = ViewMode.grid, this.error});
@override final bool isConnected;
@@ -221,6 +222,7 @@ class _CallState with DiagnosticableTreeMixin implements CallState {
@override final bool isScreenSharing;
@override final bool isSpeakerphone;
@override@JsonKey() final Duration duration;
@override@JsonKey() final ViewMode viewMode;
@override final String? error;
/// Create a copy of CallState
@@ -234,21 +236,21 @@ _$CallStateCopyWith<_CallState> get copyWith => __$CallStateCopyWithImpl<_CallSt
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'CallState'))
..add(DiagnosticsProperty('isConnected', isConnected))..add(DiagnosticsProperty('isMicrophoneEnabled', isMicrophoneEnabled))..add(DiagnosticsProperty('isCameraEnabled', isCameraEnabled))..add(DiagnosticsProperty('isScreenSharing', isScreenSharing))..add(DiagnosticsProperty('isSpeakerphone', isSpeakerphone))..add(DiagnosticsProperty('duration', duration))..add(DiagnosticsProperty('error', error));
..add(DiagnosticsProperty('isConnected', isConnected))..add(DiagnosticsProperty('isMicrophoneEnabled', isMicrophoneEnabled))..add(DiagnosticsProperty('isCameraEnabled', isCameraEnabled))..add(DiagnosticsProperty('isScreenSharing', isScreenSharing))..add(DiagnosticsProperty('isSpeakerphone', isSpeakerphone))..add(DiagnosticsProperty('duration', duration))..add(DiagnosticsProperty('viewMode', viewMode))..add(DiagnosticsProperty('error', error));
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _CallState&&(identical(other.isConnected, isConnected) || other.isConnected == isConnected)&&(identical(other.isMicrophoneEnabled, isMicrophoneEnabled) || other.isMicrophoneEnabled == isMicrophoneEnabled)&&(identical(other.isCameraEnabled, isCameraEnabled) || other.isCameraEnabled == isCameraEnabled)&&(identical(other.isScreenSharing, isScreenSharing) || other.isScreenSharing == isScreenSharing)&&(identical(other.isSpeakerphone, isSpeakerphone) || other.isSpeakerphone == isSpeakerphone)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.error, error) || other.error == error));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _CallState&&(identical(other.isConnected, isConnected) || other.isConnected == isConnected)&&(identical(other.isMicrophoneEnabled, isMicrophoneEnabled) || other.isMicrophoneEnabled == isMicrophoneEnabled)&&(identical(other.isCameraEnabled, isCameraEnabled) || other.isCameraEnabled == isCameraEnabled)&&(identical(other.isScreenSharing, isScreenSharing) || other.isScreenSharing == isScreenSharing)&&(identical(other.isSpeakerphone, isSpeakerphone) || other.isSpeakerphone == isSpeakerphone)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.viewMode, viewMode) || other.viewMode == viewMode)&&(identical(other.error, error) || other.error == error));
}
@override
int get hashCode => Object.hash(runtimeType,isConnected,isMicrophoneEnabled,isCameraEnabled,isScreenSharing,isSpeakerphone,duration,error);
int get hashCode => Object.hash(runtimeType,isConnected,isMicrophoneEnabled,isCameraEnabled,isScreenSharing,isSpeakerphone,duration,viewMode,error);
@override
String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
return 'CallState(isConnected: $isConnected, isMicrophoneEnabled: $isMicrophoneEnabled, isCameraEnabled: $isCameraEnabled, isScreenSharing: $isScreenSharing, isSpeakerphone: $isSpeakerphone, duration: $duration, error: $error)';
return 'CallState(isConnected: $isConnected, isMicrophoneEnabled: $isMicrophoneEnabled, isCameraEnabled: $isCameraEnabled, isScreenSharing: $isScreenSharing, isSpeakerphone: $isSpeakerphone, duration: $duration, viewMode: $viewMode, error: $error)';
}
@@ -259,7 +261,7 @@ abstract mixin class _$CallStateCopyWith<$Res> implements $CallStateCopyWith<$Re
factory _$CallStateCopyWith(_CallState value, $Res Function(_CallState) _then) = __$CallStateCopyWithImpl;
@override @useResult
$Res call({
bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, String? error
bool isConnected, bool isMicrophoneEnabled, bool isCameraEnabled, bool isScreenSharing, bool isSpeakerphone, Duration duration, ViewMode viewMode, String? error
});
@@ -276,7 +278,7 @@ class __$CallStateCopyWithImpl<$Res>
/// Create a copy of CallState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? isConnected = null,Object? isMicrophoneEnabled = null,Object? isCameraEnabled = null,Object? isScreenSharing = null,Object? isSpeakerphone = null,Object? duration = null,Object? error = freezed,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? isConnected = null,Object? isMicrophoneEnabled = null,Object? isCameraEnabled = null,Object? isScreenSharing = null,Object? isSpeakerphone = null,Object? duration = null,Object? viewMode = null,Object? error = freezed,}) {
return _then(_CallState(
isConnected: null == isConnected ? _self.isConnected : isConnected // ignore: cast_nullable_to_non_nullable
as bool,isMicrophoneEnabled: null == isMicrophoneEnabled ? _self.isMicrophoneEnabled : isMicrophoneEnabled // ignore: cast_nullable_to_non_nullable
@@ -284,7 +286,8 @@ as bool,isCameraEnabled: null == isCameraEnabled ? _self.isCameraEnabled : isCam
as bool,isScreenSharing: null == isScreenSharing ? _self.isScreenSharing : isScreenSharing // ignore: cast_nullable_to_non_nullable
as bool,isSpeakerphone: null == isSpeakerphone ? _self.isSpeakerphone : isSpeakerphone // ignore: cast_nullable_to_non_nullable
as bool,duration: null == duration ? _self.duration : duration // ignore: cast_nullable_to_non_nullable
as Duration,error: freezed == error ? _self.error : error // ignore: cast_nullable_to_non_nullable
as Duration,viewMode: null == viewMode ? _self.viewMode : viewMode // ignore: cast_nullable_to_non_nullable
as ViewMode,error: freezed == error ? _self.error : error // ignore: cast_nullable_to_non_nullable
as String?,
));
}

View File

@@ -41,7 +41,7 @@ final class CallNotifierProvider
}
}
String _$callNotifierHash() => r'ef4e3e9c9d411cf9dce1ceb456a3b866b2c87db3';
String _$callNotifierHash() => r'caa03913d98c6d98448af44059db5ef72b5d58f6';
abstract class _$CallNotifier extends $Notifier<CallState> {
CallState build();

View File

@@ -15,7 +15,7 @@ class ChatOnlineCountNotifier extends _$ChatOnlineCountNotifier {
// Fetch initial online count
final response = await apiClient.get(
'/sphere/chat/$chatroomId/members/online',
'/messager/chat/$chatroomId/members/online',
);
final initialCount = response.data as int;

View File

@@ -52,7 +52,7 @@ final class ChatOnlineCountNotifierProvider
}
String _$chatOnlineCountNotifierHash() =>
r'19af8fd0e9f62c65e12a68215406776085235fa3';
r'b2f9f17bfece1937ec90590b8f11db2bec923156';
final class ChatOnlineCountNotifierFamily extends $Family
with

View File

@@ -105,7 +105,7 @@ class ChatRoomJoinedNotifier extends _$ChatRoomJoinedNotifier {
Future(() async {
try {
final client = ref.read(apiClientProvider);
final resp = await client.get('/sphere/chat');
final resp = await client.get('/messager/chat');
final remoteRooms = resp.data
.map((e) => SnChatRoom.fromJson(e))
.cast<SnChatRoom>()
@@ -122,7 +122,7 @@ class ChatRoomJoinedNotifier extends _$ChatRoomJoinedNotifier {
// Fallback to API
final client = ref.watch(apiClientProvider);
final resp = await client.get('/sphere/chat');
final resp = await client.get('/messager/chat');
final rooms = resp.data
.map((e) => SnChatRoom.fromJson(e))
.cast<SnChatRoom>()
@@ -306,7 +306,7 @@ class ChatRoomNotifier extends _$ChatRoomNotifier {
Future(() async {
try {
final client = ref.read(apiClientProvider);
final resp = await client.get('/sphere/chat/$identifier');
final resp = await client.get('/messager/chat/$identifier');
final remoteRoom = SnChatRoom.fromJson(resp.data);
// Update state with fresh data directly without saving to DB
// DB will be updated by ChatRoomJoinedNotifier's full sync
@@ -321,7 +321,7 @@ class ChatRoomNotifier extends _$ChatRoomNotifier {
// Fallback to API
try {
final client = ref.watch(apiClientProvider);
final resp = await client.get('/sphere/chat/$identifier');
final resp = await client.get('/messager/chat/$identifier');
final room = SnChatRoom.fromJson(resp.data);
await db.saveChatRooms([room]);
return room;
@@ -375,7 +375,7 @@ class ChatRoomIdentityNotifier extends _$ChatRoomIdentityNotifier {
try {
final client = ref.read(apiClientProvider);
final resp = await client.get(
'/sphere/chat/$identifier/members/me',
'/messager/chat/$identifier/members/me',
);
final remoteMember = SnChatMember.fromJson(resp.data);
await db.saveMember(remoteMember);
@@ -396,7 +396,7 @@ class ChatRoomIdentityNotifier extends _$ChatRoomIdentityNotifier {
// Fallback to API
try {
final client = ref.watch(apiClientProvider);
final resp = await client.get('/sphere/chat/$identifier/members/me');
final resp = await client.get('/messager/chat/$identifier/members/me');
final member = SnChatMember.fromJson(resp.data);
await db.saveMember(member);
return member;
@@ -444,7 +444,7 @@ class ChatRoomIdentityNotifier extends _$ChatRoomIdentityNotifier {
@riverpod
Future<List<SnChatMember>> chatroomInvites(Ref ref) async {
final client = ref.watch(apiClientProvider);
final resp = await client.get('/sphere/chat/invites');
final resp = await client.get('/messager/chat/invites');
return resp.data
.map((e) => SnChatMember.fromJson(e))
.cast<SnChatMember>()

View File

@@ -34,7 +34,7 @@ final class ChatRoomJoinedNotifierProvider
}
String _$chatRoomJoinedNotifierHash() =>
r'e69955be56ef2c04a8062a8a65925e0a23bfcbaa';
r'b3726e10298b99a8529c5e28a5c402b95016f096';
abstract class _$ChatRoomJoinedNotifier
extends $AsyncNotifier<List<SnChatRoom>> {
@@ -98,7 +98,7 @@ final class ChatRoomNotifierProvider
}
}
String _$chatRoomNotifierHash() => r'1e6391e2ab4eeb114fa001aaa6b06ab2bd646f38';
String _$chatRoomNotifierHash() => r'9f7a8bdd4af381c6b60e65e74363a0af3c1a650e';
final class ChatRoomNotifierFamily extends $Family
with
@@ -190,7 +190,7 @@ final class ChatRoomIdentityNotifierProvider
}
String _$chatRoomIdentityNotifierHash() =>
r'27c17d55366d39be81d7209837e5c01f80a68a24';
r'1ce75462a19cc037c97ee6084a30fee1f5335875';
final class ChatRoomIdentityNotifierFamily extends $Family
with
@@ -279,4 +279,4 @@ final class ChatroomInvitesProvider
}
}
String _$chatroomInvitesHash() => r'5cd6391b09c5517ede19bacce43b45c8d71dd087';
String _$chatroomInvitesHash() => r'fc23231d5f111b1c3796ffae2b471384b951861a';

View File

@@ -61,7 +61,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.subscribe',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);
@@ -98,7 +98,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.subscribe',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);
@@ -116,7 +116,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.unsubscribe',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);
@@ -128,7 +128,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.subscribe',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);
@@ -143,7 +143,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.unsubscribe',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);
@@ -207,7 +207,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.read',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);
@@ -224,7 +224,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
WebSocketPacket(
type: 'messages.typing',
data: {'chat_room_id': roomId},
endpoint: 'sphere',
endpoint: 'messager',
),
),
);

View File

@@ -59,7 +59,7 @@ final class ChatSubscribeNotifierProvider
}
String _$chatSubscribeNotifierHash() =>
r'1aa164429aaab1628b5edbae11e33b0860abdcdc';
r'a05739450e6d23eb3d8c0a96078887b2b58ffd10';
final class ChatSubscribeNotifierFamily extends $Family
with

View File

@@ -24,7 +24,7 @@ class ChatUnreadCountNotifier extends _$ChatUnreadCountNotifier {
try {
final client = ref.read(apiClientProvider);
final response = await client.get('/sphere/chat/unread');
final response = await client.get('/messager/chat/unread');
return (response.data as num).toInt();
} catch (_) {
return 0;
@@ -65,7 +65,7 @@ class ChatSummary extends _$ChatSummary {
@override
Future<Map<String, SnChatSummary>> build() async {
final client = ref.watch(apiClientProvider);
final resp = await client.get('/sphere/chat/summary');
final resp = await client.get('/messager/chat/summary');
final Map<String, dynamic> data = resp.data;
final summaries = data.map(

View File

@@ -34,7 +34,7 @@ final class ChatUnreadCountNotifierProvider
}
String _$chatUnreadCountNotifierHash() =>
r'b8d93589dc37f772d4c3a07d9afd81c37026e57d';
r'169b28f8759ebd9de75f7de17f60d493737ee7a8';
abstract class _$ChatUnreadCountNotifier extends $AsyncNotifier<int> {
FutureOr<int> build();
@@ -79,7 +79,7 @@ final class ChatSummaryProvider
ChatSummary create() => ChatSummary();
}
String _$chatSummaryHash() => r'dfa5e487586482ebdafef8d711f74db68ee86f84';
String _$chatSummaryHash() => r'82f516d4ce8b67dadb815523df57a3c30a33ef91';
abstract class _$ChatSummary
extends $AsyncNotifier<Map<String, SnChatSummary>> {

View File

@@ -24,6 +24,8 @@ import "package:island/screens/account/profile.dart";
part 'messages_notifier.g.dart';
const Set<String> kSilentMessageTypes = {'messages.update.links'};
@riverpod
class MessagesNotifier extends _$MessagesNotifier {
late Dio _apiClient;
@@ -48,6 +50,9 @@ class MessagesNotifier extends _$MessagesNotifier {
late Future<SnAccount?> Function(String) _fetchAccount;
// Disposal handling
bool _disposed = false;
@override
FutureOr<List<LocalChatMessage>> build(String roomId) async {
_apiClient = ref.watch(apiClientProvider);
@@ -76,10 +81,17 @@ class MessagesNotifier extends _$MessagesNotifier {
talker.log('MessagesNotifier built for room $roomId');
// Set up disposal handling
ref.onDispose(() {
_disposed = true;
talker.log('MessagesNotifier disposed for room $roomId');
});
// Only setup sync and lifecycle listeners if user is a member
if (identity != null) {
ref.listen(appLifecycleStateProvider, (_, next) {
next.whenData((state) {
if (_disposed) return; // Check disposal before accessing ref
if (state == AppLifecycleState.paused) {
_lastPauseTime = DateTime.now();
talker.log('App paused, recording time');
@@ -88,7 +100,9 @@ class MessagesNotifier extends _$MessagesNotifier {
final diff = DateTime.now().difference(_lastPauseTime!);
if (diff > const Duration(minutes: 1)) {
talker.log('App resumed after >1 min, syncing messages');
syncMessages();
if (!_disposed) {
syncMessages(); // Check disposal before calling syncMessages
}
} else {
talker.log('App resumed within 1 min, skipping sync');
}
@@ -167,15 +181,15 @@ class MessagesNotifier extends _$MessagesNotifier {
List<LocalChatMessage> filteredMessages = dbMessages;
if (withLinks == true) {
filteredMessages =
filteredMessages.where((msg) => _hasLink(msg)).toList();
filteredMessages = filteredMessages
.where((msg) => _hasLink(msg))
.toList();
}
if (withAttachments == true) {
filteredMessages =
filteredMessages
.where((msg) => msg.toRemoteMessage().attachments.isNotEmpty)
.toList();
filteredMessages = filteredMessages
.where((msg) => msg.toRemoteMessage().attachments.isNotEmpty)
.toList();
}
final dbLocalMessages = filteredMessages;
@@ -190,8 +204,9 @@ class MessagesNotifier extends _$MessagesNotifier {
}
if (offset == 0) {
final pendingForRoom =
_pendingMessages.values.where((msg) => msg.roomId == roomId).toList();
final pendingForRoom = _pendingMessages.values
.where((msg) => msg.roomId == roomId)
.toList();
final allMessages = [...pendingForRoom, ...uniqueMessages];
_sortMessages(allMessages); // Use the helper function
@@ -239,8 +254,9 @@ class MessagesNotifier extends _$MessagesNotifier {
}
if (offset == 0) {
final pendingForRoom =
_pendingMessages.values.where((msg) => msg.roomId == roomId).toList();
final pendingForRoom = _pendingMessages.values
.where((msg) => msg.roomId == roomId)
.toList();
final allMessages = [...pendingForRoom, ...uniqueMessages];
_sortMessages(allMessages);
@@ -265,7 +281,7 @@ class MessagesNotifier extends _$MessagesNotifier {
talker.log('Fetching messages from API, offset $offset, take $take');
if (_totalCount == null) {
final response = await _apiClient.get(
'/sphere/chat/$roomId/messages',
'/messager/chat/$roomId/messages',
queryParameters: {'offset': 0, 'take': 1},
);
_totalCount = int.parse(response.headers['x-total']?.firstOrNull ?? '0');
@@ -277,21 +293,20 @@ class MessagesNotifier extends _$MessagesNotifier {
}
final response = await _apiClient.get(
'/sphere/chat/$roomId/messages',
'/messager/chat/$roomId/messages',
queryParameters: {'offset': offset, 'take': take},
);
final List<dynamic> data = response.data;
_totalCount = int.parse(response.headers['x-total']?.firstOrNull ?? '0');
final messages =
data.map((json) {
final remoteMessage = SnChatMessage.fromJson(json);
return LocalChatMessage.fromRemoteMessage(
remoteMessage,
MessageStatus.sent,
);
}).toList();
final messages = data.map((json) {
final remoteMessage = SnChatMessage.fromJson(json);
return LocalChatMessage.fromRemoteMessage(
remoteMessage,
MessageStatus.sent,
);
}).toList();
for (final message in messages) {
await _database.saveMessageWithSender(message);
@@ -319,20 +334,24 @@ class MessagesNotifier extends _$MessagesNotifier {
_allRemoteMessagesFetched = false;
talker.log('Starting message sync');
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(true));
// Use Future.microtask to set syncing state, but check disposal to avoid errors
Future.microtask(() {
if (!_disposed) {
ref.read(chatSyncingProvider.notifier).set(true);
}
});
try {
final dbMessages = await _database.getMessagesForRoom(
_room.id,
offset: 0,
limit: 1,
);
final lastMessage =
dbMessages.isEmpty
? null
: await _database.companionToMessage(
dbMessages.first,
fetchAccount: _fetchAccount,
);
final lastMessage = dbMessages.isEmpty
? null
: await _database.companionToMessage(
dbMessages.first,
fetchAccount: _fetchAccount,
);
if (lastMessage == null) {
talker.log('No local messages, fetching from network');
@@ -347,12 +366,14 @@ class MessagesNotifier extends _$MessagesNotifier {
// Sync with pagination support using timestamp-based cursor
int? totalMessages;
int syncedCount = 0;
int lastSyncTimestamp =
lastMessage.toRemoteMessage().updatedAt.millisecondsSinceEpoch;
int lastSyncTimestamp = lastMessage
.toRemoteMessage()
.updatedAt
.millisecondsSinceEpoch;
do {
final resp = await _apiClient.post(
'/sphere/chat/${_room.id}/sync',
'/messager/chat/${_room.id}/sync',
data: {'last_sync_timestamp': lastSyncTimestamp},
);
@@ -395,6 +416,7 @@ class MessagesNotifier extends _$MessagesNotifier {
showErrorAlert(err);
} finally {
talker.log('Finished message sync');
// Always reset global syncing state, regardless of disposal
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(false));
_isSyncing = false;
}
@@ -492,7 +514,9 @@ class MessagesNotifier extends _$MessagesNotifier {
if (!_hasMore || state is AsyncLoading) return;
talker.log('Loading more messages');
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(true));
if (!_disposed) {
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(true));
}
try {
final currentMessages = state.value ?? [];
final offset = currentMessages.length;
@@ -515,6 +539,7 @@ class MessagesNotifier extends _$MessagesNotifier {
);
showErrorAlert(err);
} finally {
// Always reset global syncing state, regardless of disposal
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(false));
}
}
@@ -559,18 +584,17 @@ class MessagesNotifier extends _$MessagesNotifier {
try {
var cloudAttachments = List.empty(growable: true);
for (var idx = 0; idx < attachments.length; idx++) {
final cloudFile =
await FileUploader.createCloudFile(
ref: ref,
fileData: attachments[idx],
onProgress: (progress, _) {
_fileUploadProgress[localMessage.id]?[idx] = progress ?? 0.0;
onProgress?.call(
localMessage.id,
_fileUploadProgress[localMessage.id] ?? {},
);
},
).future;
final cloudFile = await FileUploader.createCloudFile(
ref: ref,
fileData: attachments[idx],
onProgress: (progress, _) {
_fileUploadProgress[localMessage.id]?[idx] = progress ?? 0.0;
onProgress?.call(
localMessage.id,
_fileUploadProgress[localMessage.id] ?? {},
);
},
).future;
if (cloudFile == null) {
throw ArgumentError('Failed to upload the file...');
}
@@ -579,8 +603,8 @@ class MessagesNotifier extends _$MessagesNotifier {
final response = await _apiClient.request(
editingTo == null
? '/sphere/chat/$roomId/messages'
: '/sphere/chat/$roomId/messages/${editingTo.id}',
? '/messager/chat/$roomId/messages'
: '/messager/chat/$roomId/messages/${editingTo.id}',
data: {
'content': content,
'attachments_id': cloudAttachments.map((e) => e.id).toList(),
@@ -606,22 +630,20 @@ class MessagesNotifier extends _$MessagesNotifier {
final currentMessages = state.value ?? [];
if (editingTo != null) {
final newMessages =
currentMessages
.where((m) => m.id != localMessage.id) // remove pending message
.map(
(m) => m.id == editingTo.id ? updatedMessage : m,
) // update original message
.toList();
final newMessages = currentMessages
.where((m) => m.id != localMessage.id) // remove pending message
.map(
(m) => m.id == editingTo.id ? updatedMessage : m,
) // update original message
.toList();
state = AsyncValue.data(newMessages);
} else {
final newMessages =
currentMessages.map((m) {
if (m.id == localMessage.id) {
return updatedMessage;
}
return m;
}).toList();
final newMessages = currentMessages.map((m) {
if (m.id == localMessage.id) {
return updatedMessage;
}
return m;
}).toList();
state = AsyncValue.data(newMessages);
}
talker.log('Message with nonce $nonce sent successfully');
@@ -638,13 +660,12 @@ class MessagesNotifier extends _$MessagesNotifier {
localMessage.id,
MessageStatus.failed,
);
final newMessages =
(state.value ?? []).map((m) {
if (m.id == localMessage.id) {
return m..status = MessageStatus.failed;
}
return m;
}).toList();
final newMessages = (state.value ?? []).map((m) {
if (m.id == localMessage.id) {
return m..status = MessageStatus.failed;
}
return m;
}).toList();
state = AsyncValue.data(newMessages);
showErrorAlert(e);
}
@@ -667,7 +688,7 @@ class MessagesNotifier extends _$MessagesNotifier {
try {
var remoteMessage = message.toRemoteMessage();
final response = await _apiClient.post(
'/sphere/chat/${message.roomId}/messages',
'/messager/chat/${message.roomId}/messages',
data: {
'content': remoteMessage.content,
'attachments_id': remoteMessage.attachments,
@@ -686,13 +707,12 @@ class MessagesNotifier extends _$MessagesNotifier {
await _database.deleteMessage(pendingMessageId);
await _database.saveMessageWithSender(updatedMessage);
final newMessages =
(state.value ?? []).map((m) {
if (m.id == pendingMessageId) {
return updatedMessage;
}
return m;
}).toList();
final newMessages = (state.value ?? []).map((m) {
if (m.id == pendingMessageId) {
return updatedMessage;
}
return m;
}).toList();
state = AsyncValue.data(newMessages);
} catch (e, stackTrace) {
talker.log(
@@ -707,13 +727,12 @@ class MessagesNotifier extends _$MessagesNotifier {
pendingMessageId,
MessageStatus.failed,
);
final newMessages =
(state.value ?? []).map((m) {
if (m.id == pendingMessageId) {
return m..status = MessageStatus.failed;
}
return m;
}).toList();
final newMessages = (state.value ?? []).map((m) {
if (m.id == pendingMessageId) {
return m..status = MessageStatus.failed;
}
return m;
}).toList();
state = AsyncValue.data(_sortMessages(newMessages));
showErrorAlert(e);
}
@@ -730,6 +749,8 @@ class MessagesNotifier extends _$MessagesNotifier {
talker.log('Received new message ${remoteMessage.id}');
final isSilentMessage = kSilentMessageTypes.contains(remoteMessage.type);
final localMessage = LocalChatMessage.fromRemoteMessage(
remoteMessage,
MessageStatus.sent,
@@ -741,23 +762,25 @@ class MessagesNotifier extends _$MessagesNotifier {
);
}
await _database.saveMessageWithSender(localMessage);
if (!isSilentMessage) {
await _database.saveMessageWithSender(localMessage);
final currentMessages = state.value ?? [];
final existingIndex = currentMessages.indexWhere(
(m) =>
m.id == localMessage.id ||
(localMessage.nonce != null && m.nonce == localMessage.nonce),
);
if (existingIndex >= 0) {
final newList = [...currentMessages];
newList[existingIndex] = localMessage;
state = AsyncValue.data(_sortMessages(newList));
} else {
state = AsyncValue.data(
_sortMessages([localMessage, ...currentMessages]),
final currentMessages = state.value ?? [];
final existingIndex = currentMessages.indexWhere(
(m) =>
m.id == localMessage.id ||
(localMessage.nonce != null && m.nonce == localMessage.nonce),
);
if (existingIndex >= 0) {
final newList = [...currentMessages];
newList[existingIndex] = localMessage;
state = AsyncValue.data(_sortMessages(newList));
} else {
state = AsyncValue.data(
_sortMessages([localMessage, ...currentMessages]),
);
}
}
switch (remoteMessage.type) {
@@ -783,15 +806,44 @@ class MessagesNotifier extends _$MessagesNotifier {
talker.log('Received message update ${remoteMessage.id}');
final targetId = remoteMessage.meta['message_id'] ?? remoteMessage.id;
final updatedMessage = LocalChatMessage.fromRemoteMessage(
remoteMessage.copyWith(
id: targetId,
meta: Map.of(remoteMessage.meta)..remove('message_id'),
type: 'text',
LocalChatMessage updatedMessage;
if (remoteMessage.type == 'messages.update.links') {
// For link updates, merge meta with existing message instead of creating new one
final existingMessage = await fetchMessageById(targetId);
if (existingMessage == null) {
talker.log('Cannot update links for non-existent message $targetId');
return;
}
final existingRemote = existingMessage.toRemoteMessage();
final mergedMeta = Map<String, dynamic>.of(existingRemote.meta);
mergedMeta.addAll(remoteMessage.meta);
mergedMeta.remove('message_id'); // Remove the target message ID from meta
final updatedRemote = existingRemote.copyWith(
meta: mergedMeta,
editedAt: remoteMessage.createdAt,
),
MessageStatus.sent,
);
);
updatedMessage = LocalChatMessage.fromRemoteMessage(
updatedRemote,
existingMessage.status,
);
} else {
// For regular updates, create new message as before
updatedMessage = LocalChatMessage.fromRemoteMessage(
remoteMessage.copyWith(
id: targetId,
meta: Map.of(remoteMessage.meta)..remove('message_id'),
type: 'text',
editedAt: remoteMessage.createdAt,
),
MessageStatus.sent,
);
}
await _database.updateMessage(_database.messageToCompanion(updatedMessage));
final currentMessages = state.value ?? [];
@@ -865,14 +917,15 @@ class MessagesNotifier extends _$MessagesNotifier {
await _database.deleteMessage(messageId);
final currentMessages = state.value ?? [];
final newMessages =
currentMessages.where((m) => m.id != messageId).toList();
final newMessages = currentMessages
.where((m) => m.id != messageId)
.toList();
state = AsyncValue.data(newMessages);
return;
}
try {
await _apiClient.delete('/sphere/chat/$roomId/messages/$messageId');
await _apiClient.delete('/messager/chat/$roomId/messages/$messageId');
await receiveMessageDeletion(messageId);
} catch (err, stackTrace) {
talker.log(
@@ -969,9 +1022,9 @@ class MessagesNotifier extends _$MessagesNotifier {
Future<LocalChatMessage?> fetchMessageById(String messageId) async {
talker.log('Fetching message by id $messageId');
try {
final localMessage =
await (_database.select(_database.chatMessages)
..where((tbl) => tbl.id.equals(messageId))).getSingleOrNull();
final localMessage = await (_database.select(
_database.chatMessages,
)..where((tbl) => tbl.id.equals(messageId))).getSingleOrNull();
if (localMessage != null) {
return _database.companionToMessage(
localMessage,
@@ -980,7 +1033,7 @@ class MessagesNotifier extends _$MessagesNotifier {
}
final response = await _apiClient.get(
'/sphere/chat/$roomId/messages/$messageId',
'/messager/chat/$roomId/messages/$messageId',
);
final remoteMessage = SnChatMessage.fromJson(response.data);
final message = LocalChatMessage.fromRemoteMessage(
@@ -1005,7 +1058,9 @@ class MessagesNotifier extends _$MessagesNotifier {
_isJumping = true;
// Clear flashing messages when starting a new jump
ref.read(flashingMessagesProvider.notifier).state = {};
if (!_disposed) {
ref.read(flashingMessagesProvider.notifier).state = {};
}
try {
talker.log('Fetching message $messageId');
@@ -1047,8 +1102,9 @@ class MessagesNotifier extends _$MessagesNotifier {
// Calculate offset to position target message in the middle of the loaded chunk
const chunkSize = 100; // Load 100 messages around the target
final offset =
(newerCount - chunkSize ~/ 2).clamp(0, double.infinity).toInt();
final offset = (newerCount - chunkSize ~/ 2)
.clamp(0, double.infinity)
.toInt();
talker.log(
'Calculated offset $offset for target message (newer: $newerCount, chunk: $chunkSize)',
);
@@ -1060,8 +1116,9 @@ class MessagesNotifier extends _$MessagesNotifier {
// Check if loaded messages are already in current state
final currentIds = currentMessages.map((m) => m.id).toSet();
final newMessages =
loadedMessages.where((m) => !currentIds.contains(m.id)).toList();
final newMessages = loadedMessages
.where((m) => !currentIds.contains(m.id))
.toList();
talker.log(
'Loaded ${loadedMessages.length} messages, ${newMessages.length} are new',
);

View File

@@ -50,7 +50,7 @@ final class MessagesNotifierProvider
}
}
String _$messagesNotifierHash() => r'2f3f19cb99357184e82d66e74a31863fcfc48856';
String _$messagesNotifierHash() => r'a721a4b92b48ee7c2289cdcd7130bbf1ca9dcb40';
final class MessagesNotifierFamily extends $Family
with

View File

@@ -32,35 +32,21 @@ const kAppEnterToSend = 'app_enter_to_send';
const kAppDefaultPoolId = 'app_default_pool_id';
const kAppMessageDisplayStyle = 'app_message_display_style';
const kAppThemeMode = 'app_theme_mode';
const kMaterialYouToggleStoreKey = 'app_theme_material_you';
const kAppDisableAnimation = 'app_disable_animation';
const kAppFabPosition = 'app_fab_position';
const kAppGroupedChatList = 'app_grouped_chat_list';
const kFeaturedPostsCollapsedId =
'featured_posts_collapsed_id'; // Key for storing the ID of the collapsed featured post
const kAppFirstLaunchAt = 'app_first_launch_at';
const kAppAskedReview = 'app_asked_review';
const kAppDashSearchEngine = 'app_dash_search_engine';
const kAppDefaultScreen = 'app_default_screen';
const kAppShowFediverseContent = 'app_show_fediverse_content';
const Map<String, FilterQuality> kImageQualityLevel = {
'settingsImageQualityLowest': FilterQuality.none,
'settingsImageQualityLow': FilterQuality.low,
'settingsImageQualityMedium': FilterQuality.medium,
'settingsImageQualityHigh': FilterQuality.high,
};
// Will be overrided by the ProviderScope
final sharedPreferencesProvider = Provider<SharedPreferences>((ref) {
throw UnimplementedError();
});
final imageQualityProvider = Provider<FilterQuality>((ref) {
final prefs = ref.watch(sharedPreferencesProvider);
return kImageQualityLevel.values.elementAtOrNull(
prefs.getInt('app_image_quality') ?? 3,
) ??
FilterQuality.high;
});
final serverUrlProvider = Provider<String>((ref) {
final prefs = ref.watch(sharedPreferencesProvider);
return prefs.getString(kNetworkServerStoreKey) ?? kNetworkServerDefault;
@@ -100,13 +86,13 @@ sealed class AppSettings with _$AppSettings {
required String? defaultPoolId,
required String messageDisplayStyle,
required String? themeMode,
required bool useMaterial3,
required bool disableAnimation,
required String fabPosition,
required bool groupedChatList,
required String? firstLaunchAt,
required bool askedReview,
required String? dashSearchEngine,
required String? defaultScreen,
required bool showFediverseContent,
}) = _AppSettings;
}
@@ -132,13 +118,13 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
defaultPoolId: prefs.getString(kAppDefaultPoolId),
messageDisplayStyle: prefs.getString(kAppMessageDisplayStyle) ?? 'bubble',
themeMode: prefs.getString(kAppThemeMode) ?? 'system',
useMaterial3: prefs.getBool(kMaterialYouToggleStoreKey) ?? true,
disableAnimation: prefs.getBool(kAppDisableAnimation) ?? false,
fabPosition: prefs.getString(kAppFabPosition) ?? 'center',
groupedChatList: prefs.getBool(kAppGroupedChatList) ?? false,
askedReview: prefs.getBool(kAppAskedReview) ?? false,
firstLaunchAt: prefs.getString(kAppFirstLaunchAt),
dashSearchEngine: prefs.getString(kAppDashSearchEngine),
defaultScreen: prefs.getString(kAppDefaultScreen),
showFediverseContent: prefs.getBool(kAppShowFediverseContent) ?? true,
);
}
@@ -229,6 +215,12 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
state = state.copyWith(customFonts: value);
}
void setDefaultScreen(String? value) {
final prefs = ref.read(sharedPreferencesProvider);
prefs.setString(kAppDefaultScreen, value ?? 'dashboard');
state = state.copyWith(defaultScreen: value);
}
void setAppColorScheme(int? value) {
final prefs = ref.read(sharedPreferencesProvider);
prefs.setInt(kAppColorSchemeStoreKey, value ?? 0);
@@ -274,12 +266,6 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
state = state.copyWith(cardTransparency: value);
}
void setUseMaterial3(bool value) {
final prefs = ref.read(sharedPreferencesProvider);
prefs.setBool(kMaterialYouToggleStoreKey, value);
state = state.copyWith(useMaterial3: value);
}
void setCustomColors(ThemeColors? value) {
final prefs = ref.read(sharedPreferencesProvider);
if (value != null) {
@@ -297,12 +283,6 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
state = state.copyWith(disableAnimation: value);
}
void setFabPosition(String value) {
final prefs = ref.read(sharedPreferencesProvider);
prefs.setString(kAppFabPosition, value);
state = state.copyWith(fabPosition: value);
}
void setGroupedChatList(bool value) {
final prefs = ref.read(sharedPreferencesProvider);
prefs.setBool(kAppGroupedChatList, value);
@@ -334,6 +314,12 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
}
state = state.copyWith(dashSearchEngine: value);
}
void setShowFediverseContent(bool value) {
final prefs = ref.read(sharedPreferencesProvider);
prefs.setBool(kAppShowFediverseContent, value);
state = state.copyWith(showFediverseContent: value);
}
}
final updateInfoProvider =

View File

@@ -290,7 +290,7 @@ mixin _$AppSettings {
ThemeColors? get customColors; Size? get windowSize;// The window size for desktop platforms
double get windowOpacity;// The window opacity for desktop platforms
double get cardTransparency;// The card background opacity
String? get defaultPoolId; String get messageDisplayStyle; String? get themeMode; bool get useMaterial3; bool get disableAnimation; String get fabPosition; bool get groupedChatList; String? get firstLaunchAt; bool get askedReview; String? get dashSearchEngine;
String? get defaultPoolId; String get messageDisplayStyle; String? get themeMode; bool get disableAnimation; bool get groupedChatList; String? get firstLaunchAt; bool get askedReview; String? get dashSearchEngine; String? get defaultScreen; bool get showFediverseContent;
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@@ -301,16 +301,16 @@ $AppSettingsCopyWith<AppSettings> get copyWith => _$AppSettingsCopyWithImpl<AppS
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.useMaterial3, useMaterial3) || other.useMaterial3 == useMaterial3)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.fabPosition, fabPosition) || other.fabPosition == fabPosition)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine));
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine)&&(identical(other.defaultScreen, defaultScreen) || other.defaultScreen == defaultScreen)&&(identical(other.showFediverseContent, showFediverseContent) || other.showFediverseContent == showFediverseContent));
}
@override
int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,useMaterial3,disableAnimation,fabPosition,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine]);
int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,disableAnimation,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine,defaultScreen,showFediverseContent]);
@override
String toString() {
return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, useMaterial3: $useMaterial3, disableAnimation: $disableAnimation, fabPosition: $fabPosition, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine)';
return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, disableAnimation: $disableAnimation, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine, defaultScreen: $defaultScreen, showFediverseContent: $showFediverseContent)';
}
@@ -321,7 +321,7 @@ abstract mixin class $AppSettingsCopyWith<$Res> {
factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl;
@useResult
$Res call({
bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool useMaterial3, bool disableAnimation, String fabPosition, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine
bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent
});
@@ -338,7 +338,7 @@ class _$AppSettingsCopyWithImpl<$Res>
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? useMaterial3 = null,Object? disableAnimation = null,Object? fabPosition = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,}) {
@pragma('vm:prefer-inline') @override $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? disableAnimation = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,Object? defaultScreen = freezed,Object? showFediverseContent = null,}) {
return _then(_self.copyWith(
dataSavingMode: null == dataSavingMode ? _self.dataSavingMode : dataSavingMode // ignore: cast_nullable_to_non_nullable
as bool,soundEffects: null == soundEffects ? _self.soundEffects : soundEffects // ignore: cast_nullable_to_non_nullable
@@ -356,14 +356,14 @@ as double,cardTransparency: null == cardTransparency ? _self.cardTransparency :
as double,defaultPoolId: freezed == defaultPoolId ? _self.defaultPoolId : defaultPoolId // ignore: cast_nullable_to_non_nullable
as String?,messageDisplayStyle: null == messageDisplayStyle ? _self.messageDisplayStyle : messageDisplayStyle // ignore: cast_nullable_to_non_nullable
as String,themeMode: freezed == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable
as String?,useMaterial3: null == useMaterial3 ? _self.useMaterial3 : useMaterial3 // ignore: cast_nullable_to_non_nullable
as bool,disableAnimation: null == disableAnimation ? _self.disableAnimation : disableAnimation // ignore: cast_nullable_to_non_nullable
as bool,fabPosition: null == fabPosition ? _self.fabPosition : fabPosition // ignore: cast_nullable_to_non_nullable
as String,groupedChatList: null == groupedChatList ? _self.groupedChatList : groupedChatList // ignore: cast_nullable_to_non_nullable
as String?,disableAnimation: null == disableAnimation ? _self.disableAnimation : disableAnimation // ignore: cast_nullable_to_non_nullable
as bool,groupedChatList: null == groupedChatList ? _self.groupedChatList : groupedChatList // ignore: cast_nullable_to_non_nullable
as bool,firstLaunchAt: freezed == firstLaunchAt ? _self.firstLaunchAt : firstLaunchAt // ignore: cast_nullable_to_non_nullable
as String?,askedReview: null == askedReview ? _self.askedReview : askedReview // ignore: cast_nullable_to_non_nullable
as bool,dashSearchEngine: freezed == dashSearchEngine ? _self.dashSearchEngine : dashSearchEngine // ignore: cast_nullable_to_non_nullable
as String?,
as String?,defaultScreen: freezed == defaultScreen ? _self.defaultScreen : defaultScreen // ignore: cast_nullable_to_non_nullable
as String?,showFediverseContent: null == showFediverseContent ? _self.showFediverseContent : showFediverseContent // ignore: cast_nullable_to_non_nullable
as bool,
));
}
/// Create a copy of AppSettings
@@ -457,10 +457,10 @@ return $default(_that);case _:
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool useMaterial3, bool disableAnimation, String fabPosition, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine)? $default,{required TResult orElse(),}) {final _that = this;
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _AppSettings() when $default != null:
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.useMaterial3,_that.disableAnimation,_that.fabPosition,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine);case _:
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent);case _:
return orElse();
}
@@ -478,10 +478,10 @@ return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool useMaterial3, bool disableAnimation, String fabPosition, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine) $default,) {final _that = this;
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent) $default,) {final _that = this;
switch (_that) {
case _AppSettings():
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.useMaterial3,_that.disableAnimation,_that.fabPosition,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine);}
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent);}
}
/// A variant of `when` that fallback to returning `null`
///
@@ -495,10 +495,10 @@ return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool useMaterial3, bool disableAnimation, String fabPosition, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine)? $default,) {final _that = this;
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent)? $default,) {final _that = this;
switch (_that) {
case _AppSettings() when $default != null:
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.useMaterial3,_that.disableAnimation,_that.fabPosition,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine);case _:
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent);case _:
return null;
}
@@ -510,7 +510,7 @@ return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_
class _AppSettings implements AppSettings {
const _AppSettings({required this.dataSavingMode, required this.soundEffects, required this.festivalFeatures, required this.enterToSend, required this.appBarTransparent, required this.showBackgroundImage, required this.notifyWithHaptic, required this.customFonts, required this.appColorScheme, required this.customColors, required this.windowSize, required this.windowOpacity, required this.cardTransparency, required this.defaultPoolId, required this.messageDisplayStyle, required this.themeMode, required this.useMaterial3, required this.disableAnimation, required this.fabPosition, required this.groupedChatList, required this.firstLaunchAt, required this.askedReview, required this.dashSearchEngine});
const _AppSettings({required this.dataSavingMode, required this.soundEffects, required this.festivalFeatures, required this.enterToSend, required this.appBarTransparent, required this.showBackgroundImage, required this.notifyWithHaptic, required this.customFonts, required this.appColorScheme, required this.customColors, required this.windowSize, required this.windowOpacity, required this.cardTransparency, required this.defaultPoolId, required this.messageDisplayStyle, required this.themeMode, required this.disableAnimation, required this.groupedChatList, required this.firstLaunchAt, required this.askedReview, required this.dashSearchEngine, required this.defaultScreen, required this.showFediverseContent});
@override final bool dataSavingMode;
@@ -533,13 +533,13 @@ class _AppSettings implements AppSettings {
@override final String? defaultPoolId;
@override final String messageDisplayStyle;
@override final String? themeMode;
@override final bool useMaterial3;
@override final bool disableAnimation;
@override final String fabPosition;
@override final bool groupedChatList;
@override final String? firstLaunchAt;
@override final bool askedReview;
@override final String? dashSearchEngine;
@override final String? defaultScreen;
@override final bool showFediverseContent;
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@@ -551,16 +551,16 @@ _$AppSettingsCopyWith<_AppSettings> get copyWith => __$AppSettingsCopyWithImpl<_
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.useMaterial3, useMaterial3) || other.useMaterial3 == useMaterial3)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.fabPosition, fabPosition) || other.fabPosition == fabPosition)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine));
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine)&&(identical(other.defaultScreen, defaultScreen) || other.defaultScreen == defaultScreen)&&(identical(other.showFediverseContent, showFediverseContent) || other.showFediverseContent == showFediverseContent));
}
@override
int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,useMaterial3,disableAnimation,fabPosition,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine]);
int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,disableAnimation,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine,defaultScreen,showFediverseContent]);
@override
String toString() {
return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, useMaterial3: $useMaterial3, disableAnimation: $disableAnimation, fabPosition: $fabPosition, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine)';
return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, disableAnimation: $disableAnimation, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine, defaultScreen: $defaultScreen, showFediverseContent: $showFediverseContent)';
}
@@ -571,7 +571,7 @@ abstract mixin class _$AppSettingsCopyWith<$Res> implements $AppSettingsCopyWith
factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl;
@override @useResult
$Res call({
bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool useMaterial3, bool disableAnimation, String fabPosition, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine
bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent
});
@@ -588,7 +588,7 @@ class __$AppSettingsCopyWithImpl<$Res>
/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? useMaterial3 = null,Object? disableAnimation = null,Object? fabPosition = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,}) {
@override @pragma('vm:prefer-inline') $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? disableAnimation = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,Object? defaultScreen = freezed,Object? showFediverseContent = null,}) {
return _then(_AppSettings(
dataSavingMode: null == dataSavingMode ? _self.dataSavingMode : dataSavingMode // ignore: cast_nullable_to_non_nullable
as bool,soundEffects: null == soundEffects ? _self.soundEffects : soundEffects // ignore: cast_nullable_to_non_nullable
@@ -606,14 +606,14 @@ as double,cardTransparency: null == cardTransparency ? _self.cardTransparency :
as double,defaultPoolId: freezed == defaultPoolId ? _self.defaultPoolId : defaultPoolId // ignore: cast_nullable_to_non_nullable
as String?,messageDisplayStyle: null == messageDisplayStyle ? _self.messageDisplayStyle : messageDisplayStyle // ignore: cast_nullable_to_non_nullable
as String,themeMode: freezed == themeMode ? _self.themeMode : themeMode // ignore: cast_nullable_to_non_nullable
as String?,useMaterial3: null == useMaterial3 ? _self.useMaterial3 : useMaterial3 // ignore: cast_nullable_to_non_nullable
as bool,disableAnimation: null == disableAnimation ? _self.disableAnimation : disableAnimation // ignore: cast_nullable_to_non_nullable
as bool,fabPosition: null == fabPosition ? _self.fabPosition : fabPosition // ignore: cast_nullable_to_non_nullable
as String,groupedChatList: null == groupedChatList ? _self.groupedChatList : groupedChatList // ignore: cast_nullable_to_non_nullable
as String?,disableAnimation: null == disableAnimation ? _self.disableAnimation : disableAnimation // ignore: cast_nullable_to_non_nullable
as bool,groupedChatList: null == groupedChatList ? _self.groupedChatList : groupedChatList // ignore: cast_nullable_to_non_nullable
as bool,firstLaunchAt: freezed == firstLaunchAt ? _self.firstLaunchAt : firstLaunchAt // ignore: cast_nullable_to_non_nullable
as String?,askedReview: null == askedReview ? _self.askedReview : askedReview // ignore: cast_nullable_to_non_nullable
as bool,dashSearchEngine: freezed == dashSearchEngine ? _self.dashSearchEngine : dashSearchEngine // ignore: cast_nullable_to_non_nullable
as String?,
as String?,defaultScreen: freezed == defaultScreen ? _self.defaultScreen : defaultScreen // ignore: cast_nullable_to_non_nullable
as String?,showFediverseContent: null == showFediverseContent ? _self.showFediverseContent : showFediverseContent // ignore: cast_nullable_to_non_nullable
as bool,
));
}

View File

@@ -65,7 +65,7 @@ final class AppSettingsNotifierProvider
}
String _$appSettingsNotifierHash() =>
r'ee6b67190f3db5d8cb8a9e438a444e91685927d4';
r'2437c621dcb1625a120ed1f21ab5c29906ba98be';
abstract class _$AppSettingsNotifier extends $Notifier<AppSettings> {
AppSettings build();

View File

@@ -18,7 +18,8 @@ final indexedCloudFileListProvider = AsyncNotifierProvider.autoDispose(
IndexedCloudFileListNotifier.new,
);
class IndexedCloudFileListNotifier extends AsyncNotifier<List<FileListItem>>
class IndexedCloudFileListNotifier
extends AsyncNotifier<PaginationState<FileListItem>>
with AsyncPaginationController<FileListItem> {
String _currentPath = '/';
String? _poolId;
@@ -51,6 +52,19 @@ class IndexedCloudFileListNotifier extends AsyncNotifier<List<FileListItem>>
ref.invalidateSelf();
}
@override
FutureOr<PaginationState<FileListItem>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: null,
hasMore: false,
cursor: null,
);
}
@override
Future<List<FileListItem>> fetch() async {
final client = ref.read(apiClientProvider);
@@ -96,7 +110,8 @@ final unindexedFileListProvider = AsyncNotifierProvider.autoDispose(
UnindexedFileListNotifier.new,
);
class UnindexedFileListNotifier extends AsyncNotifier<List<FileListItem>>
class UnindexedFileListNotifier
extends AsyncNotifier<PaginationState<FileListItem>>
with AsyncPaginationController<FileListItem> {
String? _poolId;
bool _recycled = false;
@@ -131,6 +146,19 @@ class UnindexedFileListNotifier extends AsyncNotifier<List<FileListItem>>
static const int pageSize = 20;
@override
FutureOr<PaginationState<FileListItem>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<FileListItem>> fetch() async {
final client = ref.read(apiClientProvider);

View File

@@ -5,6 +5,7 @@ import 'dart:io';
import 'package:dio_smart_retry/dio_smart_retry.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:package_info_plus/package_info_plus.dart';
@@ -16,6 +17,36 @@ import 'package:island/talker.dart';
import 'config.dart';
part 'network.g.dart';
// Network status enum to track different states
enum NetworkStatus { online, notReady, maintenance, offline }
// Provider for network status using Riverpod v3 annotation
@riverpod
class NetworkStatusNotifier extends _$NetworkStatusNotifier {
@override
NetworkStatus build() {
return NetworkStatus.online;
}
void setOnline() {
state = NetworkStatus.online;
}
void setMaintenance() {
state = NetworkStatus.maintenance;
}
void setOffline() {
state = NetworkStatus.offline;
}
void setNotReady() {
state = NetworkStatus.notReady;
}
}
final imagePickerProvider = Provider((ref) => ImagePicker());
final userAgentProvider = FutureProvider<String>((ref) async {
@@ -80,24 +111,58 @@ final apiClientProvider = Provider<Dio>((ref) {
dio.interceptors.addAll([
InterceptorsWrapper(
onRequest: (
RequestOptions options,
RequestInterceptorHandler handler,
) async {
try {
final token = await getToken(ref.watch(tokenProvider));
if (token != null) {
options.headers['Authorization'] = 'AtField $token';
}
} catch (err) {
// ignore
}
onRequest:
(RequestOptions options, RequestInterceptorHandler handler) async {
try {
final token = await getToken(ref.watch(tokenProvider));
if (token != null) {
options.headers['Authorization'] = 'AtField $token';
}
} catch (err) {
// ignore
}
final userAgent = ref.read(userAgentProvider);
if (userAgent.value != null) {
options.headers['User-Agent'] = userAgent.value;
final userAgent = ref.read(userAgentProvider);
if (userAgent.value != null) {
options.headers['User-Agent'] = userAgent.value;
}
return handler.next(options);
},
onResponse: (response, handler) {
// Check for 503 status code (Service Unavailable/Maintenance)
if (response.statusCode == 503) {
final networkStatusNotifier = ref.read(
networkStatusProvider.notifier,
);
if (response.headers.value('X-NotReady') != null) {
networkStatusNotifier.setNotReady();
} else {
networkStatusNotifier.setMaintenance();
}
} else if (response.statusCode != null &&
response.statusCode! >= 200 &&
response.statusCode! < 300) {
// Set online status for successful responses
final networkStatusNotifier = ref.read(
networkStatusProvider.notifier,
);
networkStatusNotifier.setOnline();
}
return handler.next(options);
return handler.next(response);
},
onError: (error, handler) {
// Handle network errors and set offline status
if (error.response?.statusCode == 503) {
final networkStatusNotifier = ref.read(
networkStatusProvider.notifier,
);
if (error.response?.headers.value('X-NotReady') != null) {
networkStatusNotifier.setNotReady();
} else {
networkStatusNotifier.setMaintenance();
}
}
return handler.next(error);
},
),
TalkerDioLogger(

64
lib/pods/network.g.dart Normal file
View File

@@ -0,0 +1,64 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'network.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(NetworkStatusNotifier)
const networkStatusProvider = NetworkStatusNotifierProvider._();
final class NetworkStatusNotifierProvider
extends $NotifierProvider<NetworkStatusNotifier, NetworkStatus> {
const NetworkStatusNotifierProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'networkStatusProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$networkStatusNotifierHash();
@$internal
@override
NetworkStatusNotifier create() => NetworkStatusNotifier();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(NetworkStatus value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<NetworkStatus>(value),
);
}
}
String _$networkStatusNotifierHash() =>
r'6f08e3067fa5265432f28f64e10775e3039506c3';
abstract class _$NetworkStatusNotifier extends $Notifier<NetworkStatus> {
NetworkStatus build();
@$mustCallSuper
@override
void runBuild() {
final created = build();
final ref = this.ref as $Ref<NetworkStatus, NetworkStatus>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<NetworkStatus, NetworkStatus>,
NetworkStatus,
Object?,
Object?
>;
element.handleValue(ref, created);
}
}

View File

@@ -2,12 +2,53 @@ import 'dart:async';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class PaginationState<T> {
final List<T> items;
final bool isLoading;
final bool isReloading;
final int? totalCount;
final bool hasMore;
final String? cursor;
const PaginationState({
required this.items,
required this.isLoading,
required this.isReloading,
required this.totalCount,
required this.hasMore,
required this.cursor,
});
PaginationState<T> copyWith({
List<T>? items,
bool? isLoading,
bool? isReloading,
int? totalCount,
bool? hasMore,
String? cursor,
}) {
return PaginationState<T>(
items: items ?? this.items,
isLoading: isLoading ?? this.isLoading,
isReloading: isReloading ?? this.isReloading,
totalCount: totalCount ?? this.totalCount,
hasMore: hasMore ?? this.hasMore,
cursor: cursor ?? this.cursor,
);
}
}
abstract class PaginationController<T> {
int? get totalCount;
int get fetchedCount;
bool get fetchedAll;
bool get isLoading;
bool get isReloading;
bool get hasMore;
set hasMore(bool value);
String? get cursor;
set cursor(String? value);
FutureOr<List<T>> fetch();
@@ -22,50 +63,104 @@ abstract class PaginationFiltered<F> {
Future<void> applyFilter(F filter);
}
mixin AsyncPaginationController<T> on AsyncNotifier<List<T>>
mixin AsyncPaginationController<T> on AsyncNotifier<PaginationState<T>>
implements PaginationController<T> {
@override
int? totalCount;
@override
int get fetchedCount => state.value?.length ?? 0;
int get fetchedCount =>
state.value?.isReloading == true ? 0 : state.value?.items.length ?? 0;
@override
bool get fetchedAll => totalCount != null && fetchedCount >= totalCount!;
bool get fetchedAll =>
!(state.value?.hasMore ?? true) ||
((state.value?.totalCount != null &&
fetchedCount >= state.value!.totalCount!));
@override
bool isLoading = false;
bool get isLoading => state.value?.isLoading ?? false;
@override
FutureOr<List<T>> build() async => fetch();
bool get isReloading => state.value?.isReloading ?? false;
@override
bool get hasMore => state.value?.hasMore ?? true;
@override
String? get cursor => state.value?.cursor;
@override
set hasMore(bool value) {
if (state is AsyncData) {
state = AsyncData((state as AsyncData).value.copyWith(hasMore: value));
}
}
@override
set cursor(String? value) {
if (state is AsyncData) {
state = AsyncData((state as AsyncData).value.copyWith(cursor: value));
}
}
@override
FutureOr<PaginationState<T>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<void> refresh() async {
isLoading = true;
totalCount = null;
state = AsyncData<List<T>>([]);
state = AsyncData(
PaginationState(
items: [],
isLoading: true,
isReloading: true,
totalCount: null,
hasMore: true,
cursor: null,
),
);
final newState = await AsyncValue.guard<List<T>>(() async {
return await fetch();
});
state = newState;
isLoading = false;
final newItems = await fetch();
if (!ref.mounted) return;
state = AsyncData(
PaginationState(
items: newItems,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
),
);
}
@override
Future<void> fetchFurther() async {
if (fetchedAll) return;
if (isLoading) return;
isLoading = true;
state = AsyncLoading<List<T>>();
state = AsyncData(state.value!.copyWith(isLoading: true));
final newState = await AsyncValue.guard<List<T>>(() async {
final elements = await fetch();
return [...?state.value, ...elements];
});
final newItems = await fetch();
state = newState;
isLoading = false;
if (!ref.mounted) return;
state = AsyncData(
state.value!.copyWith(
items: [...state.value!.items, ...newItems],
isLoading: false,
),
);
}
}
@@ -74,16 +169,31 @@ mixin AsyncPaginationFilter<F, T> on AsyncPaginationController<T>
@override
Future<void> applyFilter(F filter) async {
if (currentFilter == filter) return;
// Reset the data
isLoading = true;
totalCount = null;
state = AsyncData<List<T>>([]);
state = AsyncData(
PaginationState(
items: [],
isLoading: true,
isReloading: true,
totalCount: null,
hasMore: true,
cursor: null,
),
);
currentFilter = filter;
final newState = await AsyncValue.guard<List<T>>(() async {
return await fetch();
});
state = newState;
isLoading = false;
final newItems = await fetch();
if (!ref.mounted) return;
state = AsyncData(
PaginationState(
items: newItems,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
),
);
}
}

View File

@@ -1,4 +1,6 @@
// Post Categories Notifier
import 'dart:async';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/post_category.dart';
import 'package:island/models/post_tag.dart';
@@ -8,11 +10,25 @@ import 'package:island/pods/paging.dart';
final postCategoriesProvider =
AsyncNotifierProvider.autoDispose<
PostCategoriesNotifier,
List<SnPostCategory>
PaginationState<SnPostCategory>
>(PostCategoriesNotifier.new);
class PostCategoriesNotifier extends AsyncNotifier<List<SnPostCategory>>
class PostCategoriesNotifier
extends AsyncNotifier<PaginationState<SnPostCategory>>
with AsyncPaginationController<SnPostCategory> {
@override
FutureOr<PaginationState<SnPostCategory>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnPostCategory>> fetch() async {
final client = ref.read(apiClientProvider);
@@ -30,12 +46,26 @@ class PostCategoriesNotifier extends AsyncNotifier<List<SnPostCategory>>
// Post Tags Notifier
final postTagsProvider =
AsyncNotifierProvider.autoDispose<PostTagsNotifier, List<SnPostTag>>(
PostTagsNotifier.new,
);
AsyncNotifierProvider.autoDispose<
PostTagsNotifier,
PaginationState<SnPostTag>
>(PostTagsNotifier.new);
class PostTagsNotifier extends AsyncNotifier<List<SnPostTag>>
class PostTagsNotifier extends AsyncNotifier<PaginationState<SnPostTag>>
with AsyncPaginationController<SnPostTag> {
@override
FutureOr<PaginationState<SnPostTag>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnPostTag>> fetch() async {
final client = ref.read(apiClientProvider);

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/post.dart';
@@ -39,7 +41,7 @@ final postListProvider = AsyncNotifierProvider.autoDispose.family(
PostListNotifier.new,
);
class PostListNotifier extends AsyncNotifier<List<SnPost>>
class PostListNotifier extends AsyncNotifier<PaginationState<SnPost>>
with
AsyncPaginationController<SnPost>,
AsyncPaginationFilter<PostListQuery, SnPost> {
@@ -53,9 +55,17 @@ class PostListNotifier extends AsyncNotifier<List<SnPost>>
late PostListQuery currentFilter;
@override
Future<List<SnPost>> build() async {
FutureOr<PaginationState<SnPost>> build() async {
currentFilter = config.initialFilter;
return fetch();
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override

View File

@@ -25,10 +25,9 @@ ThemeSet createAppThemeSet(AppSettings settings) {
}
ThemeData createAppTheme(Brightness brightness, AppSettings settings) {
final seedColor =
settings.appColorScheme != null
? Color(settings.appColorScheme!)
: Colors.indigo;
final seedColor = settings.appColorScheme != null
? Color(settings.appColorScheme!)
: Colors.indigo;
var colorScheme = ColorScheme.fromSeed(
seedColor: seedColor,
@@ -38,33 +37,33 @@ ThemeData createAppTheme(Brightness brightness, AppSettings settings) {
final customColors = settings.customColors;
if (customColors != null) {
colorScheme = colorScheme.copyWith(
primary:
customColors.primary != null ? Color(customColors.primary!) : null,
secondary:
customColors.secondary != null
? Color(customColors.secondary!)
: null,
tertiary:
customColors.tertiary != null ? Color(customColors.tertiary!) : null,
surface:
customColors.surface != null ? Color(customColors.surface!) : null,
background:
customColors.background != null
? Color(customColors.background!)
: null,
primary: customColors.primary != null
? Color(customColors.primary!)
: null,
secondary: customColors.secondary != null
? Color(customColors.secondary!)
: null,
tertiary: customColors.tertiary != null
? Color(customColors.tertiary!)
: null,
surface: customColors.surface != null
? Color(customColors.surface!)
: null,
background: customColors.background != null
? Color(customColors.background!)
: null,
error: customColors.error != null ? Color(customColors.error!) : null,
);
}
final hasAppBarTransparent = settings.appBarTransparent;
final useM3 = settings.useMaterial3;
final inUseFonts =
settings.customFonts?.split(',').map((ele) => ele.trim()).toList() ??
['Nunito'];
return ThemeData(
useMaterial3: useM3,
useMaterial3: true,
colorScheme: colorScheme,
brightness: brightness,
fontFamily: inUseFonts.firstOrNull,
@@ -78,10 +77,12 @@ ThemeData createAppTheme(Brightness brightness, AppSettings settings) {
appBarTheme: AppBarTheme(
centerTitle: true,
elevation: hasAppBarTransparent ? 0 : null,
backgroundColor:
hasAppBarTransparent ? Colors.transparent : colorScheme.primary,
foregroundColor:
hasAppBarTransparent ? colorScheme.onSurface : colorScheme.onPrimary,
backgroundColor: hasAppBarTransparent
? Colors.transparent
: colorScheme.primary,
foregroundColor: hasAppBarTransparent
? colorScheme.onSurface
: colorScheme.onPrimary,
),
cardTheme: CardThemeData(
color: colorScheme.surfaceContainer.withOpacity(

View File

@@ -1,5 +1,8 @@
import 'dart:async';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/activity.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart';
import 'package:island/pods/paging.dart';
@@ -7,25 +10,39 @@ final activityListProvider = AsyncNotifierProvider.autoDispose(
ActivityListNotifier.new,
);
class ActivityListNotifier extends AsyncNotifier<List<SnTimelineEvent>>
class ActivityListNotifier
extends AsyncNotifier<PaginationState<SnTimelineEvent>>
with
AsyncPaginationController<SnTimelineEvent>,
AsyncPaginationFilter<String?, SnTimelineEvent> {
static const int pageSize = 20;
@override
FutureOr<PaginationState<SnTimelineEvent>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
String? currentFilter;
@override
Future<List<SnTimelineEvent>> fetch() async {
final client = ref.read(apiClientProvider);
final cursor = state.value?.lastOrNull?.createdAt.toUtc().toIso8601String();
final settings = ref.read(appSettingsProvider);
final queryParameters = {
if (cursor != null) 'cursor': cursor,
'take': pageSize,
if (currentFilter != null) 'filter': currentFilter,
'showFediverse': settings.showFediverseContent,
};
final response = await client.get(
@@ -37,10 +54,16 @@ class ActivityListNotifier extends AsyncNotifier<List<SnTimelineEvent>>
.map((e) => SnTimelineEvent.fromJson(e as Map<String, dynamic>))
.toList();
final hasMore = (items.firstOrNull?.type ?? 'empty') != 'empty';
totalCount =
(state.value?.length ?? 0) + items.length + (hasMore ? pageSize : 0);
hasMore = (items.firstOrNull?.type ?? 'empty') != 'empty';
// Find the latest createdAt timestamp from all items for cursor-based pagination
// This ensures we get items created before this timestamp, regardless of sort order
if (items.isNotEmpty) {
final latestCreatedAt = items
.where((e) => e.type.startsWith('posts.'))
.map((e) => e.createdAt)
.reduce((a, b) => a.isBefore(b) ? a : b);
cursor = latestCreatedAt.toUtc().toIso8601String();
}
return items;
}
@@ -49,9 +72,9 @@ class ActivityListNotifier extends AsyncNotifier<List<SnTimelineEvent>>
final currentState = state.value;
if (currentState == null) return;
final updatedItems = [...currentState];
final updatedItems = [...currentState.items];
updatedItems[index] = activity;
state = AsyncData(updatedItems);
state = AsyncData(currentState.copyWith(items: updatedItems));
}
}

View File

@@ -36,71 +36,41 @@ class UserInfoNotifier extends AsyncNotifier<SnAccount?> {
}
return user;
} catch (error, stackTrace) {
if (!kIsWeb) {
if (error is DioException) {
showOverlayDialog<bool>(
builder:
(context, close) => AlertDialog(
title: Text('failedToLoadUserInfo'.tr()),
content: Text(
[
(error.response?.statusCode == 401
? 'failedToLoadUserInfoUnauthorized'
: 'failedToLoadUserInfoNetwork')
.tr()
.trim(),
'',
'${error.response?.statusCode ?? 'Network Error'}',
if (error.response?.headers != null)
error.response?.headers,
if (error.response?.data != null)
jsonEncode(error.response?.data),
].join('\n'),
),
actions: [
TextButton(
onPressed: () => close(false),
child: Text('okay'.tr()),
),
TextButton(
onPressed: () => close(true),
child: Text('retry'.tr()),
),
],
),
).then((value) {
if (value == true) {
ref.invalidateSelf();
}
});
} else {
showOverlayDialog<bool>(
builder:
(context, close) => AlertDialog(
title: Text('failedToLoadUserInfo'.tr()),
content: Text(
[
'failedToLoadUserInfoNetwork'.tr(),
error.toString(),
].join('\n\n').trim(),
),
actions: [
TextButton(
onPressed: () => close(false),
child: Text('okay'.tr()),
),
TextButton(
onPressed: () => close(true),
child: Text('retry'.tr()),
),
],
),
).then((value) {
if (value == true) {
ref.invalidateSelf();
}
});
}
if (error is DioException) {
if (error.response?.statusCode == 503) return null;
showOverlayDialog<bool>(
builder: (context, close) => AlertDialog(
title: Text('failedToLoadUserInfo'.tr()),
content: Text(
[
(error.response?.statusCode == 401
? 'failedToLoadUserInfoUnauthorized'
: 'failedToLoadUserInfoNetwork')
.tr()
.trim(),
'',
'${error.response?.statusCode ?? 'Network Error'}',
if (error.response?.headers != null) error.response?.headers,
if (error.response?.data != null)
jsonEncode(error.response?.data),
].join('\n'),
),
actions: [
TextButton(
onPressed: () => close(false),
child: Text('okay'.tr()),
),
TextButton(
onPressed: () => close(true),
child: Text('retry'.tr()),
),
],
),
).then((value) {
if (value == true) {
ref.invalidateSelf();
}
});
}
talker.error(
"[UserInfo] Failed to fetch user info...",

View File

@@ -52,6 +52,11 @@ class WebSocketService {
DateTime? _heartbeatAt;
Duration? heartbeatDelay;
// Reconnection tracking
int _reconnectCount = 0;
DateTime? _reconnectWindowStart;
static const int _maxReconnectsPerMinute = 5;
Stream<WebSocketPacket> get dataStream => _streamController.stream;
Stream<WebSocketState> get statusStream => _statusStreamController.stream;
@@ -79,8 +84,9 @@ class WebSocketService {
_scheduleHeartbeat();
_channel!.stream.listen(
(data) {
final dataStr =
data is Uint8List ? utf8.decode(data) : data.toString();
final dataStr = data is Uint8List
? utf8.decode(data)
: data.toString();
final packet = WebSocketPacket.fromJson(jsonDecode(dataStr));
if (packet.type == 'error.dupe') {
_statusStreamController.sink.add(WebSocketState.duplicateDevice());
@@ -123,6 +129,35 @@ class WebSocketService {
}
void _scheduleReconnect() {
// Check if we've exceeded the reconnect limit
final now = DateTime.now();
if (_reconnectWindowStart == null ||
now.difference(_reconnectWindowStart!).inMinutes >= 1) {
// Reset window if it's been more than 1 minute since the window started
_reconnectWindowStart = now;
_reconnectCount = 0;
}
_reconnectCount++;
if (_reconnectCount > _maxReconnectsPerMinute) {
talker.error(
'[WebSocket] Reconnect limit exceeded: $_maxReconnectsPerMinute reconnections in the last minute. Stopping auto-reconnect.',
);
_statusStreamController.sink.add(WebSocketState.serverDown());
return;
}
_reconnectTimer?.cancel();
_reconnectTimer = Timer(const Duration(milliseconds: 500), () {
_statusStreamController.sink.add(WebSocketState.connecting());
connect(_ref);
});
}
void manualReconnect() {
_statusStreamController.sink.add(WebSocketState.connecting());
talker.info('[WebSocket] Manual reconnect triggered by user');
_reconnectTimer?.cancel();
_reconnectTimer = Timer(const Duration(milliseconds: 500), () {
_statusStreamController.sink.add(WebSocketState.connecting());
@@ -204,4 +239,9 @@ class WebSocketStateNotifier extends Notifier<WebSocketState> {
_reconnectTimer?.cancel();
state = const WebSocketState.disconnected();
}
void manualReconnect() {
final service = ref.read(websocketProvider);
service.manualReconnect();
}
}

View File

@@ -6,6 +6,8 @@ import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/screens/about.dart';
import 'package:island/screens/activitypub/list.dart';
import 'package:island/screens/activitypub/search.dart';
import 'package:island/screens/dashboard/dash.dart';
import 'package:island/screens/developers/app_detail.dart';
import 'package:island/screens/developers/bot_detail.dart';
@@ -19,6 +21,8 @@ import 'package:island/screens/files/file_detail.dart';
import 'package:island/screens/posts/post_categories_list.dart';
import 'package:island/screens/posts/post_category_detail.dart';
import 'package:island/screens/posts/post_search.dart';
import 'package:island/screens/search.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/app_wrapper.dart';
import 'package:island/screens/tabs.dart';
import 'package:island/screens/explore.dart';
@@ -121,7 +125,12 @@ final routerProvider = Provider<GoRouter>((ref) {
GoRoute(
name: 'logs',
path: '/logs',
builder: (context, state) => TalkerScreen(talker: talker),
builder: (context, state) => TalkerScreen(
talker: talker,
appBarTitle: 'Debug Logs',
appBarLeading: const PageBackButton(),
theme: TalkerScreenTheme.fromTheme(Theme.of(context)),
),
),
// Web articles
@@ -179,6 +188,30 @@ final routerProvider = Provider<GoRouter>((ref) {
},
),
GoRoute(
name: 'universalSearch',
path: '/search',
builder: (context, state) => const UniversalSearchScreen(),
),
GoRoute(
name: 'activitypubSearch',
path: '/activitypub/search',
builder: (context, state) => const ApSearchScreen(),
),
GoRoute(
name: 'activitypubFollowing',
path: '/activitypub/following',
builder: (context, state) =>
const ApListScreen(type: ActivityPubListType.following),
),
GoRoute(
name: 'activitypubFollowers',
path: '/activitypub/followers',
builder: (context, state) =>
const ApListScreen(type: ActivityPubListType.followers),
),
// Main tabs with TabsScreen shell
ShellRoute(
navigatorKey: _tabsShellKey,

View File

@@ -0,0 +1,23 @@
import 'package:island/screens/activitypub/activitypub.dart';
Add to Explore tab routes, after postCategoryDetail route:
GoRoute(
name: 'activitypubSearch',
path: '/activitypub/search',
builder: (context, state) => const ActivityPubSearchScreen(),
),
GoRoute(
name: 'activitypubFollowing',
path: '/activitypub/following',
builder: (context, state) => const ActivityPubListScreen(
type: ActivityPubListType.following,
),
),
GoRoute(
name: 'activitypubFollowers',
path: '/activitypub/followers',
builder: (context, state) => const ActivityPubListScreen(
type: ActivityPubListType.followers,
),
),

View File

@@ -368,20 +368,22 @@ class AccountScreen extends HookConsumerWidget {
);
},
},
{
'icon': Symbols.files,
'title': 'files',
'onTap': () {
context.goNamed('files');
if (!isWideScreen(context))
{
'icon': Symbols.files,
'title': 'files',
'onTap': () {
context.goNamed('files');
},
},
},
{
'icon': Symbols.group,
'title': 'realms',
'onTap': () {
context.goNamed('realmList');
if (!isWideScreen(context))
{
'icon': Symbols.groups_3,
'title': 'realms',
'onTap': () {
context.goNamed('realmList');
},
},
},
{
'icon': Symbols.wallet,
'title': 'wallet',
@@ -418,67 +420,47 @@ class AccountScreen extends HookConsumerWidget {
},
},
];
return GridView.builder(
padding: const EdgeInsets.symmetric(horizontal: 12),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 80,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
itemCount: menuItems.length,
itemBuilder: (context, index) {
final item = menuItems[index];
return Column(
children: menuItems.map((item) {
final icon = item['icon'] as IconData;
final title = item['title'] as String;
final badgeCount = item['badgeCount'] as int?;
final onTap = item['onTap'] as VoidCallback?;
return Card(
margin: EdgeInsets.zero,
child: Tooltip(
message: title.tr(),
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Badge(
isLabelVisible:
badgeCount != null && badgeCount > 0,
label: Text(badgeCount.toString()),
child: Icon(icon, size: 28),
),
],
),
),
),
return ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
trailing: const Icon(Symbols.chevron_right),
dense: true,
leading: Badge(
isLabelVisible: badgeCount != null && badgeCount > 0,
label: Text(badgeCount.toString()),
child: Icon(icon, size: 24),
),
title: Text(title).tr(),
onTap: onTap,
);
},
}).toList(),
);
},
),
const Divider(height: 1).padding(vertical: 8),
ListTile(
minTileHeight: 48,
leading: const Icon(Symbols.info),
trailing: const Icon(Symbols.chevron_right),
contentPadding: EdgeInsets.symmetric(horizontal: 24),
dense: true,
title: Text('about').tr(),
onTap: () {
context.pushNamed('about');
},
),
ListTile(
minTileHeight: 48,
leading: const Icon(Symbols.bug_report),
trailing: const Icon(Symbols.chevron_right),
contentPadding: EdgeInsets.symmetric(horizontal: 24),
title: Text('debugOptions').tr(),
dense: true,
onTap: () {
showModalBottomSheet(
useRootNavigator: true,
@@ -489,11 +471,11 @@ class AccountScreen extends HookConsumerWidget {
},
),
ListTile(
minTileHeight: 48,
leading: const Icon(Symbols.logout),
trailing: const Icon(Symbols.chevron_right),
contentPadding: EdgeInsets.symmetric(horizontal: 24),
title: Text('logout').tr(),
dense: true,
onTap: () async {
final ws = ref.watch(websocketStateProvider.notifier);
final apiClient = ref.watch(apiClientProvider);

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
@@ -28,10 +30,23 @@ final socialCreditHistoryNotifierProvider = AsyncNotifierProvider.autoDispose(
);
class SocialCreditHistoryNotifier
extends AsyncNotifier<List<SnSocialCreditRecord>>
extends AsyncNotifier<PaginationState<SnSocialCreditRecord>>
with AsyncPaginationController<SnSocialCreditRecord> {
static const int pageSize = 20;
@override
FutureOr<PaginationState<SnSocialCreditRecord>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnSocialCreditRecord>> fetch() async {
final client = ref.read(apiClientProvider);

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
@@ -14,14 +16,30 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:island/widgets/paging/pagination_list.dart';
import 'package:styled_widget/styled_widget.dart';
final levelingHistoryNotifierProvider = AsyncNotifierProvider.autoDispose(
LevelingHistoryNotifier.new,
);
final levelingHistoryNotifierProvider =
AsyncNotifierProvider.autoDispose<
LevelingHistoryNotifier,
PaginationState<SnExperienceRecord>
>(LevelingHistoryNotifier.new);
class LevelingHistoryNotifier extends AsyncNotifier<List<SnExperienceRecord>>
class LevelingHistoryNotifier
extends AsyncNotifier<PaginationState<SnExperienceRecord>>
with AsyncPaginationController<SnExperienceRecord> {
static const int pageSize = 20;
@override
FutureOr<PaginationState<SnExperienceRecord>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnExperienceRecord>> fetch() async {
final client = ref.read(apiClientProvider);

View File

@@ -476,9 +476,9 @@ class _AccountPublisherList extends StatelessWidget {
subtitle: Text(
publisher.bio.isNotEmpty
? publisher.bio
.split('\n')
.where((line) => line.trim().isNotEmpty)
.join('\n')
.split('\n')
.where((line) => line.trim().isNotEmpty)
.join('\n')
: 'descriptionNone'.tr(),
maxLines: 3,
overflow: TextOverflow.ellipsis,
@@ -550,16 +550,14 @@ class _AccountAction extends StatelessWidget {
),
),
onPressed: relationshipAction,
label:
Text(
accountRelationship.value == null
? 'addFriendShort'
: 'added',
).tr(),
icon:
accountRelationship.value == null
? const Icon(Symbols.person_add)
: const Icon(Symbols.person_check),
label: Text(
accountRelationship.value == null
? 'addFriendShort'
: 'added',
).tr(),
icon: accountRelationship.value == null
? const Icon(Symbols.person_add)
: const Icon(Symbols.person_check),
),
),
if (accountRelationship.value == null ||
@@ -579,16 +577,14 @@ class _AccountAction extends StatelessWidget {
),
),
onPressed: blockAction,
label:
Text(
accountRelationship.value == null
? 'blockUser'
: 'unblockUser',
).tr(),
icon:
accountRelationship.value == null
? const Icon(Symbols.block)
: const Icon(Symbols.person_cancel),
label: Text(
accountRelationship.value == null
? 'blockUser'
: 'unblockUser',
).tr(),
icon: accountRelationship.value == null
? const Icon(Symbols.block)
: const Icon(Symbols.person_cancel),
),
),
],
@@ -600,13 +596,12 @@ class _AccountAction extends StatelessWidget {
child: FilledButton.icon(
onPressed: directMessageAction,
icon: const Icon(Symbols.message),
label:
Text(
accountChat.value == null
? 'createDirectMessage'
: 'gotoDirectMessage',
maxLines: 1,
).tr(),
label: Text(
accountChat.value == null
? 'createDirectMessage'
: 'gotoDirectMessage',
maxLines: 1,
).tr(),
),
),
IconButton.filled(
@@ -664,7 +659,7 @@ Future<Color?> accountAppbarForcegroundColor(Ref ref, String uname) async {
if (account.profile.background == null) return null;
final colors = await ColorExtractionService.getColorsFromImage(
CloudImageWidget.provider(
fileId: account.profile.background!.id,
file: account.profile.background!,
serverUrl: ref.watch(serverUrlProvider),
),
);
@@ -683,7 +678,7 @@ Future<SnChatRoom?> accountDirectChat(Ref ref, String uname) async {
final account = await ref.watch(accountProvider(uname).future);
final apiClient = ref.watch(apiClientProvider);
try {
final resp = await apiClient.get("/sphere/chat/direct/${account.id}");
final resp = await apiClient.get("/messager/chat/direct/${account.id}");
return SnChatRoom.fromJson(resp.data);
} catch (err) {
if (err is DioException && err.response?.statusCode == 404) {
@@ -812,7 +807,7 @@ class AccountProfileScreen extends HookConsumerWidget {
try {
final client = ref.watch(apiClientProvider);
final resp = await client.post(
'/sphere/chat/direct',
'/messager/chat/direct',
data: {'related_user_id': account.value!.id},
);
final chat = SnChatRoom.fromJson(resp.data);
@@ -838,262 +833,256 @@ class AccountProfileScreen extends HookConsumerWidget {
final accountPublishers = ref.watch(accountPublishersProvider(data.id));
return AppScaffold(
isNoBackground: false,
appBar:
isWideScreen(context)
? AppBar(
foregroundColor: appbarColor.value,
leading: PageBackButton(
color: appbarColor.value,
appBar: isWideScreen(context)
? AppBar(
foregroundColor: appbarColor.value,
leading: PageBackButton(
color: appbarColor.value,
shadows: [appbarShadow],
),
title: Text(
data.nick,
style: TextStyle(
color:
appbarColor.value ??
Theme.of(context).appBarTheme.foregroundColor,
shadows: [appbarShadow],
),
title: Text(
data.nick,
style: TextStyle(
color:
appbarColor.value ??
Theme.of(context).appBarTheme.foregroundColor,
shadows: [appbarShadow],
),
),
)
: null,
body:
isWideScreen(context)
? Row(
children: [
Flexible(
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: _AccountBasicInfo(
data: data,
uname: name,
accountDeveloper: accountDeveloper,
).padding(horizontal: 4, top: 20),
),
if (data.badges.isNotEmpty)
SliverToBoxAdapter(
child: Card(
child: BadgeList(
badges: data.badges,
).padding(horizontal: 26, vertical: 20),
).padding(left: 2, right: 4),
),
SliverToBoxAdapter(
child: Column(
spacing: 12,
children: [
LevelingProgressCard(
level: data.profile.level,
experience: data.profile.experience,
progress: data.profile.levelingProgress,
).padding(left: 2, right: 4),
if (data.profile.verification != null)
Card(
margin: EdgeInsets.zero,
child: VerificationStatusCard(
mark: data.profile.verification!,
),
),
],
).padding(horizontal: 4, top: 8),
),
SliverToBoxAdapter(
child: _AccountProfileBio(
data: data,
).padding(top: 4),
),
if (data.profile.links.isNotEmpty)
SliverToBoxAdapter(
child: _AccountProfileLinks(data: data),
),
if (data.contacts.any((c) => c.isPublic))
SliverToBoxAdapter(
child: _AccountProfileContacts(data: data),
),
SliverToBoxAdapter(
child: _AccountProfileDetail(data: data),
),
],
),
),
Flexible(
child: CustomScrollView(
slivers: [
SliverGap(18),
SliverToBoxAdapter(
child: ActivityPresenceWidget(
uname: name,
).padding(horizontal: 4, top: 4, bottom: 4),
),
SliverToBoxAdapter(
child: _AccountPublisherList(
publishers: accountPublishers.value ?? [],
),
),
if (user.value != null && !isCurrentUser)
SliverToBoxAdapter(
child: _AccountAction(
data: data,
accountRelationship: accountRelationship,
accountChat: accountChat,
relationshipAction: relationshipAction,
blockAction: blockAction,
directMessageAction: directMessageAction,
),
),
),
)
: null,
body: isWideScreen(context)
? Row(
children: [
Flexible(
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: _AccountBasicInfo(
data: data,
uname: name,
accountDeveloper: accountDeveloper,
).padding(horizontal: 4, top: 20),
),
if (data.badges.isNotEmpty)
SliverToBoxAdapter(
child: Card(
child: FortuneGraphWidget(
events: accountEvents,
eventCalandarUser: data.name,
margin: EdgeInsets.zero,
),
child: BadgeList(
badges: data.badges,
).padding(horizontal: 26, vertical: 20),
).padding(left: 2, right: 4),
),
SliverToBoxAdapter(
child: Column(
spacing: 12,
children: [
LevelingProgressCard(
level: data.profile.level,
experience: data.profile.experience,
progress: data.profile.levelingProgress,
).padding(left: 2, right: 4),
if (data.profile.verification != null)
Card(
margin: EdgeInsets.zero,
child: VerificationStatusCard(
mark: data.profile.verification!,
),
),
],
).padding(horizontal: 4, top: 8),
),
SliverToBoxAdapter(
child: _AccountProfileBio(
data: data,
).padding(top: 4),
),
if (data.profile.links.isNotEmpty)
SliverToBoxAdapter(
child: _AccountProfileLinks(data: data),
),
if (data.contacts.any((c) => c.isPublic))
SliverToBoxAdapter(
child: _AccountProfileContacts(data: data),
),
SliverToBoxAdapter(
child: _AccountProfileDetail(data: data),
),
],
),
),
Flexible(
child: CustomScrollView(
slivers: [
SliverGap(18),
SliverToBoxAdapter(
child: ActivityPresenceWidget(
uname: name,
).padding(horizontal: 4, top: 4, bottom: 4),
),
SliverToBoxAdapter(
child: _AccountPublisherList(
publishers: accountPublishers.value ?? [],
),
),
if (user.value != null && !isCurrentUser)
SliverToBoxAdapter(
child: _AccountAction(
data: data,
accountRelationship: accountRelationship,
accountChat: accountChat,
relationshipAction: relationshipAction,
blockAction: blockAction,
directMessageAction: directMessageAction,
),
),
],
),
),
],
).padding(horizontal: 24)
: CustomScrollView(
slivers: [
SliverAppBar(
foregroundColor: appbarColor.value,
expandedHeight: 180,
pinned: true,
leading: PageBackButton(
color: appbarColor.value,
shadows: [appbarShadow],
),
flexibleSpace: Stack(
children: [
Positioned.fill(
child:
data.profile.background?.id != null
? CloudImageWidget(
file: data.profile.background,
)
: Container(
color:
Theme.of(
context,
).appBarTheme.backgroundColor,
),
),
FlexibleSpaceBar(
title: Text(
data.nick,
style: TextStyle(
color:
appbarColor.value ??
Theme.of(
context,
).appBarTheme.foregroundColor,
shadows: [appbarShadow],
),
SliverToBoxAdapter(
child: Card(
child: FortuneGraphWidget(
events: accountEvents,
eventCalandarUser: data.name,
margin: EdgeInsets.zero,
),
),
],
),
),
],
),
SliverToBoxAdapter(
child: _AccountBasicInfo(
data: data,
uname: name,
accountDeveloper: accountDeveloper,
).padding(horizontal: 4, top: 8),
),
],
).padding(horizontal: 24)
: CustomScrollView(
slivers: [
SliverAppBar(
foregroundColor: appbarColor.value,
expandedHeight: 180,
pinned: true,
leading: PageBackButton(
color: appbarColor.value,
shadows: [appbarShadow],
),
if (data.badges.isNotEmpty)
SliverToBoxAdapter(
child: Card(
child: BadgeList(
badges: data.badges,
).padding(horizontal: 26, vertical: 20),
).padding(horizontal: 4),
),
SliverToBoxAdapter(
child: Column(
children: [
LevelingProgressCard(
level: data.profile.level,
experience: data.profile.experience,
progress: data.profile.levelingProgress,
).padding(top: 8, horizontal: 8, bottom: 4),
if (data.profile.verification != null)
Card(
child: VerificationStatusCard(
mark: data.profile.verification!,
),
).padding(horizontal: 4),
],
),
flexibleSpace: Stack(
children: [
Positioned.fill(
child: data.profile.background?.id != null
? CloudImageWidget(
file: data.profile.background,
)
: Container(
color: Theme.of(
context,
).appBarTheme.backgroundColor,
),
),
FlexibleSpaceBar(
title: Text(
data.nick,
style: TextStyle(
color:
appbarColor.value ??
Theme.of(
context,
).appBarTheme.foregroundColor,
shadows: [appbarShadow],
),
),
),
],
),
SliverToBoxAdapter(
child: _AccountProfileBio(
data: data,
).padding(horizontal: 4),
),
if (data.profile.links.isNotEmpty)
SliverToBoxAdapter(
child: _AccountProfileLinks(
data: data,
).padding(horizontal: 4),
),
if (data.contacts.any((c) => c.isPublic))
SliverToBoxAdapter(
child: _AccountProfileContacts(
data: data,
).padding(horizontal: 4),
),
SliverToBoxAdapter(
child: ActivityPresenceWidget(
uname: name,
).padding(horizontal: 8, top: 4, bottom: 4),
),
SliverToBoxAdapter(
child: _AccountPublisherList(
publishers: accountPublishers.value ?? [],
).padding(horizontal: 4),
),
SliverToBoxAdapter(
child: _AccountProfileDetail(
data: data,
).padding(horizontal: 4),
),
if (user.value != null && !isCurrentUser)
SliverToBoxAdapter(
child: _AccountAction(
data: data,
accountRelationship: accountRelationship,
accountChat: accountChat,
relationshipAction: relationshipAction,
blockAction: blockAction,
directMessageAction: directMessageAction,
).padding(horizontal: 4),
),
),
SliverToBoxAdapter(
child: _AccountBasicInfo(
data: data,
uname: name,
accountDeveloper: accountDeveloper,
).padding(horizontal: 4, top: 8),
),
if (data.badges.isNotEmpty)
SliverToBoxAdapter(
child: Card(
child: FortuneGraphWidget(
events: accountEvents,
eventCalandarUser: data.name,
),
child: BadgeList(
badges: data.badges,
).padding(horizontal: 26, vertical: 20),
).padding(horizontal: 4),
),
],
),
SliverToBoxAdapter(
child: Column(
children: [
LevelingProgressCard(
level: data.profile.level,
experience: data.profile.experience,
progress: data.profile.levelingProgress,
).padding(top: 8, horizontal: 8, bottom: 4),
if (data.profile.verification != null)
Card(
child: VerificationStatusCard(
mark: data.profile.verification!,
),
).padding(horizontal: 4),
],
),
),
SliverToBoxAdapter(
child: _AccountProfileBio(
data: data,
).padding(horizontal: 4),
),
if (data.profile.links.isNotEmpty)
SliverToBoxAdapter(
child: _AccountProfileLinks(
data: data,
).padding(horizontal: 4),
),
if (data.contacts.any((c) => c.isPublic))
SliverToBoxAdapter(
child: _AccountProfileContacts(
data: data,
).padding(horizontal: 4),
),
SliverToBoxAdapter(
child: ActivityPresenceWidget(
uname: name,
).padding(horizontal: 8, top: 4, bottom: 4),
),
SliverToBoxAdapter(
child: _AccountPublisherList(
publishers: accountPublishers.value ?? [],
).padding(horizontal: 4),
),
SliverToBoxAdapter(
child: _AccountProfileDetail(
data: data,
).padding(horizontal: 4),
),
if (user.value != null && !isCurrentUser)
SliverToBoxAdapter(
child: _AccountAction(
data: data,
accountRelationship: accountRelationship,
accountChat: accountChat,
relationshipAction: relationshipAction,
blockAction: blockAction,
directMessageAction: directMessageAction,
).padding(horizontal: 4),
),
SliverToBoxAdapter(
child: Card(
child: FortuneGraphWidget(
events: accountEvents,
eventCalandarUser: data.name,
),
).padding(horizontal: 4),
),
],
),
);
},
error:
(error, stackTrace) => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: Center(child: Text(error.toString())),
),
loading:
() => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: Center(child: CircularProgressIndicator()),
),
error: (error, stackTrace) => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: Center(child: Text(error.toString())),
),
loading: () => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: Center(child: CircularProgressIndicator()),
),
);
}
}

View File

@@ -212,7 +212,7 @@ final class AccountAppbarForcegroundColorProvider
}
String _$accountAppbarForcegroundColorHash() =>
r'127fcc7fd6ec6a41ac4a6975276b5271aa4fa7d0';
r'59e0049a5158ea653f0afd724df9ff2312b90050';
final class AccountAppbarForcegroundColorFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<Color?>, String> {
@@ -287,7 +287,7 @@ final class AccountDirectChatProvider
}
}
String _$accountDirectChatHash() => r'149ea3a3730672cfbbb8c16fe1f2caa0bb9f0e17';
String _$accountDirectChatHash() => r'71bc9eed34a436a3743e8ef87f7aaae861fc5746';
final class AccountDirectChatFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<SnChatRoom?>, String> {

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -29,12 +31,28 @@ Future<List<SnRelationship>> sentFriendRequest(Ref ref) async {
.toList();
}
final relationshipListNotifierProvider = AsyncNotifierProvider.autoDispose(
RelationshipListNotifier.new,
);
final relationshipListNotifierProvider =
AsyncNotifierProvider.autoDispose<
RelationshipListNotifier,
PaginationState<SnRelationship>
>(RelationshipListNotifier.new);
class RelationshipListNotifier extends AsyncNotifier<List<SnRelationship>>
class RelationshipListNotifier
extends AsyncNotifier<PaginationState<SnRelationship>>
with AsyncPaginationController<SnRelationship> {
@override
FutureOr<PaginationState<SnRelationship>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnRelationship>> fetch() async {
final client = ref.read(apiClientProvider);

View File

@@ -0,0 +1,2 @@
export 'list.dart';
export 'search.dart';

View File

@@ -0,0 +1,151 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/activitypub.dart';
import 'package:island/services/activitypub_service.dart';
import 'package:island/widgets/activitypub/user_list_item.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/extended_refresh_indicator.dart';
import 'package:material_symbols_icons/symbols.dart';
enum ActivityPubListType { following, followers }
class ApListScreen extends HookConsumerWidget {
final ActivityPubListType type;
const ApListScreen({super.key, required this.type});
@override
Widget build(BuildContext context, WidgetRef ref) {
final users = useState<List<SnActivityPubUser>>([]);
final isLoading = useState(true);
final followingUris = useState<Set<String>>({});
final isLoadingAction = useState<String?>(null);
Future<void> loadUsers() async {
isLoading.value = true;
try {
final service = ref.read(activityPubServiceProvider);
final result = type == ActivityPubListType.following
? await service.getFollowing()
: await service.getFollowers();
users.value = result;
followingUris.value = result.map((user) => user.actorUri).toSet();
} catch (err) {
showErrorAlert(err);
} finally {
isLoading.value = false;
}
}
Future<void> handleFollow(SnActivityPubUser user) async {
isLoadingAction.value = user.actorUri;
try {
final service = ref.read(activityPubServiceProvider);
await service.followRemoteUser(user.actorUri);
followingUris.value = {...followingUris.value, user.actorUri};
showSnackBar('followedUser'.tr(args: ['@${user.username}']));
} catch (err) {
showErrorAlert(err);
} finally {
isLoadingAction.value = null;
}
}
Future<void> handleUnfollow(SnActivityPubUser user) async {
isLoadingAction.value = user.actorUri;
try {
final service = ref.read(activityPubServiceProvider);
await service.unfollowRemoteUser(user.actorUri);
followingUris.value = followingUris.value
.where((uri) => uri != user.actorUri)
.toSet();
if (type == ActivityPubListType.following) {
users.value = users.value
.where((u) => u.actorUri != user.actorUri)
.toList();
}
showSnackBar('unfollowedUser'.tr(args: ['@${user.username}']));
} catch (err) {
showErrorAlert(err);
} finally {
isLoadingAction.value = null;
}
}
final title = type == ActivityPubListType.following
? 'following'.tr()
: 'followers'.tr();
return AppScaffold(
appBar: AppBar(
title: Text(title),
elevation: 0,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: loadUsers,
tooltip: 'refresh'.tr(),
),
],
),
body: isLoading.value
? const Center(child: CircularProgressIndicator())
: users.value.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Symbols.group,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
type == ActivityPubListType.following
? 'followingEmpty'.tr()
: 'followersEmpty'.tr(),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Text(
'followingEmptyHint'.tr(),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
)
: ExtendedRefreshIndicator(
onRefresh: loadUsers,
child: ListView.separated(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: users.value.length,
separatorBuilder: (context, index) => const Divider(height: 1),
itemBuilder: (context, index) {
final user = users.value[index];
final isFollowing = followingUris.value.contains(
user.actorUri,
);
final isLoadingUser = isLoadingAction.value == user.actorUri;
return ActivityPubUserListItem(
user: user,
isFollowing: isFollowing,
isLoading: isLoadingUser,
onFollow: type == ActivityPubListType.followers
? () => handleFollow(user)
: null,
onUnfollow: type == ActivityPubListType.following
? () => handleUnfollow(user)
: null,
);
},
),
),
);
}
}

View File

@@ -0,0 +1,180 @@
import 'dart:async';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/activitypub.dart';
import 'package:island/services/activitypub_service.dart';
import 'package:island/widgets/activitypub/actor_list_item.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/extended_refresh_indicator.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart';
class ApSearchScreen extends HookConsumerWidget {
const ApSearchScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final searchController = useTextEditingController();
final debounce = useMemoized(() => const Duration(milliseconds: 500));
final debounceTimer = useRef<Timer?>(null);
final searchResults = useState<List<SnActivityPubActor>>([]);
final isSearching = useState(false);
useEffect(() {
return () {
searchController.dispose();
debounceTimer.value?.cancel();
};
}, []);
Future<void> performSearch(String query) async {
if (query.trim().isEmpty) {
searchResults.value = [];
return;
}
isSearching.value = true;
try {
final service = ref.read(activityPubServiceProvider);
final results = await service.searchUsers(query);
searchResults.value = results;
} catch (err) {
showErrorAlert(err);
} finally {
isSearching.value = false;
}
}
void onSearchChanged(String query) {
if (debounceTimer.value?.isActive ?? false) {
debounceTimer.value!.cancel();
}
debounceTimer.value = Timer(debounce, () {
performSearch(query);
});
}
void updateActorIsFollowing(String actorId, bool isFollowing) {
searchResults.value = searchResults.value
.map(
(a) => a.id == actorId ? a.copyWith(isFollowing: isFollowing) : a,
)
.toList();
}
Future<void> handleFollow(SnActivityPubActor actor) async {
try {
updateActorIsFollowing(actor.id, true);
final service = ref.read(activityPubServiceProvider);
await service.followRemoteUser(actor.uri);
showSnackBar(
'followedUser'.tr(
args: [
'${actor.username?.isNotEmpty ?? false ? actor.username : actor.displayName}',
],
),
);
} catch (err) {
showErrorAlert(err);
updateActorIsFollowing(actor.id, false);
}
}
Future<void> handleUnfollow(SnActivityPubActor actor) async {
try {
updateActorIsFollowing(actor.id, false);
final service = ref.read(activityPubServiceProvider);
await service.unfollowRemoteUser(actor.uri);
showSnackBar(
'unfollowedUser'.tr(
args: [
'${actor.username?.isNotEmpty ?? false ? actor.username : actor.displayName}',
],
),
);
} catch (err) {
showErrorAlert(err);
updateActorIsFollowing(actor.id, true);
}
}
return AppScaffold(
isNoBackground: false,
appBar: AppBar(title: Text('searchFediverse'.tr()), elevation: 0),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: SearchBar(
controller: searchController,
hintText: 'searchFediverseHint'.tr(
args: ['@username@instance.com'],
),
leading: const Icon(Symbols.search).padding(horizontal: 24),
onChanged: onSearchChanged,
onSubmitted: (value) {
onSearchChanged(value);
performSearch(value);
},
),
),
Expanded(
child: isSearching.value
? const Center(child: CircularProgressIndicator())
: searchResults.value.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Symbols.search,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
if (searchController.text.isEmpty)
Text(
'searchFediverseEmpty'.tr(),
style: Theme.of(context).textTheme.titleMedium,
)
else
Text(
'searchFediverseNoResults'.tr(),
style: Theme.of(context).textTheme.titleMedium,
),
],
),
)
: ExtendedRefreshIndicator(
onRefresh: () => performSearch(searchController.text),
child: ListView.separated(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: searchResults.value.length,
separatorBuilder: (context, index) => const Gap(8),
itemBuilder: (context, index) {
final actor = searchResults.value[index];
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560),
child: ApActorListItem(
actor: actor,
isFollowing: actor.isFollowing ?? false,
isLoading: false,
onFollow: () => handleFollow(actor),
onUnfollow: () => handleUnfollow(actor),
),
),
);
},
),
),
),
],
),
);
}
}

View File

@@ -69,11 +69,11 @@ class CallScreen extends HookConsumerWidget {
callState.isConnected
? formatDuration(callState.duration)
: (switch (callNotifier.room?.connectionState) {
ConnectionState.connected => 'connected',
ConnectionState.connecting => 'connecting',
ConnectionState.reconnecting => 'reconnecting',
_ => 'disconnected',
}).tr(),
ConnectionState.connected => 'connected',
ConnectionState.connecting => 'connecting',
ConnectionState.reconnecting => 'reconnecting',
_ => 'disconnected',
}).tr(),
style: const TextStyle(fontSize: 14),
),
],
@@ -92,40 +92,40 @@ class CallScreen extends HookConsumerWidget {
),
],
),
body:
callState.error != null
? Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 320),
child: Column(
children: [
const Icon(Symbols.error_outline, size: 48),
const Gap(4),
Text(
callState.error!,
textAlign: TextAlign.center,
style: const TextStyle(color: Color(0xFF757575)),
),
const Gap(8),
TextButton(
onPressed: () {
callNotifier.disconnect();
callNotifier.dispose();
callNotifier.joinRoom(room);
},
child: Text('retry').tr(),
),
],
),
body: callState.error != null
? Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 320),
child: Column(
children: [
const Icon(Symbols.error_outline, size: 48),
const Gap(4),
Text(
callState.error!,
textAlign: TextAlign.center,
style: const TextStyle(color: Color(0xFF757575)),
),
const Gap(8),
TextButton(
onPressed: () {
callNotifier.disconnect();
callNotifier.dispose();
callNotifier.joinRoom(room);
},
child: Text('retry').tr(),
),
],
),
)
: Column(
children: [
Expanded(child: CallContent()),
CallControlsBar(),
Gap(MediaQuery.of(context).padding.bottom + 16),
],
),
)
: Column(
children: [
const SizedBox(width: double.infinity),
Expanded(child: CallContent()),
CallControlsBar(popOnLeaves: true),
Gap(MediaQuery.of(context).padding.bottom + 16),
],
),
);
}
}

View File

@@ -9,15 +9,17 @@ import 'package:island/models/chat.dart';
import 'package:island/pods/chat/chat_summary.dart';
import 'package:island/pods/network.dart';
import 'package:island/pods/userinfo.dart';
import 'package:island/screens/chat/chat_form.dart';
import 'package:island/screens/realm/realms.dart';
import 'package:island/services/event_bus.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/account/account_picker.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/chat_room_widgets.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:island/widgets/navigation/fab_menu.dart';
import 'package:island/widgets/extended_refresh_indicator.dart';
import 'package:island/widgets/response.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart';
@@ -72,123 +74,155 @@ class ChatListBodyWidget extends HookConsumerWidget {
.where((item) => !item.isPinned)
.toList();
return RefreshIndicator(
return ExtendedRefreshIndicator(
onRefresh: () => Future.sync(() {
ref.invalidate(chatRoomJoinedProvider);
}),
child: Column(
children: [
// Always show pinned chats in their own section
if (pinnedItems.isNotEmpty)
ExpansionTile(
backgroundColor: Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.5),
collapsedBackgroundColor: Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.5),
title: Text('pinnedChatRoom'.tr()),
leading: const Icon(Symbols.keep, fill: 1),
tilePadding: const EdgeInsets.symmetric(horizontal: 24),
initiallyExpanded: true,
children: [
for (final item in pinnedItems)
ChatRoomListTile(
room: item,
isDirect: item.type == 1,
onTap: () {
if (isWideScreen(context)) {
context.replaceNamed(
'chatRoom',
pathParameters: {'id': item.id},
);
} else {
context.pushNamed(
'chatRoom',
pathParameters: {'id': item.id},
);
child: Theme(
data: Theme.of(
context,
).copyWith(dividerColor: Colors.transparent),
child: Column(
children: [
// Always show pinned chats in their own section
if (pinnedItems.isNotEmpty)
ExpansionTile(
backgroundColor: Theme.of(context)
.colorScheme
.surfaceContainerHighest
.withOpacity(0.5),
collapsedBackgroundColor: Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.5),
title: Text('pinnedChatRoom'.tr()),
leading: const Icon(Symbols.keep, fill: 1),
tilePadding: const EdgeInsets.symmetric(
horizontal: 24,
),
initiallyExpanded: true,
children: [
for (final item in pinnedItems)
ChatRoomListTile(
room: item,
isDirect: item.type == 1,
onTap: () {
if (isWideScreen(context)) {
context.replaceNamed(
'chatRoom',
pathParameters: {'id': item.id},
);
} else {
context.pushNamed(
'chatRoom',
pathParameters: {'id': item.id},
);
}
},
),
],
),
Expanded(
child: Consumer(
builder: (context, ref, _) {
final summaries =
ref
.watch(chatSummaryProvider)
.whenData((data) => data)
.value ??
{};
if (settings.groupedChatList &&
selectedTab.value == 0) {
// Group by realm (include both pinned and unpinned)
final realmGroups = <String?, List<SnChatRoom>>{};
final ungrouped = <SnChatRoom>[];
for (final item in filteredItems) {
if (item.realmId != null) {
realmGroups
.putIfAbsent(item.realmId, () => [])
.add(item);
} else if (!item.isPinned) {
// Only unpinned chats without realm go to ungrouped
ungrouped.add(item);
}
},
),
],
),
Expanded(
child: Consumer(
builder: (context, ref, _) {
final summaries =
ref
.watch(chatSummaryProvider)
.whenData((data) => data)
.value ??
{};
if (settings.groupedChatList &&
selectedTab.value == 0) {
// Group by realm (include both pinned and unpinned)
final realmGroups = <String?, List<SnChatRoom>>{};
final ungrouped = <SnChatRoom>[];
for (final item in filteredItems) {
if (item.realmId != null) {
realmGroups
.putIfAbsent(item.realmId, () => [])
.add(item);
} else if (!item.isPinned) {
// Only unpinned chats without realm go to ungrouped
ungrouped.add(item);
}
}
final children = <Widget>[];
final children = <Widget>[];
// Add realm groups
for (final entry in realmGroups.entries) {
final rooms = entry.value;
final realm = rooms.first.realm;
final realmName = realm?.name ?? 'Unknown Realm';
// Add realm groups
for (final entry in realmGroups.entries) {
final rooms = entry.value;
final realm = rooms.first.realm;
final realmName =
realm?.name ?? 'Unknown Realm';
// Calculate total unread count for this realm
final totalUnread = rooms.fold<int>(
0,
(sum, room) =>
sum +
(summaries[room.id]?.unreadCount ?? 0),
);
// Calculate total unread count for this realm
final totalUnread = rooms.fold<int>(
0,
(sum, room) =>
sum +
(summaries[room.id]?.unreadCount ?? 0),
);
children.add(
ExpansionTile(
backgroundColor: Theme.of(context)
.colorScheme
.surfaceContainer
.withOpacity(0.5),
collapsedBackgroundColor: Theme.of(context)
.colorScheme
.surfaceContainer
.withOpacity(0.5),
title: Row(
children: [
Expanded(child: Text(realmName)),
Badge(
isLabelVisible: totalUnread > 0,
label: Text(totalUnread.toString()),
backgroundColor: Theme.of(
context,
).colorScheme.primary,
textColor: Theme.of(
context,
).colorScheme.onPrimary,
),
],
children.add(
ExpansionTile(
backgroundColor: Theme.of(context)
.colorScheme
.surfaceContainerHighest
.withOpacity(0.5),
collapsedBackgroundColor:
Colors.transparent,
title: Row(
children: [
Expanded(child: Text(realmName)),
Badge(
isLabelVisible: totalUnread > 0,
label: Text(totalUnread.toString()),
backgroundColor: Theme.of(
context,
).colorScheme.primary,
textColor: Theme.of(
context,
).colorScheme.onPrimary,
),
],
),
leading: ProfilePictureWidget(
file: realm?.picture,
radius: 16,
),
tilePadding: const EdgeInsets.only(
left: 20,
right: 24,
),
children: rooms.map((room) {
return ChatRoomListTile(
room: room,
isDirect: room.type == 1,
onTap: () {
if (isWideScreen(context)) {
context.replaceNamed(
'chatRoom',
pathParameters: {'id': room.id},
);
} else {
context.pushNamed(
'chatRoom',
pathParameters: {'id': room.id},
);
}
},
);
}).toList(),
),
leading: ProfilePictureWidget(
file: realm?.picture,
radius: 16,
),
tilePadding: const EdgeInsets.only(
left: 20,
right: 24,
),
children: rooms.map((room) {
);
}
// Add ungrouped chats
if (ungrouped.isNotEmpty) {
children.addAll(
ungrouped.map((room) {
return ChatRoomListTile(
room: room,
isDirect: room.type == 1,
@@ -206,80 +240,55 @@ class ChatListBodyWidget extends HookConsumerWidget {
}
},
);
}).toList(),
),
);
}
}),
);
}
// Add ungrouped chats
if (ungrouped.isNotEmpty) {
children.addAll(
ungrouped.map((room) {
return ListView(
padding: EdgeInsets.only(bottom: 96),
children: children,
);
} else {
// Normal list view
return SuperListView.builder(
padding: EdgeInsets.only(bottom: 96),
itemCount: unpinnedItems
.where(
(item) =>
selectedTab.value == 0 ||
(selectedTab.value == 1 &&
item.type == 1) ||
(selectedTab.value == 2 &&
item.type != 1),
)
.length,
itemBuilder: (context, index) {
final item = unpinnedItems[index];
return ChatRoomListTile(
room: room,
isDirect: room.type == 1,
room: item,
isDirect: item.type == 1,
onTap: () {
if (isWideScreen(context)) {
context.replaceNamed(
'chatRoom',
pathParameters: {'id': room.id},
pathParameters: {'id': item.id},
);
} else {
context.pushNamed(
'chatRoom',
pathParameters: {'id': room.id},
pathParameters: {'id': item.id},
);
}
},
);
}),
},
);
}
return ListView(
padding: EdgeInsets.only(bottom: 96),
children: children,
);
} else {
// Normal list view
return SuperListView.builder(
padding: EdgeInsets.only(bottom: 96),
itemCount: unpinnedItems
.where(
(item) =>
selectedTab.value == 0 ||
(selectedTab.value == 1 &&
item.type == 1) ||
(selectedTab.value == 2 &&
item.type != 1),
)
.length,
itemBuilder: (context, index) {
final item = unpinnedItems[index];
return ChatRoomListTile(
room: item,
isDirect: item.type == 1,
onTap: () {
if (isWideScreen(context)) {
context.replaceNamed(
'chatRoom',
pathParameters: {'id': item.id},
);
} else {
context.pushNamed(
'chatRoom',
pathParameters: {'id': item.id},
);
}
},
);
},
);
}
},
},
),
),
),
],
],
),
),
);
},
@@ -372,23 +381,6 @@ class ChatListScreen extends HookConsumerWidget {
};
}, [tabController]);
useEffect(() {
// Set FAB type to chat
final fabMenuNotifier = ref.read(fabMenuTypeProvider.notifier);
Future(() {
fabMenuNotifier.setMenuType(FabMenuType.chat);
});
return () {
// Clean up: reset FAB type to main
final fabMenu = ref.read(fabMenuTypeProvider);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (fabMenu == FabMenuType.chat) {
fabMenuNotifier.setMenuType(FabMenuType.main);
}
});
};
}, []);
if (isAside) {
return Card(
margin: EdgeInsets.zero,
@@ -461,8 +453,78 @@ class ChatListScreen extends HookConsumerWidget {
final appbarFeColor = Theme.of(context).appBarTheme.foregroundColor;
final userInfo = ref.watch(userInfoProvider);
return AppScaffold(
extendBody: false, // Prevent conflicts with tabs navigation
floatingActionButton: userInfo.value != null
? FloatingActionButton(
child: const Icon(Symbols.add),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
const Gap(40),
ListTile(
title: const Text('createChatRoom').tr(),
leading: const Icon(Symbols.add),
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
onTap: () {
showModalBottomSheet(
context: context,
useRootNavigator: true,
isScrollControlled: true,
builder: (context) => const EditChatScreen(),
).then((value) {
if (value != null) {
eventBus.fire(const ChatRoomsRefreshEvent());
}
});
},
),
ListTile(
title: const Text('createDirectMessage').tr(),
leading: const Icon(Symbols.person),
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
onTap: () async {
final result = await showModalBottomSheet(
context: context,
useRootNavigator: true,
isScrollControlled: true,
builder: (context) => const AccountPickerSheet(),
);
if (result == null) return;
final client = ref.read(apiClientProvider);
try {
await client.post(
'/messager/chat/direct',
data: {'related_user_id': result.id},
);
eventBus.fire(const ChatRoomsRefreshEvent());
} catch (err) {
showErrorAlert(err);
}
},
),
const Gap(16),
],
),
);
},
).padding(
bottom:
(isWideScreen(context) ? 0 : 56) +
MediaQuery.of(context).padding.bottom,
)
: null,
appBar: AppBar(
flexibleSpace: Container(
height: 48,
@@ -560,7 +622,9 @@ class _ChatInvitesSheet extends HookConsumerWidget {
Future<void> acceptInvite(SnChatMember invite) async {
try {
final client = ref.read(apiClientProvider);
await client.post('/sphere/chat/invites/${invite.chatRoom!.id}/accept');
await client.post(
'/messager/chat/invites/${invite.chatRoom!.id}/accept',
);
ref.invalidate(chatroomInvitesProvider);
ref.invalidate(chatRoomJoinedProvider);
} catch (err) {
@@ -572,7 +636,7 @@ class _ChatInvitesSheet extends HookConsumerWidget {
try {
final client = ref.read(apiClientProvider);
await client.post(
'/sphere/chat/invites/${invite.chatRoom!.id}/decline',
'/messager/chat/invites/${invite.chatRoom!.id}/decline',
);
ref.invalidate(chatroomInvitesProvider);
} catch (err) {

View File

@@ -97,14 +97,10 @@ class EditChatScreen extends HookConsumerWidget {
submitting.value = true;
try {
final cloudFile =
await FileUploader.createCloudFile(
ref: ref,
fileData: UniversalFile(
data: result,
type: UniversalFileType.image,
),
).future;
final cloudFile = await FileUploader.createCloudFile(
ref: ref,
fileData: UniversalFile(data: result, type: UniversalFileType.image),
).future;
if (cloudFile == null) {
throw ArgumentError('Failed to upload the file...');
}
@@ -129,7 +125,7 @@ class EditChatScreen extends HookConsumerWidget {
try {
final client = ref.watch(apiClientProvider);
final resp = await client.request(
id == null ? '/sphere/chat' : '/sphere/chat/$id',
id == null ? '/messager/chat' : '/messager/chat/$id',
data: {
'name': nameController.text,
'description': descriptionController.text,
@@ -166,13 +162,12 @@ class EditChatScreen extends HookConsumerWidget {
GestureDetector(
child: Container(
color: Theme.of(context).colorScheme.surfaceContainerHigh,
child:
background.value != null
? CloudFileWidget(
item: background.value!,
fit: BoxFit.cover,
)
: const SizedBox.shrink(),
child: background.value != null
? CloudFileWidget(
item: background.value!,
fit: BoxFit.cover,
)
: const SizedBox.shrink(),
),
onTap: () {
setPicture('background');
@@ -208,8 +203,8 @@ class EditChatScreen extends HookConsumerWidget {
borderRadius: BorderRadius.circular(12),
),
),
onTapOutside:
(_) => FocusManager.instance.primaryFocus?.unfocus(),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
),
const SizedBox(height: 16),
TextFormField(
@@ -223,8 +218,8 @@ class EditChatScreen extends HookConsumerWidget {
),
minLines: 3,
maxLines: null,
onTapOutside:
(_) => FocusManager.instance.primaryFocus?.unfocus(),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
),
const SizedBox(height: 16),
DropdownButtonFormField<SnRealm>(
@@ -241,22 +236,20 @@ class EditChatScreen extends HookConsumerWidget {
child: Text('none'.tr()),
),
...joinedRealms.maybeWhen(
data:
(realms) => realms.map(
(realm) => DropdownMenuItem(
value: realm,
child: Text(realm.name),
),
),
data: (realms) => realms.map(
(realm) => DropdownMenuItem(
value: realm,
child: Text(realm.name),
),
),
orElse: () => [],
),
],
onChanged:
joinedRealms.isLoading
? null
: (SnRealm? value) {
currentRealm.value = value;
},
onChanged: joinedRealms.isLoading
? null
: (SnRealm? value) {
currentRealm.value = value;
},
),
const SizedBox(height: 16),
Card(

View File

@@ -65,8 +65,9 @@ class PublicRoomPreview extends HookConsumerWidget {
extentEstimation: (_, _) => 40,
itemBuilder: (context, index) {
final message = messageList[index];
final nextMessage =
index < messageList.length - 1 ? messageList[index + 1] : null;
final nextMessage = index < messageList.length - 1
? messageList[index + 1]
: null;
final isLastInGroup =
nextMessage == null ||
nextMessage.senderId != message.senderId ||
@@ -97,25 +98,23 @@ class PublicRoomPreview extends HookConsumerWidget {
SizedBox(
height: 26,
width: 26,
child:
(room.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId:
room.members!
.map((e) => e.account.profile.picture?.id)
.toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
child: (room.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId: room.members!
.map((e) => e.account.profile.picture?.id)
.toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
),
),
Text(
(room.type == 1 && room.name == null)
@@ -132,25 +131,23 @@ class PublicRoomPreview extends HookConsumerWidget {
SizedBox(
height: 26,
width: 26,
child:
(room.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId:
room.members!
.map((e) => e.account.profile.picture?.id)
.toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
child: (room.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId: room.members!
.map((e) => e.account.profile.picture?.id)
.toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
),
),
Text(
(room.type == 1 && room.name == null)
@@ -181,17 +178,14 @@ class PublicRoomPreview extends HookConsumerWidget {
children: [
Expanded(
child: messages.when(
data:
(messageList) =>
messageList.isEmpty
? Center(child: Text('No messages yet'.tr()))
: chatMessageListWidget(messageList),
data: (messageList) => messageList.isEmpty
? Center(child: Text('No messages yet'.tr()))
: chatMessageListWidget(messageList),
loading: () => const Center(child: CircularProgressIndicator()),
error:
(error, _) => ResponseErrorWidget(
error: error,
onRetry: () => messagesNotifier.loadInitial(),
),
error: (error, _) => ResponseErrorWidget(
error: error,
onRetry: () => messagesNotifier.loadInitial(),
),
),
),
// Join button at the bottom for public rooms
@@ -202,7 +196,7 @@ class PublicRoomPreview extends HookConsumerWidget {
try {
showLoadingModal(context);
final apiClient = ref.read(apiClientProvider);
await apiClient.post('/sphere/chat/${room.id}/members/me');
await apiClient.post('/messager/chat/${room.id}/members/me');
ref.invalidate(chatRoomIdentityProvider(id));
} catch (err) {
showErrorAlert(err);

View File

@@ -71,67 +71,64 @@ class ChatRoomScreen extends HookConsumerWidget {
return AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: Center(
child:
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 280),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
room.isCommunity == true
? Symbols.person_add
: Symbols.person_remove,
size: 36,
fill: 1,
).padding(bottom: 4),
Text('chatNotJoined').tr(),
if (room.isCommunity != true)
Text(
'chatUnableJoin',
textAlign: TextAlign.center,
).tr().bold()
else
FilledButton.tonalIcon(
onPressed: () async {
try {
showLoadingModal(context);
final apiClient = ref.read(apiClientProvider);
await apiClient.post(
'/sphere/chat/${room.id}/members/me',
);
ref.invalidate(chatRoomIdentityProvider(id));
} catch (err) {
showErrorAlert(err);
} finally {
if (context.mounted) {
hideLoadingModal(context);
}
}
},
label: Text('chatJoin').tr(),
icon: const Icon(Icons.add),
).padding(top: 8),
],
),
).center(),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 280),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
room.isCommunity == true
? Symbols.person_add
: Symbols.person_remove,
size: 36,
fill: 1,
).padding(bottom: 4),
Text('chatNotJoined').tr(),
if (room.isCommunity != true)
Text(
'chatUnableJoin',
textAlign: TextAlign.center,
).tr().bold()
else
FilledButton.tonalIcon(
onPressed: () async {
try {
showLoadingModal(context);
final apiClient = ref.read(apiClientProvider);
await apiClient.post(
'/messager/chat/${room.id}/members/me',
);
ref.invalidate(chatRoomIdentityProvider(id));
} catch (err) {
showErrorAlert(err);
} finally {
if (context.mounted) {
hideLoadingModal(context);
}
}
},
label: Text('chatJoin').tr(),
icon: const Icon(Icons.add),
).padding(top: 8),
],
),
).center(),
),
);
}
},
loading:
() => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: CircularProgressIndicator().center(),
),
error:
(error, _) => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: ResponseErrorWidget(
error: error,
onRetry: () => ref.refresh(chatRoomProvider(id)),
),
),
loading: () => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: CircularProgressIndicator().center(),
),
error: (error, _) => AppScaffold(
appBar: AppBar(leading: const PageBackButton()),
body: ResponseErrorWidget(
error: error,
onRetry: () => ref.refresh(chatRoomProvider(id)),
),
),
);
}
@@ -186,10 +183,9 @@ class ChatRoomScreen extends HookConsumerWidget {
case MessageItemAction.edit:
messageEditingTo.value = message.toRemoteMessage();
messageController.text = messageEditingTo.value?.content ?? '';
attachments.value =
messageEditingTo.value!.attachments
.map((e) => UniversalFile.fromAttachment(e))
.toList();
attachments.value = messageEditingTo.value!.attachments
.map((e) => UniversalFile.fromAttachment(e))
.toList();
case MessageItemAction.forward:
messageForwardingTo.value = message.toRemoteMessage();
case MessageItemAction.reply:
@@ -424,38 +420,37 @@ class ChatRoomScreen extends HookConsumerWidget {
label: Text('${(onlineCount.value ?? 0)}'),
textStyle: GoogleFonts.robotoMono(fontSize: 10),
textColor: Colors.white,
backgroundColor:
(onlineCount.value ?? 0) > 1 ? Colors.green : Colors.grey,
backgroundColor: (onlineCount.value ?? 0) > 1
? Colors.green
: Colors.grey,
offset: Offset(6, 14),
child: SizedBox(
height: 26,
width: 26,
child:
(room!.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId:
getValidMembers(
room.members!,
).map((e) => e.account.profile.picture?.id).toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
child: (room!.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId: getValidMembers(
room.members!,
).map((e) => e.account.profile.picture?.id).toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
),
),
),
Text(
(room.type == 1 && room.name == null)
? getValidMembers(
room.members!,
).map((e) => e.account.nick).join(', ')
room.members!,
).map((e) => e.account.nick).join(', ')
: room.name!,
).fontSize(15),
],
@@ -470,39 +465,38 @@ class ChatRoomScreen extends HookConsumerWidget {
isLabelVisible: (onlineCount.value ?? 0) > 1,
label: Text('${(onlineCount.value ?? 0)}'),
textStyle: GoogleFonts.robotoMono(fontSize: 10),
backgroundColor:
(onlineCount.value ?? 0) > 1 ? Colors.green : Colors.grey,
backgroundColor: (onlineCount.value ?? 0) > 1
? Colors.green
: Colors.grey,
textColor: Colors.white,
offset: Offset(6, 14),
child: SizedBox(
height: 28,
width: 28,
child:
(room!.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId:
getValidMembers(
room.members!,
).map((e) => e.account.profile.picture?.id).toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
child: (room!.type == 1 && room.picture?.id == null)
? SplitAvatarWidget(
filesId: getValidMembers(
room.members!,
).map((e) => e.account.profile.picture?.id).toList(),
)
: room.picture?.id != null
? ProfilePictureWidget(
fileId: room.picture?.id,
fallbackIcon: Symbols.chat,
)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
),
),
),
Text(
(room.type == 1 && room.name == null)
? getValidMembers(
room.members!,
).map((e) => e.account.nick).join(', ')
room.members!,
).map((e) => e.account.nick).join(', ')
: room.name!,
).fontSize(19),
],
@@ -531,11 +525,9 @@ class ChatRoomScreen extends HookConsumerWidget {
index: index,
scrollController: scrollController,
alignment: 0.5,
duration:
(estimatedDistance) => Duration(
milliseconds:
(estimatedDistance * 0.5).clamp(200, 800).toInt(),
),
duration: (estimatedDistance) => Duration(
milliseconds: (estimatedDistance * 0.5).clamp(200, 800).toInt(),
),
curve: (estimatedDistance) => Curves.easeOutCubic,
);
@@ -605,12 +597,11 @@ class ChatRoomScreen extends HookConsumerWidget {
final config = await showModalBottomSheet<AttachmentUploadConfig>(
context: context,
isScrollControlled: true,
builder:
(context) => AttachmentUploaderSheet(
ref: ref,
attachments: attachments.value,
index: index,
),
builder: (context) => AttachmentUploaderSheet(
ref: ref,
attachments: attachments.value,
index: index,
),
);
if (config == null) return;
@@ -621,22 +612,20 @@ class ChatRoomScreen extends HookConsumerWidget {
'chat-upload': {index: 0},
};
final cloudFile =
await FileUploader.createCloudFile(
ref: ref,
fileData: attachment,
poolId: config.poolId,
mode:
attachment.type == UniversalFileType.file
? FileUploadMode.generic
: FileUploadMode.mediaSafe,
onProgress: (progress, _) {
attachmentProgress.value = {
...attachmentProgress.value,
'chat-upload': {index: progress ?? 0.0},
};
},
).future;
final cloudFile = await FileUploader.createCloudFile(
ref: ref,
fileData: attachment,
poolId: config.poolId,
mode: attachment.type == UniversalFileType.file
? FileUploadMode.generic
: FileUploadMode.mediaSafe,
onProgress: (progress, _) {
attachmentProgress.value = {
...attachmentProgress.value,
'chat-upload': {index: progress ?? 0.0},
};
},
).future;
if (cloudFile == null) {
throw ArgumentError('Failed to upload the file...');
@@ -690,10 +679,9 @@ class ChatRoomScreen extends HookConsumerWidget {
extentEstimation: (_, _) => 40,
itemBuilder: (context, index) {
final message = messageList[index];
final nextMessage =
index < messageList.length - 1
? messageList[index + 1]
: null;
final nextMessage = index < messageList.length - 1
? messageList[index + 1]
: null;
final isLastInGroup =
nextMessage == null ||
nextMessage.senderId != message.senderId ||
@@ -718,15 +706,14 @@ class ChatRoomScreen extends HookConsumerWidget {
toggleSelectionMode: toggleSelectionMode,
toggleMessageSelection: toggleMessageSelection,
onMessageAction: onMessageAction,
onJump:
(messageId) => scrollToMessage(
messageId: messageId,
messageList: messageList,
messagesNotifier: messagesNotifier,
listController: listController,
scrollController: scrollController,
ref: ref,
),
onJump: (messageId) => scrollToMessage(
messageId: messageId,
messageList: messageList,
messagesNotifier: messagesNotifier,
listController: listController,
scrollController: scrollController,
ref: ref,
),
attachmentProgress: attachmentProgress.value,
disableAnimation: settings.disableAnimation,
roomOpenTime: roomOpenTime,
@@ -744,17 +731,14 @@ class ChatRoomScreen extends HookConsumerWidget {
automaticallyImplyLeading: false,
toolbarHeight: compactHeader ? null : 74,
title: chatRoom.when(
data:
(room) =>
compactHeader
? compactHeaderWidget(room)
: comfortHeaderWidget(room),
data: (room) => compactHeader
? compactHeaderWidget(room)
: comfortHeaderWidget(room),
loading: () => const Text('Loading...'),
error:
(err, _) => ResponseErrorWidget(
error: err,
onRetry: () => messagesNotifier.loadInitial(),
),
error: (err, _) => ResponseErrorWidget(
error: err,
onRetry: () => messagesNotifier.loadInitial(),
),
),
actions: [
chatRoom.when(
@@ -787,13 +771,11 @@ class ChatRoomScreen extends HookConsumerWidget {
index: index,
scrollController: scrollController,
alignment: 0.5,
duration:
(estimatedDistance) => Duration(
milliseconds:
(estimatedDistance * 0.5)
.clamp(200, 800)
.toInt(),
),
duration: (estimatedDistance) => Duration(
milliseconds: (estimatedDistance * 0.5)
.clamp(200, 800)
.toInt(),
),
curve: (estimatedDistance) => Curves.easeOutCubic,
);
} catch (e) {
@@ -819,38 +801,35 @@ class ChatRoomScreen extends HookConsumerWidget {
duration: const Duration(milliseconds: 300),
switchInCurve: Curves.easeOutCubic,
switchOutCurve: Curves.easeInCubic,
transitionBuilder: (
Widget child,
Animation<double> animation,
) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(0, 0.05),
end: Offset.zero,
).animate(animation),
child: FadeTransition(opacity: animation, child: child),
);
},
transitionBuilder:
(Widget child, Animation<double> animation) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(0, 0.05),
end: Offset.zero,
).animate(animation),
child: FadeTransition(
opacity: animation,
child: child,
),
);
},
child: messages.when(
data:
(messageList) =>
messageList.isEmpty
? Center(
key: const ValueKey('empty-messages'),
child: Text('No messages yet'.tr()),
)
: chatMessageListWidget(messageList),
loading:
() => const Center(
key: ValueKey('loading-messages'),
child: CircularProgressIndicator(),
),
error:
(error, _) => ResponseErrorWidget(
key: const ValueKey('error-messages'),
error: error,
onRetry: () => messagesNotifier.loadInitial(),
),
data: (messageList) => messageList.isEmpty
? Center(
key: const ValueKey('empty-messages'),
child: Text('No messages yet'.tr()),
)
: chatMessageListWidget(messageList),
loading: () => const Center(
key: ValueKey('loading-messages'),
child: CircularProgressIndicator(),
),
error: (error, _) => ResponseErrorWidget(
key: const ValueKey('error-messages'),
error: error,
onRetry: () => messagesNotifier.loadInitial(),
),
),
),
),
@@ -862,10 +841,8 @@ class ChatRoomScreen extends HookConsumerWidget {
right: 0,
top: 0,
child: chatRoom.when(
data:
(data) => CallOverlayBar(
room: data!,
).padding(horizontal: 8, top: 12),
data: (data) =>
CallOverlayBar(room: data!).padding(horizontal: 8, top: 12),
error: (_, _) => const SizedBox.shrink(),
loading: () => const SizedBox.shrink(),
),
@@ -903,35 +880,34 @@ class ChatRoomScreen extends HookConsumerWidget {
if (!isSelectionMode.value)
AnimatedBuilder(
animation: bottomGradientNotifier.value,
builder:
(context, child) => Positioned(
left: 0,
right: 0,
bottom: 0,
child: Opacity(
opacity: bottomGradientNotifier.value.value,
child: Container(
height: math.min(
MediaQuery.of(context).size.height * 0.1,
128,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.8),
Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.0),
],
),
),
builder: (context, child) => Positioned(
left: 0,
right: 0,
bottom: 0,
child: Opacity(
opacity: bottomGradientNotifier.value.value,
child: Container(
height: math.min(
MediaQuery.of(context).size.height * 0.1,
128,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.8),
Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.0),
],
),
),
),
),
),
),
// Chat Input positioned above gradient (higher z-index)
if (!isSelectionMode.value)
@@ -940,74 +916,73 @@ class ChatRoomScreen extends HookConsumerWidget {
right: 0,
bottom: 0, // At the very bottom, above gradient
child: chatRoom.when(
data:
(room) => Column(
key: inputKey,
mainAxisSize: MainAxisSize.min,
children: [
ChatInput(
messageController: messageController,
chatRoom: room!,
onSend: sendMessage,
onClear: () {
if (messageEditingTo.value != null) {
attachments.value.clear();
messageController.clear();
}
messageEditingTo.value = null;
messageReplyingTo.value = null;
messageForwardingTo.value = null;
selectedPoll.value = null;
selectedFund.value = null;
},
messageEditingTo: messageEditingTo.value,
messageReplyingTo: messageReplyingTo.value,
messageForwardingTo: messageForwardingTo.value,
selectedPoll: selectedPoll.value,
onPollSelected: (poll) => selectedPoll.value = poll,
selectedFund: selectedFund.value,
onFundSelected: (fund) => selectedFund.value = fund,
onPickFile: (bool isPhoto) {
if (isPhoto) {
pickPhotoMedia();
} else {
pickVideoMedia();
}
},
onPickAudio: pickAudioMedia,
onPickGeneralFile: pickGeneralFile,
onLinkAttachment: linkAttachment,
attachments: attachments.value,
onUploadAttachment: uploadAttachment,
onDeleteAttachment: (index) async {
final attachment = attachments.value[index];
if (attachment.isOnCloud && !attachment.isLink) {
final client = ref.watch(apiClientProvider);
await client.delete(
'/drive/files/${attachment.data.id}',
);
}
final clone = List.of(attachments.value);
clone.removeAt(index);
attachments.value = clone;
},
onMoveAttachment: (idx, delta) {
if (idx + delta < 0 ||
idx + delta >= attachments.value.length) {
return;
}
final clone = List.of(attachments.value);
clone.insert(idx + delta, clone.removeAt(idx));
attachments.value = clone;
},
onAttachmentsChanged: (newAttachments) {
attachments.value = newAttachments;
},
attachmentProgress: attachmentProgress.value,
),
Gap(MediaQuery.of(context).padding.bottom),
],
data: (room) => Column(
key: inputKey,
mainAxisSize: MainAxisSize.min,
children: [
ChatInput(
messageController: messageController,
chatRoom: room!,
onSend: sendMessage,
onClear: () {
if (messageEditingTo.value != null) {
attachments.value.clear();
messageController.clear();
}
messageEditingTo.value = null;
messageReplyingTo.value = null;
messageForwardingTo.value = null;
selectedPoll.value = null;
selectedFund.value = null;
},
messageEditingTo: messageEditingTo.value,
messageReplyingTo: messageReplyingTo.value,
messageForwardingTo: messageForwardingTo.value,
selectedPoll: selectedPoll.value,
onPollSelected: (poll) => selectedPoll.value = poll,
selectedFund: selectedFund.value,
onFundSelected: (fund) => selectedFund.value = fund,
onPickFile: (bool isPhoto) {
if (isPhoto) {
pickPhotoMedia();
} else {
pickVideoMedia();
}
},
onPickAudio: pickAudioMedia,
onPickGeneralFile: pickGeneralFile,
onLinkAttachment: linkAttachment,
attachments: attachments.value,
onUploadAttachment: uploadAttachment,
onDeleteAttachment: (index) async {
final attachment = attachments.value[index];
if (attachment.isOnCloud && !attachment.isLink) {
final client = ref.watch(apiClientProvider);
await client.delete(
'/drive/files/${attachment.data.id}',
);
}
final clone = List.of(attachments.value);
clone.removeAt(index);
attachments.value = clone;
},
onMoveAttachment: (idx, delta) {
if (idx + delta < 0 ||
idx + delta >= attachments.value.length) {
return;
}
final clone = List.of(attachments.value);
clone.insert(idx + delta, clone.removeAt(idx));
attachments.value = clone;
},
onAttachmentsChanged: (newAttachments) {
attachments.value = newAttachments;
},
attachmentProgress: attachmentProgress.value,
),
Gap(MediaQuery.of(context).padding.bottom),
],
),
error: (_, _) => const SizedBox.shrink(),
loading: () => const SizedBox.shrink(),
),

View File

@@ -67,7 +67,7 @@ class ChatDetailScreen extends HookConsumerWidget {
try {
final client = ref.watch(apiClientProvider);
await client.patch(
'/sphere/chat/$id/members/me/notify',
'/messager/chat/$id/members/me/notify',
data: {'notify_level': level},
);
ref.invalidate(chatRoomIdentityProvider(id));
@@ -85,7 +85,7 @@ class ChatDetailScreen extends HookConsumerWidget {
try {
final client = ref.watch(apiClientProvider);
await client.patch(
'/sphere/chat/$id/members/me/notify',
'/messager/chat/$id/members/me/notify',
data: {'break_until': until.toUtc().toIso8601String()},
);
ref.invalidate(chatRoomIdentityProvider(id));
@@ -529,7 +529,7 @@ class _ChatRoomActionMenu extends HookConsumerWidget {
).then((confirm) async {
if (confirm) {
final client = ref.watch(apiClientProvider);
await client.delete('/sphere/chat/$id');
await client.delete('/messager/chat/$id');
ref.invalidate(chatRoomJoinedProvider);
if (context.mounted) {
context.pop();
@@ -560,7 +560,7 @@ class _ChatRoomActionMenu extends HookConsumerWidget {
).then((confirm) async {
if (confirm) {
final client = ref.watch(apiClientProvider);
await client.delete('/sphere/chat/$id/members/me');
await client.delete('/messager/chat/$id/members/me');
ref.invalidate(chatRoomJoinedProvider);
if (context.mounted) {
context.pop();
@@ -588,7 +588,8 @@ final chatMemberListProvider = AsyncNotifierProvider.autoDispose.family(
ChatMemberListNotifier.new,
);
class ChatMemberListNotifier extends AsyncNotifier<List<SnChatMember>>
class ChatMemberListNotifier
extends AsyncNotifier<PaginationState<SnChatMember>>
with AsyncPaginationController<SnChatMember> {
static const pageSize = 20;
@@ -599,7 +600,7 @@ class ChatMemberListNotifier extends AsyncNotifier<List<SnChatMember>>
Future<List<SnChatMember>> fetch() async {
final apiClient = ref.watch(apiClientProvider);
final response = await apiClient.get(
'/sphere/chat/$arg/members',
'/messager/chat/$arg/members',
queryParameters: {
'offset': fetchedCount.toString(),
'take': pageSize,
@@ -623,7 +624,8 @@ class _ChatMemberListSheet extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final memberNotifier = ref.read(chatMemberListProvider(roomId).notifier);
final memberState = ref.watch(chatMemberListProvider(roomId));
final memberNotifier = ref.watch(chatMemberListProvider(roomId).notifier);
final roomIdentity = ref.watch(chatRoomIdentityProvider(roomId));
final chatRoom = ref.watch(chatRoomProvider(roomId));
@@ -643,7 +645,7 @@ class _ChatMemberListSheet extends HookConsumerWidget {
try {
final apiClient = ref.watch(apiClientProvider);
await apiClient.post(
'/sphere/chat/invites/$roomId',
'/messager/chat/invites/$roomId',
data: {'related_user_id': result.id, 'role': 0},
);
memberNotifier.refresh();
@@ -663,7 +665,7 @@ class _ChatMemberListSheet extends HookConsumerWidget {
child: Row(
children: [
Text(
'members'.plural(memberNotifier.totalCount ?? 0),
'members'.plural(memberState.value?.totalCount ?? 0),
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
@@ -733,7 +735,7 @@ class _ChatMemberListSheet extends HookConsumerWidget {
try {
final apiClient = ref.watch(apiClientProvider);
await apiClient.delete(
'/sphere/chat/$roomId/members/${member.accountId}',
'/messager/chat/$roomId/members/${member.accountId}',
);
// Refresh both providers
memberNotifier.refresh();

View File

@@ -6,6 +6,7 @@ import 'package:go_router/go_router.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/activitypub.dart';
import 'package:island/models/post.dart';
import 'package:island/models/publisher.dart';
import 'package:island/models/heatmap.dart';
@@ -15,6 +16,7 @@ import 'package:island/screens/creators/publishers_form.dart';
import 'package:island/services/responsive.dart';
import 'package:island/utils/text.dart';
import 'package:island/widgets/account/account_picker.dart';
import 'package:island/widgets/activitypub/actor_profile.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/content/cloud_files.dart';
@@ -78,16 +80,43 @@ Future<List<SnPublisherMember>> publisherInvites(Ref ref) async {
.toList();
}
@riverpod
Future<SnActorStatusResponse> publisherActorStatus(
Ref ref,
String? publisherName,
) async {
if (publisherName == null) throw Exception('Publisher name is required');
final apiClient = ref.watch(apiClientProvider);
final response = await apiClient.get(
'/sphere/publishers/$publisherName/fediverse',
);
return SnActorStatusResponse.fromJson(response.data);
}
final publisherMemberListNotifierProvider = AsyncNotifierProvider.family
.autoDispose(PublisherMemberListNotifier.new);
class PublisherMemberListNotifier extends AsyncNotifier<List<SnPublisherMember>>
class PublisherMemberListNotifier
extends AsyncNotifier<PaginationState<SnPublisherMember>>
with AsyncPaginationController<SnPublisherMember> {
static const int pageSize = 20;
final String arg;
PublisherMemberListNotifier(this.arg);
@override
FutureOr<PaginationState<SnPublisherMember>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnPublisherMember>> fetch() async {
final apiClient = ref.read(apiClientProvider);
@@ -501,6 +530,24 @@ class CreatorHubScreen extends HookConsumerWidget {
leading: const Icon(Symbols.edit),
onTap: updatePublisher,
),
ListTile(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
minTileHeight: 48,
title: Text('publisherFediverse').tr(),
trailing: Icon(Symbols.chevron_right),
leading: const Icon(Symbols.public),
onTap: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) => _PublisherFediverseSheet(
publisherUname: currentPublisher.value!.name,
),
);
},
),
ListTile(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8)),
@@ -1126,3 +1173,152 @@ class _PublisherInviteSheet extends HookConsumerWidget {
);
}
}
class _PublisherFediverseSheet extends HookConsumerWidget {
final String publisherUname;
const _PublisherFediverseSheet({required this.publisherUname});
@override
Widget build(BuildContext context, WidgetRef ref) {
final actorStatus = ref.watch(publisherActorStatusProvider(publisherUname));
final apiClient = ref.read(apiClientProvider);
final isLoading = useState(false);
Future<void> toggleActor() async {
final currentStatus = actorStatus.value;
if (currentStatus == null) return;
final confirm = await showConfirmAlert(
currentStatus.enabled
? 'publisherFediverseDisableConfirm'.tr()
: 'publisherFediverseEnableConfirm'.tr(),
currentStatus.enabled
? 'publisherFediverseDisabled'.tr()
: 'publisherFediverseEnabled'.tr(),
isDanger: !currentStatus.enabled,
);
if (confirm != true) return;
try {
isLoading.value = true;
if (currentStatus.enabled) {
await apiClient.delete(
'/sphere/publishers/$publisherUname/fediverse',
);
} else {
await apiClient.post('/sphere/publishers/$publisherUname/fediverse');
}
ref.invalidate(publisherActorStatusProvider(publisherUname));
if (context.mounted) {
Navigator.pop(context);
}
} catch (err) {
showErrorAlert(err);
} finally {
isLoading.value = false;
}
}
return SheetScaffold(
titleText: 'publisherFediverse'.tr(),
child: actorStatus.when(
data: (status) => SingleChildScrollView(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Column(
spacing: 16,
children: [
Card.outlined(
child: SwitchListTile(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8)),
),
value: status.enabled,
onChanged: isLoading.value ? null : (_) => toggleActor(),
title: Text(
status.enabled
? 'publisherFediverseEnabled'.tr()
: 'publisherFediverseDisabled'.tr(),
),
subtitle: Text(
status.enabled
? 'publisherFediverseDisableHint'.tr()
: 'publisherFediverseEnableHint'.tr(),
),
secondary: isLoading.value
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Icon(
status.enabled
? Icons.check_circle
: Icons.circle_outlined,
color: status.enabled ? Colors.green : Colors.grey,
),
),
).padding(horizontal: 16),
if (status.enabled) ...[
if (status.actor != null) ...[
ListTile(
leading: ActorPictureWidget(
actor: status.actor!,
radius: 24,
),
title: Text(
status.actor!.displayName ??
status.actor!.username ??
'unknown'.tr(),
),
subtitle: Text(
'@${status.actor!.username}@${status.actor!.instance.domain}',
),
isThreeLine: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 28),
),
ListTile(
leading: const Icon(Symbols.link),
title: Text('publisherFediverseActorUri').tr(),
subtitle: Text(status.actorUri ?? 'N/A'),
contentPadding: const EdgeInsets.symmetric(horizontal: 32),
),
],
ListTile(
leading: const Icon(Symbols.group),
title: Text('publisherFediverseFollowerCount').tr(),
subtitle: Text(
status.followerCount > 0
? status.followerCount.toString()
: 'publisherFediverseNoFollowers'.tr(),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 32),
),
],
ExpansionTile(
leading: const Icon(Symbols.info),
title: Text('publisherFediverseWhatIs').tr(),
tilePadding: const EdgeInsets.symmetric(horizontal: 32),
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 16,
horizontal: 32,
),
child: Text('publisherFediverseAbout').tr(),
),
],
),
],
),
),
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) => ResponseErrorWidget(
error: error,
onRetry: () =>
ref.invalidate(publisherActorStatusProvider(publisherUname)),
),
),
);
}
}

View File

@@ -354,3 +354,81 @@ final class PublisherInvitesProvider
}
String _$publisherInvitesHash() => r'93aafc2f02af0a7a055ec1770b3999363dfaabdc';
@ProviderFor(publisherActorStatus)
const publisherActorStatusProvider = PublisherActorStatusFamily._();
final class PublisherActorStatusProvider
extends
$FunctionalProvider<
AsyncValue<SnActorStatusResponse>,
SnActorStatusResponse,
FutureOr<SnActorStatusResponse>
>
with
$FutureModifier<SnActorStatusResponse>,
$FutureProvider<SnActorStatusResponse> {
const PublisherActorStatusProvider._({
required PublisherActorStatusFamily super.from,
required String? super.argument,
}) : super(
retry: null,
name: r'publisherActorStatusProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$publisherActorStatusHash();
@override
String toString() {
return r'publisherActorStatusProvider'
''
'($argument)';
}
@$internal
@override
$FutureProviderElement<SnActorStatusResponse> $createElement(
$ProviderPointer pointer,
) => $FutureProviderElement(pointer);
@override
FutureOr<SnActorStatusResponse> create(Ref ref) {
final argument = this.argument as String?;
return publisherActorStatus(ref, argument);
}
@override
bool operator ==(Object other) {
return other is PublisherActorStatusProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$publisherActorStatusHash() =>
r'406117cb99b2aef236945ef0ef59e857d8835029';
final class PublisherActorStatusFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<SnActorStatusResponse>, String?> {
const PublisherActorStatusFamily._()
: super(
retry: null,
name: r'publisherActorStatusProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
PublisherActorStatusProvider call(String? publisherName) =>
PublisherActorStatusProvider._(argument: publisherName, from: this);
@override
String toString() => r'publisherActorStatusProvider';
}

View File

@@ -21,7 +21,7 @@ final pollListNotifierProvider = AsyncNotifierProvider.family.autoDispose(
PollListNotifier.new,
);
class PollListNotifier extends AsyncNotifier<List<SnPollWithStats>>
class PollListNotifier extends AsyncNotifier<PaginationState<SnPollWithStats>>
with AsyncPaginationController<SnPollWithStats> {
static const int pageSize = 20;

View File

@@ -18,7 +18,7 @@ final siteListNotifierProvider = AsyncNotifierProvider.family.autoDispose(
SiteListNotifier.new,
);
class SiteListNotifier extends AsyncNotifier<List<SnPublicationSite>>
class SiteListNotifier extends AsyncNotifier<PaginationState<SnPublicationSite>>
with AsyncPaginationController<SnPublicationSite> {
static const int pageSize = 20;

View File

@@ -140,7 +140,7 @@ final stickerPacksProvider = AsyncNotifierProvider.family.autoDispose(
StickerPacksNotifier.new,
);
class StickerPacksNotifier extends AsyncNotifier<List<SnStickerPack>>
class StickerPacksNotifier extends AsyncNotifier<PaginationState<SnStickerPack>>
with AsyncPaginationController<SnStickerPack> {
static const int pageSize = 20;

View File

@@ -21,6 +21,7 @@ import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/notification_tile.dart';
import 'package:island/widgets/post/post_featured.dart';
import 'package:island/widgets/check_in.dart';
import 'package:island/models/activity.dart';
import 'package:island/screens/notification.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:slide_countdown/slide_countdown.dart';
@@ -229,7 +230,7 @@ class ClockCard extends HookConsumerWidget {
Widget build(BuildContext context, WidgetRef ref) {
final time = useState(DateTime.now());
final timer = useRef<Timer?>(null);
final nextNotableDay = ref.watch(nextNotableDayProvider);
final notableDay = ref.watch(recentNotableDayProvider);
// Determine icon based on time of day
final int hour = time.value.hour;
@@ -301,23 +302,13 @@ class ClockCard extends HookConsumerWidget {
Row(
spacing: 5,
children: [
Text('notableDayNext')
.tr(
args: [
nextNotableDay.value?.localName ?? 'idk',
],
)
.fontSize(12),
if (nextNotableDay.value != null)
SlideCountdown(
decoration: const BoxDecoration(),
style: const TextStyle(fontSize: 12),
separatorStyle: const TextStyle(fontSize: 12),
padding: EdgeInsets.zero,
duration: nextNotableDay.value?.date.difference(
DateTime.now(),
),
),
notableDay.when(
data: (day) => _buildNotableDayText(context, day!),
error: (err, _) =>
Text(err.toString()).fontSize(12),
loading: () =>
const Text('loading').tr().fontSize(12),
),
],
),
],
@@ -330,6 +321,42 @@ class ClockCard extends HookConsumerWidget {
),
);
}
Widget _buildNotableDayText(BuildContext context, SnNotableDay notableDay) {
final today = DateTime.now();
final isToday =
notableDay.date.year == today.year &&
notableDay.date.month == today.month &&
notableDay.date.day == today.day;
if (isToday) {
return Row(
spacing: 5,
children: [
Text('notableDayToday').tr(args: [notableDay.localName]).fontSize(12),
Icon(
Symbols.celebration_rounded,
size: 16,
color: Theme.of(context).colorScheme.primary,
),
],
);
} else {
return Row(
spacing: 5,
children: [
Text('notableDayNext').tr(args: [notableDay.localName]).fontSize(12),
SlideCountdown(
decoration: const BoxDecoration(),
style: const TextStyle(fontSize: 12),
separatorStyle: const TextStyle(fontSize: 12),
padding: EdgeInsets.zero,
duration: notableDay.date.difference(DateTime.now()),
),
],
);
}
}
}
class NotificationsCard extends HookConsumerWidget {
@@ -385,11 +412,11 @@ class NotificationsCard extends HookConsumerWidget {
loading: () => const SkeletonNotificationTile(),
error: (error, stack) => Center(child: Text('Error: $error')),
data: (notificationList) {
if (notificationList.isEmpty) {
if (notificationList.items.isEmpty) {
return Center(child: Text('noNotificationsYet').tr());
}
// Get the most recent notification (first in the list)
final recentNotification = notificationList.first;
final recentNotification = notificationList.items.first;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -493,65 +520,38 @@ class ChatListCard extends HookConsumerWidget {
}
}
class FortuneCard extends HookWidget {
class FortuneCard extends HookConsumerWidget {
const FortuneCard({super.key});
@override
Widget build(BuildContext context) {
final fortune = useMemoized(() {
const fortunes = [
{'text': '有的人活着,但他已经死了。', 'author': '—— 鲁迅'},
{'text': '天行健,君子以自强不息。', 'author': '—— 《周易》'},
{'text': '路漫漫其修远兮,吾将上下而求索。', 'author': '—— 屈原'},
{'text': '学海无涯苦作舟。', 'author': '—— 韩愈'},
{'text': '天道酬勤。', 'author': '—— 古语'},
{'text': '书山有路勤为径,学海无涯苦作舟。', 'author': '—— 韩愈'},
{'text': '莫等闲,白了少年头,空悲切。', 'author': '—— 岳飞'},
{
'text': 'The best way to predict the future is to create it.',
'author': '— Peter Drucker',
},
{'text': 'Fortune favors the bold.', 'author': '— Virgil'},
{
'text': 'A journey of a thousand miles begins with a single step.',
'author': '— Lao Tzu',
},
{
'text': 'The only way to do great work is to love what you do.',
'author': '— Steve Jobs',
},
{
'text': 'Believe you can and you\'re halfway there.',
'author': '— Theodore Roosevelt',
},
{
'text':
'The future belongs to those who believe in the beauty of their dreams.',
'author': '— Eleanor Roosevelt',
},
];
return fortunes[math.Random().nextInt(fortunes.length)];
});
Widget build(BuildContext context, WidgetRef ref) {
final fortuneAsync = ref.watch(randomFortuneSayingProvider);
return Card(
margin: EdgeInsets.zero,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: Row(
spacing: 8,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
fortune['text']!,
maxLines: 2,
overflow: TextOverflow.fade,
),
),
Text(fortune['author']!).bold(),
],
).padding(horizontal: 16),
child: fortuneAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stack) => Center(child: Text('Error: $error')),
data: (fortune) {
return Row(
spacing: 8,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
fortune.content,
maxLines: 2,
overflow: TextOverflow.fade,
),
),
Text('—— ${fortune.source}').bold(),
],
).padding(horizontal: 16);
},
),
).height(48);
}
}

View File

@@ -22,7 +22,7 @@ final articlesListNotifierProvider = AsyncNotifierProvider.family.autoDispose(
ArticlesListNotifier.new,
);
class ArticlesListNotifier extends AsyncNotifier<List<SnWebArticle>>
class ArticlesListNotifier extends AsyncNotifier<PaginationState<SnWebArticle>>
with AsyncPaginationController<SnWebArticle> {
static const int pageSize = 20;

View File

@@ -26,7 +26,7 @@ final marketplaceWebFeedContentNotifierProvider = AsyncNotifierProvider.family
.autoDispose(MarketplaceWebFeedContentNotifier.new);
class MarketplaceWebFeedContentNotifier
extends AsyncNotifier<List<SnWebArticle>>
extends AsyncNotifier<PaginationState<SnWebArticle>>
with AsyncPaginationController<SnWebArticle> {
static const int pageSize = 20;

View File

@@ -16,7 +16,8 @@ final marketplaceWebFeedsNotifierProvider = AsyncNotifierProvider.autoDispose(
MarketplaceWebFeedsNotifier.new,
);
class MarketplaceWebFeedsNotifier extends AsyncNotifier<List<SnWebFeed>>
class MarketplaceWebFeedsNotifier
extends AsyncNotifier<PaginationState<SnWebFeed>>
with
AsyncPaginationController<SnWebFeed>,
AsyncPaginationFilter<String?, SnWebFeed> {

View File

@@ -19,8 +19,8 @@ import 'package:island/services/responsive.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/models/post.dart';
import 'package:island/widgets/extended_refresh_indicator.dart';
import 'package:island/widgets/navigation/fab_menu.dart';
import 'package:island/widgets/paging/pagination_list.dart';
import 'package:island/widgets/post/compose_sheet.dart';
import 'package:island/widgets/post/post_item.dart';
import 'package:island/widgets/post/post_item_skeleton.dart';
import 'package:island/widgets/post/post_list.dart';
@@ -46,24 +46,6 @@ class ExploreScreen extends HookConsumerWidget {
final selectedTagIds = useState<List<String>>([]);
final notifier = ref.watch(activityListProvider.notifier);
useEffect(() {
// Set FAB type to chat
final fabMenuNotifier = ref.read(fabMenuTypeProvider.notifier);
Future(() {
fabMenuNotifier.setMenuType(FabMenuType.compose);
});
return () {
// Clean up: reset FAB type to main
final fabMenu = ref.read(fabMenuTypeProvider);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (fabMenu == FabMenuType.compose) {
fabMenuNotifier.setMenuType(FabMenuType.main);
}
});
};
}, []);
void handleFilterChange(String? filter) {
currentFilter.value = filter;
notifier.applyFilter(filter);
@@ -156,6 +138,18 @@ class ExploreScreen extends HookConsumerWidget {
),
PopupMenuButton(
itemBuilder: (context) => [
PopupMenuItem(
child: Row(
children: [
const Icon(Symbols.search),
const Gap(12),
Text('search').tr(),
],
),
onTap: () {
context.pushNamed('universalSearch');
},
),
PopupMenuItem(
child: Row(
children: [
@@ -180,18 +174,6 @@ class ExploreScreen extends HookConsumerWidget {
context.pushNamed('postShuffle');
},
),
PopupMenuItem(
child: Row(
children: [
const Icon(Symbols.search),
const Gap(12),
Text('search').tr(),
],
),
onTap: () {
context.pushNamed('postSearch');
},
),
],
icon: Icon(Symbols.action_key),
tooltip: 'search'.tr(),
@@ -200,6 +182,8 @@ class ExploreScreen extends HookConsumerWidget {
).padding(horizontal: 8, vertical: 4),
);
final userInfo = ref.watch(userInfoProvider);
final appBar = isWide
? null
: _buildAppBar(
@@ -230,6 +214,53 @@ class ExploreScreen extends HookConsumerWidget {
AppScaffold(
isNoBackground: false,
appBar: appBar,
floatingActionButton: userInfo.value != null
? FloatingActionButton(
child: const Icon(Symbols.create),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
const Gap(40),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
leading: const Icon(Symbols.post_add_rounded),
title: Text('postCompose').tr(),
onTap: () async {
Navigator.of(context).pop();
await PostComposeSheet.show(context);
},
),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
leading: const Icon(Symbols.article),
title: Text('articleCompose').tr(),
onTap: () async {
Navigator.of(context).pop();
GoRouter.of(
context,
).pushNamed('articleCompose');
},
),
const Gap(16),
],
),
);
},
).padding(
bottom:
(isWideScreen(context) ? 0 : 56) +
MediaQuery.of(context).padding.bottom,
)
: null,
body: isWide
? _buildWideBody(
context,
@@ -348,6 +379,8 @@ class ExploreScreen extends HookConsumerWidget {
? null // Post list handles its own refreshing
: ref.watch(activityListProvider.notifier);
final activityState = ref.watch(activityListProvider);
return Row(
spacing: 12,
children: [
@@ -360,6 +393,10 @@ class ExploreScreen extends HookConsumerWidget {
child: CustomScrollView(
slivers: [
const SliverGap(12),
if (activityState.value?.isLoading ?? false)
SliverToBoxAdapter(
child: LinearProgressIndicator().padding(bottom: 8),
),
SliverToBoxAdapter(child: filterBar),
const SliverGap(8),
bodyView,
@@ -505,6 +542,18 @@ class ExploreScreen extends HookConsumerWidget {
),
PopupMenuButton(
itemBuilder: (context) => [
PopupMenuItem(
child: Row(
children: [
const Icon(Symbols.search),
const Gap(12),
Text('search').tr(),
],
),
onTap: () {
context.pushNamed('universalSearch');
},
),
PopupMenuItem(
child: Row(
children: [
@@ -529,18 +578,6 @@ class ExploreScreen extends HookConsumerWidget {
context.pushNamed('postShuffle');
},
),
PopupMenuItem(
child: Row(
children: [
const Icon(Symbols.search),
const Gap(12),
Text('search').tr(),
],
),
onTap: () {
context.pushNamed('postSearch');
},
),
],
icon: Icon(Symbols.action_key, color: foregroundColor),
tooltip: 'search'.tr(),

View File

@@ -1,28 +1,19 @@
import 'dart:io';
import 'package:file_saver/file_saver.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gal/gal.dart';
import 'package:gap/gap.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/file.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/drive/file_references.dart';
import 'package:island/pods/network.dart';
import 'package:island/pods/drive/upload_tasks.dart';
import 'package:island/models/drive_task.dart';
import 'package:island/services/file_download.dart';
import 'package:island/services/responsive.dart';
import 'package:island/services/time.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/content/file_info_sheet.dart';
import 'package:island/widgets/content/file_viewer_contents.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:path/path.dart' show extension;
import 'package:path_provider/path_provider.dart';
import 'package:styled_widget/styled_widget.dart';
class FileDetailScreen extends HookConsumerWidget {
@@ -155,7 +146,7 @@ class FileDetailScreen extends HookConsumerWidget {
actions.add(
IconButton(
icon: Icon(Icons.save_alt),
onPressed: () async => _saveToGallery(ref),
onPressed: () => FileDownloadService(ref).saveToGallery(item),
),
);
}
@@ -166,7 +157,8 @@ class FileDetailScreen extends HookConsumerWidget {
actions.add(
IconButton(
icon: Icon(Icons.save_alt),
onPressed: () async => _downloadFile(ref),
onPressed: () =>
FileDownloadService(ref).downloadWithProgress(item),
),
);
}
@@ -199,80 +191,6 @@ class FileDetailScreen extends HookConsumerWidget {
return actions;
}
Future<void> _saveToGallery(WidgetRef ref) async {
try {
showSnackBar('Saving image...');
final client = ref.read(apiClientProvider);
final tempDir = await getTemporaryDirectory();
var extName = extension(item.name).trim();
if (extName.isEmpty) {
extName = item.mimeType?.split('/').lastOrNull ?? 'jpeg';
}
final filePath = '${tempDir.path}/${item.id}.$extName';
await client.download(
'/drive/files/${item.id}',
filePath,
queryParameters: {'original': true},
);
if (!kIsWeb && (Platform.isAndroid || Platform.isIOS)) {
await Gal.putImage(filePath, album: 'Solar Network');
showSnackBar('Image saved to gallery');
} else {
await FileSaver.instance.saveFile(
name: item.name.isEmpty ? '${item.id}.$extName' : item.name,
file: File(filePath),
);
showSnackBar('Image saved to $filePath');
}
} catch (e) {
showErrorAlert(e);
}
}
Future<void> _downloadFile(WidgetRef ref) async {
final taskNotifier = ref.read(uploadTasksProvider.notifier);
final taskId = taskNotifier.addLocalDownloadTask(item);
try {
showSnackBar('Downloading file...');
final client = ref.read(apiClientProvider);
final tempDir = await getTemporaryDirectory();
var extName = extension(item.name).trim();
if (extName.isEmpty) {
extName = item.mimeType?.split('/').lastOrNull ?? 'bin';
}
final filePath = '${tempDir.path}/${item.id}.$extName';
await client.download(
'/drive/files/${item.id}',
filePath,
queryParameters: {'original': true},
onReceiveProgress: (count, total) {
if (total > 0) {
taskNotifier.updateDownloadProgress(taskId, count, total);
taskNotifier.updateTransmissionProgress(taskId, count / total);
}
},
);
await FileSaver.instance.saveFile(
name: item.name.isEmpty ? '${item.id}.$extName' : item.name,
file: File(filePath),
);
taskNotifier.updateTaskStatus(taskId, DriveTaskStatus.completed);
showSnackBar('File saved to downloads');
} catch (e) {
taskNotifier.updateTaskStatus(
taskId,
DriveTaskStatus.failed,
errorMessage: e.toString(),
);
showErrorAlert(e);
}
}
Widget _buildContent(BuildContext context, WidgetRef ref, String serverUrl) {
final uri = '$serverUrl/drive/files/${item.id}';

View File

@@ -164,10 +164,24 @@ final notificationListProvider = AsyncNotifierProvider.autoDispose(
NotificationListNotifier.new,
);
class NotificationListNotifier extends AsyncNotifier<List<SnNotification>>
class NotificationListNotifier
extends AsyncNotifier<PaginationState<SnNotification>>
with AsyncPaginationController<SnNotification> {
static const int pageSize = 5;
@override
FutureOr<PaginationState<SnNotification>> build() async {
final items = await fetch();
return PaginationState(
items: items,
isLoading: false,
isReloading: false,
totalCount: totalCount,
hasMore: hasMore,
cursor: cursor,
);
}
@override
Future<List<SnNotification>> fetch() async {
final client = ref.read(apiClientProvider);
@@ -185,7 +199,9 @@ class NotificationListNotifier extends AsyncNotifier<List<SnNotification>>
.toList();
final unreadCount = notifications.where((n) => n.viewedAt == null).length;
ref.read(notificationUnreadCountProvider.notifier).decrement(unreadCount);
if (ref.mounted) {
ref.read(notificationUnreadCountProvider.notifier).decrement(unreadCount);
}
return notifications;
}

View File

@@ -80,7 +80,7 @@ class PostActionButtons extends HookConsumerWidget {
Widget build(BuildContext context, WidgetRef ref) {
final user = ref.watch(userInfoProvider);
final isAuthor =
user.value != null && user.value?.id == post.publisher.accountId;
user.value != null && user.value?.id == post.publisher?.accountId;
String formatScore(int score) {
if (score >= 1000000) {
@@ -303,10 +303,9 @@ class PostActionButtons extends HookConsumerWidget {
);
},
icon: const Icon(Symbols.emoji_events),
label:
post.awardedScore > 0
? Text('${formatScore(post.awardedScore)} pts')
: Text('award').tr(),
label: post.awardedScore > 0
? Text('${formatScore(post.awardedScore)} pts')
: Text('award').tr(),
),
);
@@ -323,10 +322,9 @@ class PostActionButtons extends HookConsumerWidget {
actions.add(
Row(
mainAxisSize: MainAxisSize.min,
children:
replyButtons
.map((e) => SizedBox(height: kButtonHeight, child: e))
.toList(),
children: replyButtons
.map((e) => SizedBox(height: kButtonHeight, child: e))
.toList(),
),
);
@@ -415,16 +413,15 @@ class PostActionButtons extends HookConsumerWidget {
);
// Add gaps between actions (excluding first one) using FP style
final children =
actions.asMap().entries.expand((entry) {
final index = entry.key;
final action = entry.value;
if (index == 0) {
return [action];
} else {
return [const Gap(8), action];
}
}).toList();
final children = actions.asMap().entries.expand((entry) {
final index = entry.key;
final action = entry.value;
if (index == 0) {
return [action];
} else {
return [const Gap(8), action];
}
}).toList();
return Container(
height: kButtonHeight,
@@ -518,33 +515,28 @@ class PostDetailScreen extends HookConsumerWidget {
bottom: 16 + MediaQuery.of(context).padding.bottom,
left: 16,
right: 16,
child:
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 660),
child: postState.when(
data:
(post) => PostQuickReply(
parent: post!,
onPosted: () {
ref
.read(postRepliesProvider(id).notifier)
.refresh();
},
),
loading: () => const SizedBox.shrink(),
error: (_, _) => const SizedBox.shrink(),
),
).center(),
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 660),
child: postState.when(
data: (post) => PostQuickReply(
parent: post!,
onPosted: () {
ref.read(postRepliesProvider(id).notifier).refresh();
},
),
loading: () => const SizedBox.shrink(),
error: (_, _) => const SizedBox.shrink(),
),
).center(),
),
],
);
},
loading: () => ResponseLoadingWidget(),
error:
(e, _) => ResponseErrorWidget(
error: e,
onRetry: () => ref.invalidate(postProvider(id)),
),
error: (e, _) => ResponseErrorWidget(
error: e,
onRetry: () => ref.invalidate(postProvider(id)),
),
),
);
}

View File

@@ -160,7 +160,7 @@ class PostSearchScreen extends HookConsumerWidget {
);
},
),
if (searchState.value?.isEmpty == true &&
if (searchState.value?.items.isEmpty == true &&
searchController.text.isNotEmpty &&
!searchState.isLoading)
SliverFillRemaining(
@@ -290,7 +290,7 @@ class PostSearchScreen extends HookConsumerWidget {
);
},
),
if (searchState.value?.isEmpty == true &&
if (searchState.value?.items.isEmpty == true &&
searchController.text.isNotEmpty &&
!searchState.isLoading)
SliverFillRemaining(

View File

@@ -1,3 +1,4 @@
import 'package:dio/dio.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
@@ -371,9 +372,16 @@ Future<SnPublisherSubscription?> publisherSubscriptionStatus(
String pubName,
) async {
final apiClient = ref.watch(apiClientProvider);
final resp = await apiClient.get("/sphere/publishers/$pubName/subscription");
if (resp.statusCode == 200) {
try {
final resp = await apiClient.get(
"/sphere/publishers/$pubName/subscription",
);
return SnPublisherSubscription.fromJson(resp.data);
} catch (err) {
if (err is DioException) {
if (err.response?.statusCode == 404) return null;
rethrow;
}
}
return null;
}
@@ -385,7 +393,7 @@ Future<Color?> publisherAppbarForcegroundColor(Ref ref, String pubName) async {
if (publisher.background == null) return null;
final colors = await ColorExtractionService.getColorsFromImage(
CloudImageWidget.provider(
fileId: publisher.background!.id,
file: publisher.background!,
serverUrl: ref.watch(serverUrlProvider),
),
);

View File

@@ -221,7 +221,7 @@ final class PublisherSubscriptionStatusProvider
}
String _$publisherSubscriptionStatusHash() =>
r'accf6a0cdf98f8b0474d94ac575e8b20448adc79';
r'688bf38554afea9e68b2cb59c5f08c6e8dd31b62';
final class PublisherSubscriptionStatusFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<SnPublisherSubscription?>, String> {
@@ -293,7 +293,7 @@ final class PublisherAppbarForcegroundColorProvider
}
String _$publisherAppbarForcegroundColorHash() =>
r'cd9a9816177a6eecc2bc354acebbbd48892ffdd7';
r'a7c9795c68a29beb611d2c258022c9a5640f2061';
final class PublisherAppbarForcegroundColorFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<Color?>, String> {

View File

@@ -33,7 +33,7 @@ final realmAppbarForegroundColorProvider = FutureProvider.autoDispose
if (realm?.background == null) return null;
final colors = await ColorExtractionService.getColorsFromImage(
CloudImageWidget.provider(
fileId: realm!.background!.id,
file: realm!.background!,
serverUrl: ref.watch(serverUrlProvider),
),
);
@@ -63,7 +63,7 @@ final realmIdentityProvider = FutureProvider.autoDispose
final realmChatRoomsProvider = FutureProvider.autoDispose
.family<List<SnChatRoom>, String>((ref, realmSlug) async {
final apiClient = ref.watch(apiClientProvider);
final response = await apiClient.get('/sphere/realms/$realmSlug/chat');
final response = await apiClient.get('/messager/realms/$realmSlug/chat');
return (response.data as List)
.map((e) => SnChatRoom.fromJson(e))
.toList();
@@ -492,11 +492,10 @@ class _RealmActionMenu extends HookConsumerWidget {
}
final realmMemberListNotifierProvider = AsyncNotifierProvider.autoDispose
.family<RealmMemberListNotifier, List<SnRealmMember>, String>(
RealmMemberListNotifier.new,
);
.family(RealmMemberListNotifier.new);
class RealmMemberListNotifier extends AsyncNotifier<List<SnRealmMember>>
class RealmMemberListNotifier
extends AsyncNotifier<PaginationState<SnRealmMember>>
with AsyncPaginationController<SnRealmMember> {
String arg;
RealmMemberListNotifier(this.arg);
@@ -528,12 +527,11 @@ class _RealmMemberListSheet extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final realmIdentity = ref.watch(realmIdentityProvider(realmSlug));
final memberListProvider = realmMemberListNotifierProvider(realmSlug);
// memberListNotifier is not watched here to prevent unnecessary rebuilds of this widget
// when we only need it for passing to PaginationList as a Refreshable
// However, we used useEffect to dispose it, but AutoDispose handles it.
// So we remove the useEffect and the watch.
final memberListState = ref.watch(memberListProvider);
final memberListNotifier = ref.watch(memberListProvider.notifier);
final realmIdentity = ref.watch(realmIdentityProvider(realmSlug));
Future<void> invitePerson() async {
final result = await showModalBottomSheet(
@@ -550,7 +548,7 @@ class _RealmMemberListSheet extends HookConsumerWidget {
data: {'related_user_id': result.id, 'role': 0},
);
// Refresh the provider
ref.invalidate(memberListProvider);
memberListNotifier.refresh();
} catch (err) {
showErrorAlert(err);
}
@@ -563,11 +561,8 @@ class _RealmMemberListSheet extends HookConsumerWidget {
children: [
Consumer(
builder: (context, ref, _) {
// effective watch to rebuild when data changes (and totalCount updates)
ref.watch(memberListProvider);
final notifier = ref.read(memberListProvider.notifier);
return Text(
'members'.plural(notifier.totalCount ?? 0),
'members'.plural(memberListState.value?.totalCount ?? 0),
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,

View File

@@ -1,16 +1,16 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/realm.dart';
import 'package:island/pods/network.dart';
import 'package:island/pods/userinfo.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:island/widgets/navigation/fab_menu.dart';
import 'package:island/widgets/response.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -43,27 +43,11 @@ class RealmListScreen extends HookConsumerWidget {
final realms = ref.watch(realmsJoinedProvider);
final realmInvites = ref.watch(realmInvitesProvider);
useEffect(() {
// Set FAB type to realm
final fabMenuNotifier = ref.read(fabMenuTypeProvider.notifier);
Future(() {
fabMenuNotifier.setMenuType(FabMenuType.realm);
});
return () {
// Clean up: reset FAB type to main
final fabMenu = ref.read(fabMenuTypeProvider);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (fabMenu == FabMenuType.realm) {
fabMenuNotifier.setMenuType(FabMenuType.main);
}
});
};
}, []);
final userInfo = ref.watch(userInfoProvider);
return AppScaffold(
isNoBackground: false,
appBar: AppBar(
leading: const PageBackButton(backTo: '/account'),
title: const Text('realms').tr(),
actions: [
IconButton(
@@ -98,6 +82,45 @@ class RealmListScreen extends HookConsumerWidget {
const Gap(8),
],
),
floatingActionButton: userInfo.value != null
? FloatingActionButton(
child: const Icon(Symbols.add),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
const Gap(40),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
leading: const Icon(Symbols.group_add),
title: Text('createRealm').tr(),
onTap: () {
Navigator.of(context).pop();
context.pushNamed('realmNew').then((value) {
if (value != null) {
// Fire realm refresh event if needed
// eventBus.fire(const RealmsRefreshEvent());
}
});
},
),
const Gap(16),
],
),
);
},
).padding(
bottom:
(isWideScreen(context) ? 0 : 56) +
MediaQuery.of(context).padding.bottom,
)
: null,
body: ExtendedRefreshIndicator(
child: realms.when(
data: (value) => Column(

484
lib/screens/search.dart Normal file
View File

@@ -0,0 +1,484 @@
import 'dart:async';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:gap/gap.dart';
import 'package:island/models/activitypub.dart';
import 'package:island/pods/post/post_list.dart';
import 'package:island/services/activitypub_service.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/activitypub/actor_list_item.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/extended_refresh_indicator.dart';
import 'package:island/widgets/paging/pagination_list.dart';
import 'package:island/widgets/post/post_item.dart';
import 'package:island/widgets/post/post_item_skeleton.dart';
import 'package:island/widgets/posts/post_filter.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart';
const kSearchPostListId = 'search';
enum SearchTab { posts, fediverse }
class UniversalSearchScreen extends HookConsumerWidget {
final SearchTab initialTab;
const UniversalSearchScreen({super.key, this.initialTab = SearchTab.posts});
@override
Widget build(BuildContext context, WidgetRef ref) {
final tabController = useTabController(
initialLength: 2,
initialIndex: initialTab.index,
);
return AppScaffold(
isNoBackground: false,
appBar: AppBar(title: Text('search'.tr()), elevation: 0),
body: Column(
children: [
TabBar(
controller: tabController,
tabs: [
Tab(text: 'posts'.tr()),
Tab(text: 'fediverseUsers'.tr()),
],
),
Expanded(
child: TabBarView(
controller: tabController,
children: [_PostsSearchTab(), _FediverseSearchTab()],
),
),
],
),
);
}
}
class _PostsSearchTab extends HookConsumerWidget {
const _PostsSearchTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final searchController = useTextEditingController();
final debounce = useMemoized(() => Duration(milliseconds: 500));
final debounceTimer = useRef<Timer?>(null);
final showFilters = useState(false);
final pubNameController = useTextEditingController();
final realmController = useTextEditingController();
final categoryTabController = useTabController(initialLength: 3);
final queryState = useState(const PostListQuery());
final noti = ref.read(
postListProvider(PostListQueryConfig(id: kSearchPostListId)).notifier,
);
useEffect(() {
return () {
searchController.dispose();
pubNameController.dispose();
realmController.dispose();
debounceTimer.value?.cancel();
};
}, []);
void onSearchChanged(String query, {bool skipDebounce = false}) {
queryState.value = queryState.value.copyWith(queryTerm: query);
if (skipDebounce) {
noti.applyFilter(queryState.value);
return;
}
if (debounceTimer.value?.isActive ?? false) debounceTimer.value!.cancel();
debounceTimer.value = Timer(debounce, () {
noti.applyFilter(queryState.value);
});
}
void toggleFilterDisplay() {
showFilters.value = !showFilters.value;
}
Widget buildFilterPanel() {
return PostFilterWidget(
categoryTabController: categoryTabController,
initialQuery: queryState.value,
onQueryChanged: (newQuery) {
queryState.value = newQuery;
noti.applyFilter(newQuery);
},
hideSearch: true,
);
}
return Consumer(
builder: (context, ref, child) {
final searchState = ref.watch(
postListProvider(PostListQueryConfig(id: kSearchPostListId)),
);
return isWideScreen(context)
? Row(
children: [
Flexible(
flex: 4,
child: ExtendedRefreshIndicator(
onRefresh: noti.refresh,
child: CustomScrollView(
slivers: [
SliverGap(16),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
child: SearchBar(
elevation: WidgetStateProperty.all(4),
controller: searchController,
hintText: 'search'.tr(),
leading: const Icon(Icons.search),
padding: WidgetStateProperty.all(
const EdgeInsets.symmetric(horizontal: 24),
),
onChanged: onSearchChanged,
onSubmitted: (value) {
onSearchChanged(value, skipDebounce: true);
},
),
),
),
const SliverGap(12),
PaginationList(
provider: postListProvider(
PostListQueryConfig(id: kSearchPostListId),
),
notifier: postListProvider(
PostListQueryConfig(id: kSearchPostListId),
).notifier,
isSliver: true,
isRefreshable: false,
footerSkeletonChild: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
child: const PostItemSkeleton(),
),
itemBuilder: (context, index, post) {
return Card(
margin: EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
child: PostActionableItem(
item: post,
borderRadius: 8,
),
);
},
),
if (searchState.value?.items.isEmpty == true &&
searchController.text.isNotEmpty &&
!searchState.isLoading)
SliverFillRemaining(
child: Center(child: Text('noResultsFound'.tr())),
),
SliverGap(MediaQuery.of(context).padding.bottom + 16),
],
).padding(left: 8),
),
),
Flexible(
flex: 3,
child: Align(
alignment: Alignment.topLeft,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Gap(16),
Card(
margin: EdgeInsets.symmetric(horizontal: 8),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
child: Row(
children: [
const Icon(
Symbols.tune,
).padding(horizontal: 8),
Expanded(
child: Text(
'filters'.tr(),
style: Theme.of(
context,
).textTheme.bodyLarge,
),
),
IconButton(
icon: Icon(
Symbols.filter_alt,
fill: showFilters.value ? 1 : null,
),
onPressed: toggleFilterDisplay,
tooltip: 'toggleFilters'.tr(),
),
const Gap(4),
],
),
),
),
const Gap(8),
if (showFilters.value) buildFilterPanel(),
],
),
),
),
),
],
)
: CustomScrollView(
slivers: [
const SliverGap(4),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: SearchBar(
elevation: WidgetStateProperty.all(4),
controller: searchController,
hintText: 'search'.tr(),
leading: const Icon(Icons.search),
padding: WidgetStateProperty.all(
const EdgeInsets.symmetric(horizontal: 24),
),
onChanged: onSearchChanged,
onSubmitted: (value) {
onSearchChanged(value, skipDebounce: true);
},
),
),
),
if (showFilters.value)
SliverToBoxAdapter(
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 600),
child: buildFilterPanel(),
),
),
),
PaginationList(
provider: postListProvider(
PostListQueryConfig(id: kSearchPostListId),
),
notifier: postListProvider(
PostListQueryConfig(id: kSearchPostListId),
).notifier,
isSliver: true,
isRefreshable: false,
footerSkeletonChild: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: const PostItemSkeleton(),
),
itemBuilder: (context, index, post) {
return Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 600),
child: Card(
margin: EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
child: PostActionableItem(
item: post,
borderRadius: 8,
),
),
),
);
},
),
if (searchState.value?.items.isEmpty == true &&
searchController.text.isNotEmpty &&
!searchState.isLoading)
SliverFillRemaining(
child: Center(child: Text('noResultsFound'.tr())),
),
],
);
},
);
}
}
class _FediverseSearchTab extends HookConsumerWidget {
const _FediverseSearchTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final searchController = useTextEditingController();
final debounce = useMemoized(() => const Duration(milliseconds: 500));
final debounceTimer = useRef<Timer?>(null);
final searchResults = useState<List<SnActivityPubActor>>([]);
final isSearching = useState(false);
useEffect(() {
return () {
searchController.dispose();
debounceTimer.value?.cancel();
};
}, []);
Future<void> performSearch(String query) async {
if (query.trim().isEmpty) {
searchResults.value = [];
return;
}
isSearching.value = true;
try {
final service = ref.read(activityPubServiceProvider);
final results = await service.searchUsers(query);
searchResults.value = results;
} catch (err) {
showErrorAlert(err);
} finally {
isSearching.value = false;
}
}
void onSearchChanged(String query) {
if (debounceTimer.value?.isActive ?? false) {
debounceTimer.value!.cancel();
}
debounceTimer.value = Timer(debounce, () {
performSearch(query);
});
}
void updateActorIsFollowing(String actorId, bool isFollowing) {
searchResults.value = searchResults.value
.map(
(a) => a.id == actorId ? a.copyWith(isFollowing: isFollowing) : a,
)
.toList();
}
Future<void> handleFollow(SnActivityPubActor actor) async {
try {
updateActorIsFollowing(actor.id, true);
final service = ref.read(activityPubServiceProvider);
await service.followRemoteUser(actor.uri);
showSnackBar(
'followedUser'.tr(
args: [
'${actor.username?.isNotEmpty ?? false ? actor.username : actor.displayName}',
],
),
);
} catch (err) {
showErrorAlert(err);
updateActorIsFollowing(actor.id, false);
}
}
Future<void> handleUnfollow(SnActivityPubActor actor) async {
try {
updateActorIsFollowing(actor.id, false);
final service = ref.read(activityPubServiceProvider);
await service.unfollowRemoteUser(actor.uri);
showSnackBar(
'unfollowedUser'.tr(
args: [
'${actor.username?.isNotEmpty ?? false ? actor.username : actor.displayName}',
],
),
);
} catch (err) {
showErrorAlert(err);
updateActorIsFollowing(actor.id, true);
}
}
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: SearchBar(
controller: searchController,
hintText: 'searchFediverseHint'.tr(
args: ['@username@instance.com'],
),
leading: const Icon(Symbols.search).padding(horizontal: 24),
onChanged: onSearchChanged,
onSubmitted: (value) {
onSearchChanged(value);
performSearch(value);
},
),
),
Expanded(
child: isSearching.value
? const Center(child: CircularProgressIndicator())
: searchResults.value.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Symbols.search,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
if (searchController.text.isEmpty)
Text(
'searchFediverseEmpty'.tr(),
style: Theme.of(context).textTheme.titleMedium,
)
else
Text(
'searchFediverseNoResults'.tr(),
style: Theme.of(context).textTheme.titleMedium,
),
],
),
)
: ExtendedRefreshIndicator(
onRefresh: () => performSearch(searchController.text),
child: ListView.separated(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: searchResults.value.length,
separatorBuilder: (context, index) => const Gap(8),
itemBuilder: (context, index) {
final actor = searchResults.value[index];
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560),
child: ApActorListItem(
actor: actor,
isFollowing: actor.isFollowing ?? false,
isLoading: false,
onFollow: () => handleFollow(actor),
onUnfollow: () => handleUnfollow(actor),
),
),
);
},
),
),
),
],
);
}
}

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