Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for managing uploaded media #1323

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b14e410
Add support for managing uploaded media
micahmo Apr 23, 2024
6400b4a
Update API package
micahmo Apr 23, 2024
f56f532
Add support for searching for usages of media
micahmo Apr 24, 2024
0046592
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo May 2, 2024
d583df8
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo May 16, 2024
ed130be
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Jun 4, 2024
83098d7
Fix build after merge
micahmo Jun 4, 2024
db39402
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Jun 25, 2024
ea4bddf
Try to fix build error by directly referencing freezed_annotation
micahmo Jun 25, 2024
28307df
Making a random change to full_name_widgets.dart
micahmo Jun 26, 2024
d51bf3a
Revert random change
micahmo Jun 26, 2024
79a03e4
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Jun 26, 2024
ff0a56b
Make another random change
micahmo Jun 26, 2024
41b3e30
Fix build issue
micahmo Jun 26, 2024
da9b900
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Jul 12, 2024
2a4316d
Fix translation issue
micahmo Jul 12, 2024
5bf9a95
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Jul 16, 2024
7316c07
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Jul 16, 2024
c3845dd
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Sep 25, 2024
d6b0d0d
Merge remote-tracking branch 'upstream/develop' into feature/delete-m…
micahmo Oct 21, 2024
fd66182
Add back freezed_annotation
micahmo Oct 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/community/utils/post_actions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,13 @@ void triggerPostAction({
}
}

DismissDirection determinePostSwipeDirection(bool isUserLoggedIn, ThunderState state) {
DismissDirection determinePostSwipeDirection(bool isUserLoggedIn, ThunderState state, {bool disableSwiping = false}) {
if (!isUserLoggedIn) return DismissDirection.none;

if (state.enablePostGestures == false) return DismissDirection.none;

if (disableSwiping) return DismissDirection.none;

// If all of the actions are none, then disable swiping
if (state.leftPrimaryPostGesture == SwipeAction.none &&
state.leftSecondaryPostGesture == SwipeAction.none &&
Expand Down
11 changes: 8 additions & 3 deletions lib/community/widgets/post_card.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ class PostCard extends StatefulWidget {

final ListingType? listingType;

final bool disableSwiping;

const PostCard({
super.key,
required this.postViewMedia,
Expand All @@ -47,6 +49,7 @@ class PostCard extends StatefulWidget {
required this.onDownAction,
required this.listingType,
required this.indicateRead,
this.disableSwiping = false,
});

@override
Expand Down Expand Up @@ -131,19 +134,21 @@ class _PostCardState extends State<PostCard> {
// We are checking to see if there is a left to right swipe here. If there is a left to right swipe, and LTR swipe actions are disabled, then we disable the DismissDirection temporarily
// to allow for the full screen swipe to go back. Otherwise, we retain the default behaviour
if (horizontalDragDistance > 0) {
if (determinePostSwipeDirection(isUserLoggedIn, state) == DismissDirection.endToStart && isOverridingSwipeGestureAction == false && dismissThreshold == 0.0) {
if (determinePostSwipeDirection(isUserLoggedIn, state, disableSwiping: widget.disableSwiping) == DismissDirection.endToStart &&
isOverridingSwipeGestureAction == false &&
dismissThreshold == 0.0) {
setState(() => isOverridingSwipeGestureAction = true);
}
} else {
if (determinePostSwipeDirection(isUserLoggedIn, state) == DismissDirection.endToStart && isOverridingSwipeGestureAction == true) {
if (determinePostSwipeDirection(isUserLoggedIn, state, disableSwiping: widget.disableSwiping) == DismissDirection.endToStart && isOverridingSwipeGestureAction == true) {
setState(() => isOverridingSwipeGestureAction = false);
}
}
},
child: Column(
children: [
Dismissible(
direction: isOverridingSwipeGestureAction == true ? DismissDirection.none : determinePostSwipeDirection(isUserLoggedIn, state),
direction: isOverridingSwipeGestureAction == true ? DismissDirection.none : determinePostSwipeDirection(isUserLoggedIn, state, disableSwiping: widget.disableSwiping),
key: ObjectKey(widget.postViewMedia.postView.post.id),
resizeDuration: Duration.zero,
dismissThresholds: const {DismissDirection.endToStart: 1, DismissDirection.startToEnd: 1},
Expand Down
2 changes: 2 additions & 0 deletions lib/core/enums/local_settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ enum LocalSettings {
accountBlocks(name: 'account_blocks', key: 'accountBlocks', category: LocalSettingsCategories.account, subCategory: LocalSettingsSubCategories.contentManagement),
accountChangePassword(name: 'account_change_password', key: 'accountChangePassword', category: LocalSettingsCategories.account, subCategory: LocalSettingsSubCategories.dangerZone),
accountDeleteAccount(name: 'account_delete_account', key: 'accountDeleteAccount', category: LocalSettingsCategories.account, subCategory: LocalSettingsSubCategories.dangerZone),
accountManageMedia(name: 'account_manage_media', key: 'accountManageMedia', category: LocalSettingsCategories.account, subCategory: LocalSettingsSubCategories.dangerZone),
debugDeleteLocalPreferences(name: 'debug_delete_local_preferences', key: 'debugDeleteLocalPreferences', category: LocalSettingsCategories.debug, subCategory: LocalSettingsSubCategories.reset),
debugDeleteLocalDatabase(name: 'debug_delete_local_database', key: 'debugDeleteLocalDatabase', category: LocalSettingsCategories.debug, subCategory: LocalSettingsSubCategories.reset),
debugClearCache(name: 'debug_clear_cache', key: 'debugClearCache', category: LocalSettingsCategories.debug, subCategory: LocalSettingsSubCategories.reset),
Expand Down Expand Up @@ -536,6 +537,7 @@ extension LocalizationExt on AppLocalizations {
'accountChangePassword': changePassword,
'dangerZone': dangerZone,
'accountDeleteAccount': deleteAccount,
'accountManageMedia': manageMedia,
'reset': resetPreferencesAndData,
'debugDeleteLocalPreferences': deleteLocalPreferences,
'debugDeleteLocalDatabase': deleteLocalDatabase,
Expand Down
3 changes: 2 additions & 1 deletion lib/core/singletons/lemmy_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ enum LemmyFeature {
blockInstance(0, 19, 0, preRelease: ["rc", "1"]),
multiRead(0, 19, 0, preRelease: ["rc", "1"]),
hidePosts(0, 19, 4),
customThumbnail(0, 19, 4);
customThumbnail(0, 19, 4),
listMedia(0, 19, 4, preRelease: ["beta", "4"]);

final int major;
final int minor;
Expand Down
11 changes: 10 additions & 1 deletion lib/feed/widgets/feed_post_card_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,20 @@ class FeedPostCardList extends StatefulWidget {
/// The list of posts to show on the feed
final List<PostViewMedia> postViewMedias;

/// Whether to disable swiping of posts
final bool disableSwiping;

/// Overrides the system setting for whether to indicate read posts
final bool? indicateRead;

const FeedPostCardList({
super.key,
required this.postViewMedias,
required this.tabletMode,
required this.markPostReadOnScroll,
this.queuedForRemoval,
this.disableSwiping = false,
this.indicateRead,
});

@override
Expand Down Expand Up @@ -156,7 +164,8 @@ class _FeedPostCardListState extends State<FeedPostCardList> {
}
},
listingType: state.postListingType,
indicateRead: dimReadPosts,
indicateRead: widget.indicateRead ?? dimReadPosts,
disableSwiping: widget.disableSwiping,
))
: null,
);
Expand Down
32 changes: 32 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,14 @@
"@deleteAccountDescription": {
"description": "Description for confirmation action to delete account"
},
"deleteImageConfirmMessage": "Are you sure you want to delete this image?",
"@deleteImageConfirmMessage": {
"description": "Confirmation messages for deleting an image"
},
"deleteImageConfirmTitle": "Delete?",
"@deleteImageConfirmTitle": {
"description": "Confirmation title message for deleting an image"
},
"deleteLocalDatabase": "Delete Local Database",
"@deleteLocalDatabase": {
"description": "Label for action to delete local database"
Expand Down Expand Up @@ -811,6 +819,10 @@
"@endOfComments": {},
"endSearch": "End Search",
"@endSearch": {},
"errorDeletingImage": "There was an error deleting the image: {error}",
"@errorDeletingImage": {
"description": "Error message for deleting an image"
},
"errorDownloadingMedia": "Could not download the media file to share: {errorMessage}",
"@errorDownloadingMedia": {},
"errorMarkingReplyRead": "There was an error marking the reply as read.",
Expand Down Expand Up @@ -1205,6 +1217,10 @@
"@loadMorePlural": {},
"loadMoreSingular": "Load {count} more reply…",
"@loadMoreSingular": {},
"loading": "Loading...",
"@loading": {
"description": "Placeholder text for loading"
},
"local": "Local",
"@local": {},
"localNotifications": "Local Notifications",
Expand Down Expand Up @@ -1253,6 +1269,10 @@
},
"manageAccounts": "Manage Accounts",
"@manageAccounts": {},
"manageMedia": "Manage Media",
"@manageMedia": {
"description": "Setting name and page title for media management"
},
"markAllAsRead": "Mark all as read",
"@markAllAsRead": {
"description": "The mark all as read action"
Expand Down Expand Up @@ -1433,6 +1453,10 @@
"@noFavoritedCommunities": {
"description": "Message for no favorited communities on the drawer"
},
"noImages": "It looks like you have not uploaded any images.",
"@noImages": {
"description": "Message for no uploaded images"
},
"noInstanceBlocks": "No blocked instances.",
"@noInstanceBlocks": {},
"noItems": "No items",
Expand Down Expand Up @@ -1465,6 +1489,10 @@
"@noProfileBioSet": {
"description": "Message for no profile bio set"
},
"noReferencesToImage": "No posts or comments were found containing this image. However, it may be used elsewhere on the internet.",
"@noReferencesToImage": {
"description": "Message indicating media was not found on Lemmy"
},
"noReplies": "No replies",
"@noReplies": {
"description": "Label for when there are no replies in the list"
Expand Down Expand Up @@ -2613,6 +2641,10 @@
"@updateReleased": {},
"uploadImage": "Upload image",
"@uploadImage": {},
"uploadedDate": "Uploaded: {date}",
"@uploadedDate": {
"description": "Metadata for image uploads"
},
"upvote": "Upvote",
"@upvote": {
"description": "Action for upvoting a post/comment"
Expand Down
2 changes: 1 addition & 1 deletion lib/l10n/app_tr.arb
Original file line number Diff line number Diff line change
Expand Up @@ -2327,7 +2327,7 @@
"@unableToLoadImage": {
"description": "Bir ikili görüntüyü yükleyemediğimizde kullanılacak yer tutucu"
},
"unableToLoadImageFrom": "{Domain} adresinden resim yüklenemiyor",
"unableToLoadImageFrom": "{domain} adresinden resim yüklenemiyor",
"@unableToLoadImageFrom": {
"description": "URL'den bir resim yükleyemediğimizde kullanılacak yer tutucu"
},
Expand Down
111 changes: 111 additions & 0 deletions lib/user/bloc/user_settings_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import 'package:bloc/bloc.dart';
import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:equatable/equatable.dart';
import 'package:lemmy_api_client/pictrs.dart';
import 'package:lemmy_api_client/v3.dart';
import 'package:stream_transform/stream_transform.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import 'package:thunder/account/models/account.dart';
import 'package:thunder/core/auth/helpers/fetch_account.dart';
import 'package:thunder/core/models/post_view_media.dart';
import 'package:thunder/core/singletons/lemmy_client.dart';
import 'package:thunder/instance/utils/instance.dart';
import 'package:thunder/post/utils/post.dart';
import 'package:thunder/utils/error_messages.dart';
import 'package:thunder/utils/global_context.dart';

Expand Down Expand Up @@ -51,6 +55,17 @@ class UserSettingsBloc extends Bloc<UserSettingsEvent, UserSettingsState> {
_unblockPersonEvent,
transformer: throttleDroppable(throttleDuration),
);
on<ListMediaEvent>(
_listMediaEvent,
transformer: throttleDroppable(throttleDuration),
);
on<DeleteMediaEvent>(
_deleteMediaEvent,
// Do not use any transformer, because a throttleDroppable will only process the first request and restartable will only process the last.
);
on<FindMediaUsagesEvent>(
_findMediaUsagesEvent,
);
}

Future<void> _resetUserSettingsEvent(ResetUserSettingsEvent event, emit) async {
Expand Down Expand Up @@ -264,4 +279,100 @@ class UserSettingsBloc extends Bloc<UserSettingsEvent, UserSettingsState> {
errorMessage: e is LemmyApiException ? getErrorMessage(GlobalContext.context, e.message) : e.toString()));
}
}

Future<void> _listMediaEvent(ListMediaEvent event, emit) async {
LemmyApiV3 lemmy = LemmyClient.instance.lemmyApiV3;
Account? account = await fetchActiveProfileAccount();

emit(state.copyWith(status: UserSettingsStatus.listingMedia));

try {
int page = 1;
List<LocalImageView> images = [];
List<LocalImageView>? lastResponse;

while (lastResponse?.isEmpty != true) {
ListMediaResponse listMediaResponse = await lemmy.run(ListMedia(page: page, auth: account?.jwt));
images.addAll(lastResponse = listMediaResponse.images);
++page;
}

return emit(state.copyWith(status: UserSettingsStatus.succeededListingMedia, images: images));
} catch (e) {
return emit(state.copyWith(status: UserSettingsStatus.failedListingMedia, errorMessage: getExceptionErrorMessage(e)));
}
}

Future<void> _deleteMediaEvent(DeleteMediaEvent event, emit) async {
emit(state.copyWith(status: UserSettingsStatus.deletingMedia));

try {
// Optimistically remove the media from the list
state.images?.removeWhere((localImageView) => localImageView.localImage.pictrsAlias == event.id);

Account? account = await fetchActiveProfileAccount();

if (account?.jwt == null) return;

await PictrsApi(account!.instance!).delete(PictrsUploadFile(deleteToken: event.deleteToken, file: event.id), account.jwt);

return emit(state.copyWith(status: UserSettingsStatus.succeededListingMedia, images: state.images));
} catch (e) {
return emit(
state.copyWith(
status: UserSettingsStatus.failedListingMedia,
errorMessage: AppLocalizations.of(GlobalContext.context)!.errorDeletingImage(getExceptionErrorMessage(e)),
),
);
}
}

Future<void> _findMediaUsagesEvent(FindMediaUsagesEvent event, emit) async {
emit(state.copyWith(status: UserSettingsStatus.searchingMedia));

try {
LemmyApiV3 lemmy = LemmyClient.instance.lemmyApiV3;
Account? account = await fetchActiveProfileAccount();

String url = Uri.https(lemmy.host, 'pictrs/image/${event.id}').toString();

List<PostView> posts = (await lemmy.run(Search(
q: url,
type: SearchType.posts,
auth: account?.jwt,
)))
.posts
.toList(); // Copy so we can modify

List<PostView> postsByUrl = (await lemmy.run(Search(
q: url,
type: SearchType.url,
auth: account?.jwt,
)))
.posts;

// De-dup posts found by body and URL
posts.addAll(postsByUrl.where((postViewByUrl) => !posts.any((postView) => postView.post.id == postViewByUrl.post.id)));

final List<CommentView> comments = (await lemmy.run(Search(
q: url,
type: SearchType.comments,
auth: account?.jwt,
)))
.comments;

return emit(state.copyWith(
status: UserSettingsStatus.succeededSearchingMedia,
imageSearchPosts: await parsePostViews(posts),
imageSearchComments: comments,
));
} catch (e) {
return emit(
state.copyWith(
status: UserSettingsStatus.failedListingMedia,
errorMessage: getExceptionErrorMessage(e),
),
);
}
}
}
17 changes: 17 additions & 0 deletions lib/user/bloc/user_settings_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,20 @@ class UnblockPersonEvent extends UserSettingsEvent {

const UnblockPersonEvent({required this.personId, this.unblock = true});
}

class ListMediaEvent extends UserSettingsEvent {
const ListMediaEvent();
}

class DeleteMediaEvent extends UserSettingsEvent {
final String deleteToken;
final String id;

const DeleteMediaEvent({required this.deleteToken, required this.id});
}

class FindMediaUsagesEvent extends UserSettingsEvent {
final String id;

const FindMediaUsagesEvent({required this.id});
}
Loading
Loading