Files
Musify/lib/services/playlist_sharing.dart
2026-01-02 00:17:56 +04:00

91 lines
3.0 KiB
Dart

/*
* Copyright (C) 2026 Valeri Gokadze
*
* Musify is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Musify is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*
* For more information about Musify, including how to contribute,
* please visit: https://github.com/gokadzev/Musify
*/
import 'dart:convert';
import 'package:musify/main.dart';
import 'package:musify/services/proxy_manager.dart';
import 'package:musify/services/settings_manager.dart';
import 'package:musify/utilities/formatter.dart';
import 'package:youtube_explode_dart/youtube_explode_dart.dart';
class PlaylistSharingService {
static Map createCompactPlaylist(Map fullPlaylist) {
return {
'title': fullPlaylist['title'],
if (fullPlaylist['image'] != null) 'image': fullPlaylist['image'],
'source': 'user-created',
'list': fullPlaylist['list'].map((song) => song['ytid']).toList(),
};
}
static Future<Map> expandCompactPlaylist(Map compactPlaylist) async {
final List<dynamic> songIds = compactPlaylist['list'];
YoutubeExplode? ytClient;
try {
if (useProxy.value) {
ytClient = await ProxyManager().getYoutubeExplodeClient();
} else {
ytClient = ProxyManager().getClientSync();
}
final expandedSongs = await Future.wait(
songIds.map((ytid) async {
try {
final video = await ytClient!.videos.get(ytid);
return returnSongLayout(songIds.indexOf(ytid), video);
} catch (e, stackTrace) {
logger.log('Error expanding song: $ytid', e, stackTrace);
return null;
}
}),
);
return {
...compactPlaylist,
'list': expandedSongs.where((song) => song != null).toList(),
};
} finally {
try {
if (useProxy.value) {
ytClient?.close();
}
} catch (_) {}
}
}
static String encodePlaylist(Map playlist) {
final compactPlaylist = createCompactPlaylist(playlist);
return base64Url.encode(utf8.encode(json.encode(compactPlaylist)));
}
static Future<Map?> decodeAndExpandPlaylist(String encodedPlaylist) async {
try {
final jsonString = utf8.decode(base64Url.decode(encodedPlaylist));
final compactPlaylist = json.decode(jsonString) as Map;
return await expandCompactPlaylist(compactPlaylist);
} catch (e, stackTrace) {
logger.log('Failed to decode playlist', e, stackTrace);
return null;
}
}
}