Skip to content

Commit

Permalink
chore: 𝓼𝓸𝓶𝓮 𝓻𝓮𝓯𝓲𝓷𝓮𝓶𝓮𝓷𝓽𝓼
Browse files Browse the repository at this point in the history
  • Loading branch information
MSOB7YY committed Jul 16, 2024
1 parent 6bd6013 commit 57d437c
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 40 deletions.
8 changes: 4 additions & 4 deletions lib/base/audio_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -857,8 +857,8 @@ class NamidaAudioVideoHandler<Q extends Playable> extends BasicAudioHandler<Q> {
File? _ytNotificationVideoThumbnail;

/// Shows error if [marked] is not true.
void _onVideoMarkWatchResultError(bool? marked) {
if (marked != true) {
void _onVideoMarkWatchResultError(YTMarkVideoWatchedResult marked) {
if (marked == YTMarkVideoWatchedResult.addedAsPending) {
snackyy(message: 'Failed to mark video as watched.', top: false, isError: true);
}
}
Expand Down Expand Up @@ -1036,13 +1036,13 @@ class NamidaAudioVideoHandler<Q extends Playable> extends BasicAudioHandler<Q> {

if (checkInterrupted()) return;

Completer<bool?>? markedAsWatched;
Completer<YTMarkVideoWatchedResult>? markedAsWatched;

// only if was playing
if (okaySetFromCache() && (streamsResult != null || !ConnectivityController.inst.hasConnection)) {
// -- allow when no connection bcz this function won't try again with no connection,
// -- so we force call here and let `markVideoWatched` do the job when there is proper connection.
markedAsWatched = Completer<bool?>();
markedAsWatched = Completer<YTMarkVideoWatchedResult>();
markedAsWatched.complete(YoutubeInfoController.history.markVideoWatched(videoId: item.id, streamResult: streamsResult));
}

Expand Down
2 changes: 2 additions & 0 deletions lib/base/ports_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class IsolateFunctionReturnBuild<T> {
}

mixin PortsProvider<E> {
bool get isInitialized => _isInitialized ?? false;

Completer<SendPort>? _portCompleter;
ReceivePort? _recievePort;
StreamSubscription? _streamSub;
Expand Down
23 changes: 17 additions & 6 deletions lib/controller/thumbnail_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ class ThumbnailManager {

class _YTThumbnailDownloadManager with PortsProvider<SendPort> {
final _downloadCompleters = <String, Completer<File?>?>{}; // item id
final _requestsCountForId = <String, int>{}; // item id
final _shouldRetry = <String, bool>{}; // item id
final _notFoundThumbnails = <String, bool?>{}; // item id

Expand All @@ -213,8 +214,12 @@ class _YTThumbnailDownloadManager with PortsProvider<SendPort> {
if (onNotFound != null) onNotFound();
return null;
}

_requestsCountForId.update(id, (value) => value++, ifAbsent: () => 1);

if (forceRequest == false && _downloadCompleters[id] != null) {
final res = await _downloadCompleters[id]!.future;
_requestsCountForId.update(id, (value) => value--);
if (res != null || _shouldRetry[id] != true) {
return res;
}
Expand All @@ -231,11 +236,13 @@ class _YTThumbnailDownloadManager with PortsProvider<SendPort> {
'destinationFile': destinationFile,
'symlinkId': symlinkId,
};
await initialize();
if (!isInitialized) await initialize();
await sendPort(p);
final res = await _downloadCompleters[id]?.future;

if (_notFoundThumbnails[id] == true) {
_requestsCountForId.update(id, (value) => value--);

if (res == null && _notFoundThumbnails[id] == true) {
if (onNotFound != null) onNotFound();
return null;
}
Expand All @@ -244,9 +251,13 @@ class _YTThumbnailDownloadManager with PortsProvider<SendPort> {

Future<void> stopDownload({required String? id}) async {
if (id == null) return;
_onFileFinish(id, null, null, true);
final p = {'id': id, 'stop': true};
await sendPort(p);
final otherActiveRequests = _requestsCountForId[id];
if (otherActiveRequests == null || otherActiveRequests <= 1) {
// -- only close if active requests only 1
_onFileFinish(id, null, null, true);
final p = {'id': id, 'stop': true};
await sendPort(p);
}
}

static Future<void> _prepareDownloadResources(SendPort sendPort) async {
Expand Down Expand Up @@ -428,8 +439,8 @@ class _YTThumbnailDownloadManager with PortsProvider<SendPort> {

void _onFileFinish(String itemId, File? downloadedFile, bool? notfound, bool aborted) {
if (notfound != null) _notFoundThumbnails[itemId] = notfound;
_downloadCompleters[itemId]?.completeIfWasnt(downloadedFile);
_shouldRetry[itemId] = aborted;
_downloadCompleters[itemId]?.completeIfWasnt(downloadedFile);
}
}

Expand Down
14 changes: 9 additions & 5 deletions lib/core/functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ Future<void> showCalendarDialog<T extends ItemWithDate, E>({
);
}

Future<String> showNamidaBottomSheetWithTextField({
Future<String?> showNamidaBottomSheetWithTextField({
required BuildContext context,
bool isScrollControlled = true,
bool useRootNavigator = true,
Expand All @@ -625,6 +625,8 @@ Future<String> showNamidaBottomSheetWithTextField({
final focusNode = FocusNode();
focusNode.requestFocus();

String? finalText;

await Future.delayed(Duration.zero); // delay bcz sometimes doesnt show
await showModalBottomSheet(
// ignore: use_build_context_synchronously
Expand Down Expand Up @@ -674,8 +676,11 @@ Future<String> showNamidaBottomSheetWithTextField({
),
onTap: () async {
if (formKey.currentState!.validate()) {
final canPop = await onButtonTap(controller.text);
if (canPop && context.mounted) context.safePop();
final didAgree = await onButtonTap(controller.text);
if (didAgree) {
finalText = controller.text;
if (context.mounted) context.safePop();
}
}
},
),
Expand All @@ -688,9 +693,8 @@ Future<String> showNamidaBottomSheetWithTextField({
);
},
);
final t = controller.text;
controller.disposeAfterAnimation(also: focusNode.dispose);
return t;
return finalText;
}

// Returns a [0-1] scale representing how much similar both are.
Expand Down
2 changes: 1 addition & 1 deletion lib/ui/widgets/custom_widgets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ class CustomListTile extends StatelessWidget {
maxLines: subtitle != null ? 4 : 5,
overflow: TextOverflow.ellipsis,
),
subtitle: subtitle != null
subtitle: subtitle?.isNotEmpty == true
? Text(
subtitle!,
style: context.theme.textTheme.displaySmall,
Expand Down
17 changes: 14 additions & 3 deletions lib/youtube/controller/info_controllers/yt_history_linker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ class _YoutubeHistoryLinker {
_pendingRequestsCompleter = null;
}

Future<bool?> markVideoWatched({required String videoId, required VideoStreamsResult? streamResult, bool errorOnMissingParam = true}) async {
Future<YTMarkVideoWatchedResult> markVideoWatched({required String videoId, required VideoStreamsResult? streamResult, bool errorOnMissingParam = true}) async {
if (_dbOpenedAccId == null) return YTMarkVideoWatchedResult.noAccount; // no acc signed in

if (_hasPendingRequests) {
executePendingRequests();
}
Expand Down Expand Up @@ -167,10 +169,13 @@ class _YoutubeHistoryLinker {
}
}
if (added) {
return added;
return YTMarkVideoWatchedResult.marked;
} else {
// -- the handling of executing pending requests is different.
// -- even if `added` is false due to missing params/etc, it will
// -- properly get removed while exeuting pending.
_addPendingRequest(videoId: videoId, streamResult: streamResult);
return null;
return YTMarkVideoWatchedResult.addedAsPending;
}
}

Expand All @@ -183,3 +188,9 @@ class _YoutubeHistoryLinker {
return cache.read();
}
}

enum YTMarkVideoWatchedResult {
noAccount,
marked,
addedAsPending,
}
2 changes: 1 addition & 1 deletion lib/youtube/functions/yt_playlist_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ extension YoutubePlaylistShare on YoutubePlaylist {
return deleted;
}

Future<String> showRenamePlaylistSheet({
Future<String?> showRenamePlaylistSheet({
required BuildContext context,
required String playlistName,
}) async {
Expand Down
2 changes: 1 addition & 1 deletion lib/youtube/pages/user/youtube_account_manage_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ part 'youtube_manage_subscription_page.dart';

class YoutubeAccountManagePage extends StatelessWidget with NamidaRouteWidget {
@override
RouteType get route => RouteType.YOUTUBE_USER_MANAGE_SUBSCRIPTION_SUBPAGE;
RouteType get route => RouteType.YOUTUBE_USER_MANAGE_ACCOUNT_SUBPAGE;

const YoutubeAccountManagePage({super.key});

Expand Down
40 changes: 29 additions & 11 deletions lib/youtube/pages/youtube_main_page_fetcher_acc_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class YoutubeMainPageFetcherAccBase<W extends YoutiPieListWrapper<T>, T extends
final bool isHorizontal;
final double? horizontalHeight;
final double topPadding;
final double? bottomPadding;
final Future<void> Function()? onPullToRefresh;
final bool enablePullToRefresh;
final void Function(W? result)? onListUpdated;
Expand All @@ -58,6 +59,7 @@ class YoutubeMainPageFetcherAccBase<W extends YoutiPieListWrapper<T>, T extends
this.isHorizontal = false,
this.horizontalHeight,
this.topPadding = 24.0,
this.bottomPadding,
this.onPullToRefresh,
this.enablePullToRefresh = true,
this.onListUpdated,
Expand Down Expand Up @@ -101,17 +103,19 @@ class _YoutubePageState<W extends YoutiPieListWrapper<T>, T extends MapSerializa
);
}

@override
void initState() {
super.initState();

void _onInit({bool forceRequest = false}) async {
bool needNewRequest = false;
final lastFetchedTime = _resultsFetchTime[W];
if (_hasConnection) {
if (lastFetchedTime == null) {
needNewRequest = true;
} else if (lastFetchedTime.difference(DateTime.now()).abs() > const Duration(seconds: 180)) {
needNewRequest = true;

if (forceRequest) {
needNewRequest = true;
} else {
final lastFetchedTime = _resultsFetchTime[W];
if (_hasConnection) {
if (lastFetchedTime == null) {
needNewRequest = true;
} else if (lastFetchedTime.difference(DateTime.now()).abs() > const Duration(seconds: 180)) {
needNewRequest = true;
}
}
}

Expand All @@ -129,12 +133,24 @@ class _YoutubePageState<W extends YoutiPieListWrapper<T>, T extends MapSerializa
} else {
_fetchFeed();
}
}

void _onAccChanged() {
_onInit(forceRequest: true);
}

@override
void initState() {
super.initState();
_onInit();
YoutubeAccountController.current.addOnAccountChanged(_onAccChanged);
if (widget.onListUpdated != null) _currentFeed.addListener(_onListUpdated);
}

@override
void dispose() {
if (widget.onListUpdated != null) _currentFeed.removeListener(_onListUpdated);
YoutubeAccountController.current.removeOnAccountChanged(_onAccChanged);

_controller.dispose();
_isLoadingCurrentFeed.close();
Expand Down Expand Up @@ -165,6 +181,7 @@ class _YoutubePageState<W extends YoutiPieListWrapper<T>, T extends MapSerializa
_resultsFetchTime[W] = DateTime.now();
if (val != null) {
_currentFeed.value = val;
_lastFetchWasCached.value = false;
} else {
_lastFetchWasCached.value = true;
}
Expand Down Expand Up @@ -227,7 +244,7 @@ class _YoutubePageState<W extends YoutiPieListWrapper<T>, T extends MapSerializa
);
}

final pagePadding = EdgeInsets.only(top: widget.topPadding, bottom: Dimensions.inst.globalBottomPaddingTotalR);
final pagePadding = EdgeInsets.only(top: widget.topPadding, bottom: widget.bottomPadding ?? Dimensions.inst.globalBottomPaddingTotalR);

final EdgeInsets firstPadding;
final EdgeInsets lastPadding;
Expand Down Expand Up @@ -256,6 +273,7 @@ class _YoutubePageState<W extends YoutiPieListWrapper<T>, T extends MapSerializa
padding: pagePadding,
child: Column(
children: [
if (widget.pageHeader != null) widget.pageHeader!,
Align(
alignment: Alignment.centerLeft,
child: header,
Expand Down
7 changes: 2 additions & 5 deletions lib/youtube/pages/yt_playlist_subpage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,8 @@ class _YTNormalPlaylistSubpageState extends State<YTNormalPlaylistSubpage> {
title: lang.RENAME_PLAYLIST,
onTap: () async {
final newName = await playlist.showRenamePlaylistSheet(context: context, playlistName: playlistCurrentName);
if (context.mounted) {
refreshState(() {
playlistCurrentName = newName;
});
}
if (newName == null) return;
refreshState(() => playlistCurrentName = newName);
},
),
NamidaPopupItem(
Expand Down
4 changes: 2 additions & 2 deletions lib/youtube/widgets/yt_download_task_item_card.dart
Original file line number Diff line number Diff line change
Expand Up @@ -422,12 +422,12 @@ class YTDownloadTaskItemCard extends StatelessWidget {
);
}

Future<String> _onRenameIconTap({
Future<void> _onRenameIconTap({
required BuildContext context,
required YoutubeItemDownloadConfig config,
required DownloadTaskGroupName groupName,
}) async {
return await showNamidaBottomSheetWithTextField(
await showNamidaBottomSheetWithTextField(
context: context,
initalControllerText: config.filename.filename,
title: lang.RENAME,
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: namida
description: A Beautiful and Feature-rich Music Player, With YouTube & Video Support Built in Flutter
publish_to: "none"
version: 3.3.5-beta+240716218
version: 3.3.7-beta+240716229

environment:
sdk: ">=3.4.0 <4.0.0"
Expand Down

0 comments on commit 57d437c

Please sign in to comment.