2020-10-09 20:52:45 +02:00
|
|
|
import 'dart:async';
|
2020-09-09 20:50:15 +02:00
|
|
|
|
2020-06-23 21:23:12 +02:00
|
|
|
import 'package:disk_space/disk_space.dart';
|
2020-10-09 20:52:45 +02:00
|
|
|
import 'package:filesize/filesize.dart';
|
2020-10-19 21:28:45 +02:00
|
|
|
import 'package:flutter/material.dart';
|
2020-06-23 21:23:12 +02:00
|
|
|
import 'package:flutter/services.dart';
|
2020-10-10 22:51:20 +02:00
|
|
|
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
2020-10-09 20:52:45 +02:00
|
|
|
import 'package:fluttertoast/fluttertoast.dart';
|
|
|
|
import 'package:freezer/api/deezer.dart';
|
|
|
|
import 'package:freezer/api/definitions.dart';
|
|
|
|
import 'package:freezer/settings.dart';
|
2020-06-23 21:23:12 +02:00
|
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import 'package:path/path.dart' as p;
|
|
|
|
import 'package:permission_handler/permission_handler.dart';
|
2020-10-09 20:52:45 +02:00
|
|
|
import 'package:freezer/translations.i18n.dart';
|
2020-06-23 21:23:12 +02:00
|
|
|
|
|
|
|
import 'dart:io';
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
import 'package:sqflite/sqflite.dart';
|
|
|
|
import 'package:sqflite/sql.dart';
|
2020-06-23 21:23:12 +02:00
|
|
|
|
|
|
|
DownloadManager downloadManager = DownloadManager();
|
|
|
|
|
|
|
|
class DownloadManager {
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Platform channels
|
|
|
|
static MethodChannel platform = MethodChannel('f.f.freezer/native');
|
|
|
|
static EventChannel eventChannel = EventChannel('f.f.freezer/downloads');
|
|
|
|
|
|
|
|
bool running = false;
|
|
|
|
int queueSize = 0;
|
|
|
|
|
|
|
|
StreamController serviceEvents = StreamController.broadcast();
|
|
|
|
String offlinePath;
|
2020-06-23 21:23:12 +02:00
|
|
|
Database db;
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Start/Resume downloads
|
|
|
|
Future start() async {
|
|
|
|
await updateServiceSettings();
|
|
|
|
await platform.invokeMethod('start');
|
|
|
|
}
|
|
|
|
|
|
|
|
//Stop/Pause downloads
|
|
|
|
Future stop() async {
|
|
|
|
await platform.invokeMethod('stop');
|
|
|
|
}
|
2020-06-23 21:23:12 +02:00
|
|
|
|
|
|
|
Future init() async {
|
2020-10-09 20:52:45 +02:00
|
|
|
//Remove old DB
|
|
|
|
File oldDbFile = File(p.join((await getDatabasesPath()), 'offline.db'));
|
|
|
|
if (await oldDbFile.exists()) {
|
|
|
|
await oldDbFile.delete();
|
|
|
|
}
|
|
|
|
|
|
|
|
String dbPath = p.join((await getDatabasesPath()), 'offline2.db');
|
|
|
|
//Open db
|
2020-06-23 21:23:12 +02:00
|
|
|
db = await openDatabase(
|
2020-10-09 20:52:45 +02:00
|
|
|
dbPath,
|
2020-06-23 21:23:12 +02:00
|
|
|
version: 1,
|
|
|
|
onCreate: (Database db, int version) async {
|
|
|
|
Batch b = db.batch();
|
2020-10-09 20:52:45 +02:00
|
|
|
//Create tables, if doesn't exit
|
|
|
|
b.execute("""CREATE TABLE Tracks (
|
|
|
|
id TEXT PRIMARY KEY, title TEXT, album TEXT, artists TEXT, duration INTEGER, albumArt TEXT, trackNumber INTEGER, offline INTEGER, lyrics TEXT, favorite INTEGER, diskNumber INTEGER, explicit INTEGER)""");
|
|
|
|
b.execute("""CREATE TABLE Albums (
|
|
|
|
id TEXT PRIMARY KEY, title TEXT, artists TEXT, tracks TEXT, art TEXT, fans INTEGER, offline INTEGER, library INTEGER, type INTEGER, releaseDate TEXT)""");
|
|
|
|
b.execute("""CREATE TABLE Artists (
|
|
|
|
id TEXT PRIMARY KEY, name TEXT, albums TEXT, topTracks TEXT, picture TEXT, fans INTEGER, albumCount INTEGER, offline INTEGER, library INTEGER, radio INTEGER)""");
|
|
|
|
b.execute("""CREATE TABLE Playlists (
|
2020-06-23 21:23:12 +02:00
|
|
|
id TEXT PRIMARY KEY, title TEXT, tracks TEXT, image TEXT, duration INTEGER, userId TEXT, userName TEXT, fans INTEGER, library INTEGER, description TEXT)""");
|
|
|
|
await b.commit();
|
|
|
|
}
|
|
|
|
);
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
//Create offline directory
|
|
|
|
offlinePath = p.join((await getExternalStorageDirectory()).path, 'offline/');
|
|
|
|
await Directory(offlinePath).create(recursive: true);
|
|
|
|
|
|
|
|
//Update settings
|
|
|
|
await updateServiceSettings();
|
|
|
|
|
|
|
|
//Listen to state change event
|
|
|
|
eventChannel.receiveBroadcastStream().listen((e) {
|
|
|
|
if (e['action'] == 'onStateChange') {
|
|
|
|
running = e['running'];
|
|
|
|
queueSize = e['queueSize'];
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
//Forward
|
|
|
|
serviceEvents.add(e);
|
2020-06-23 21:23:12 +02:00
|
|
|
});
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
await platform.invokeMethod('loadDownloads');
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get all downloads from db
|
|
|
|
Future<List<Download>> getDownloads() async {
|
|
|
|
List raw = await platform.invokeMethod('getDownloads');
|
|
|
|
return raw.map((d) => Download.fromJson(d)).toList();
|
|
|
|
}
|
2020-09-22 19:13:54 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Insert track and metadata to DB
|
|
|
|
Future _addTrackToDB(Batch batch, Track track, bool overwriteTrack) async {
|
|
|
|
batch.insert('Tracks', track.toSQL(off: true), conflictAlgorithm: overwriteTrack?ConflictAlgorithm.replace:ConflictAlgorithm.ignore);
|
|
|
|
batch.insert('Albums', track.album.toSQL(off: false), conflictAlgorithm: ConflictAlgorithm.ignore);
|
|
|
|
//Artists
|
|
|
|
for (Artist a in track.artists) {
|
|
|
|
batch.insert('Artists', a.toSQL(off: false), conflictAlgorithm: ConflictAlgorithm.ignore);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
return batch;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-19 21:28:45 +02:00
|
|
|
//Quality selector for custom quality
|
|
|
|
Future qualitySelect(BuildContext context) async {
|
|
|
|
AudioQuality quality;
|
|
|
|
await showModalBottomSheet(
|
|
|
|
context: context,
|
|
|
|
builder: (context) {
|
|
|
|
return Column(
|
|
|
|
mainAxisSize: MainAxisSize.min,
|
|
|
|
children: [
|
|
|
|
Padding(
|
|
|
|
padding: EdgeInsets.fromLTRB(0, 12, 0, 2),
|
|
|
|
child: Text(
|
|
|
|
'Quality'.i18n,
|
|
|
|
style: TextStyle(
|
|
|
|
fontWeight: FontWeight.bold,
|
|
|
|
fontSize: 20.0
|
|
|
|
),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
ListTile(
|
|
|
|
title: Text('MP3 128kbps'),
|
|
|
|
onTap: () {
|
|
|
|
quality = AudioQuality.MP3_128;
|
|
|
|
Navigator.of(context).pop();
|
|
|
|
},
|
|
|
|
),
|
|
|
|
ListTile(
|
|
|
|
title: Text('MP3 320kbps'),
|
|
|
|
onTap: () {
|
|
|
|
quality = AudioQuality.MP3_320;
|
|
|
|
Navigator.of(context).pop();
|
|
|
|
},
|
|
|
|
),
|
|
|
|
ListTile(
|
|
|
|
title: Text('FLAC'),
|
|
|
|
onTap: () {
|
|
|
|
quality = AudioQuality.FLAC;
|
|
|
|
Navigator.of(context).pop();
|
|
|
|
},
|
|
|
|
)
|
|
|
|
],
|
|
|
|
);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
return quality;
|
|
|
|
}
|
|
|
|
|
2020-12-04 18:02:50 +01:00
|
|
|
Future<bool> addOfflineTrack(Track track, {private = true, BuildContext context, isSingleton = false}) async {
|
2020-10-09 20:52:45 +02:00
|
|
|
//Permission
|
2020-10-19 21:28:45 +02:00
|
|
|
if (!private && !(await checkPermission())) return false;
|
|
|
|
|
|
|
|
//Ask for quality
|
|
|
|
AudioQuality quality;
|
|
|
|
if (!private && settings.downloadQuality == AudioQuality.ASK) {
|
|
|
|
quality = await qualitySelect(context);
|
|
|
|
if (quality == null) return false;
|
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
|
2020-12-04 18:02:50 +01:00
|
|
|
//Fetch track if missing meta
|
|
|
|
if (track.artists == null || track.artists.length == 0 || track.album == null)
|
|
|
|
track = await deezerAPI.track(track.id);
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Add to DB
|
|
|
|
if (private) {
|
|
|
|
Batch b = db.batch();
|
|
|
|
b = await _addTrackToDB(b, track, true);
|
|
|
|
await b.commit();
|
2020-10-10 22:51:20 +02:00
|
|
|
|
|
|
|
//Cache art
|
|
|
|
DefaultCacheManager().getSingleFile(track.albumArt.thumb);
|
|
|
|
DefaultCacheManager().getSingleFile(track.albumArt.full);
|
2020-09-09 20:50:15 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get path
|
2020-12-04 18:02:50 +01:00
|
|
|
String path = _generatePath(track, private, isSingleton: isSingleton);
|
2020-10-19 21:28:45 +02:00
|
|
|
await platform.invokeMethod('addDownloads', [await Download.jsonFromTrack(track, path, private: private, quality: quality)]);
|
2020-10-09 20:52:45 +02:00
|
|
|
await start();
|
2020-12-04 18:02:50 +01:00
|
|
|
return true;
|
2020-09-09 20:50:15 +02:00
|
|
|
}
|
|
|
|
|
2020-10-19 21:28:45 +02:00
|
|
|
Future addOfflineAlbum(Album album, {private = true, BuildContext context}) async {
|
2020-10-09 20:52:45 +02:00
|
|
|
//Permission
|
|
|
|
if (!private && !(await checkPermission())) return;
|
2020-06-23 21:23:12 +02:00
|
|
|
|
2020-10-19 21:28:45 +02:00
|
|
|
//Ask for quality
|
|
|
|
AudioQuality quality;
|
|
|
|
if (!private && settings.downloadQuality == AudioQuality.ASK) {
|
|
|
|
quality = await qualitySelect(context);
|
|
|
|
if (quality == null) return false;
|
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get from API if no tracks
|
|
|
|
if (album.tracks == null || album.tracks.length == 0) {
|
|
|
|
album = await deezerAPI.album(album.id);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Add to DB
|
|
|
|
if (private) {
|
2020-10-10 22:51:20 +02:00
|
|
|
//Cache art
|
|
|
|
DefaultCacheManager().getSingleFile(album.art.thumb);
|
|
|
|
DefaultCacheManager().getSingleFile(album.art.full);
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
Batch b = db.batch();
|
|
|
|
b.insert('Albums', album.toSQL(off: true), conflictAlgorithm: ConflictAlgorithm.replace);
|
|
|
|
for (Track t in album.tracks) {
|
|
|
|
b = await _addTrackToDB(b, t, false);
|
|
|
|
}
|
|
|
|
await b.commit();
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Create downloads
|
|
|
|
List<Map> out = [];
|
|
|
|
for (Track t in album.tracks) {
|
2020-10-19 21:28:45 +02:00
|
|
|
out.add(await Download.jsonFromTrack(t, _generatePath(t, private), private: private, quality: quality));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
await platform.invokeMethod('addDownloads', out);
|
|
|
|
await start();
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-19 21:28:45 +02:00
|
|
|
Future addOfflinePlaylist(Playlist playlist, {private = true, BuildContext context, AudioQuality quality}) async {
|
2020-10-09 20:52:45 +02:00
|
|
|
//Permission
|
|
|
|
if (!private && !(await checkPermission())) return;
|
2020-06-23 21:23:12 +02:00
|
|
|
|
2020-10-19 21:28:45 +02:00
|
|
|
//Ask for quality
|
|
|
|
if (!private && settings.downloadQuality == AudioQuality.ASK && quality == null) {
|
|
|
|
quality = await qualitySelect(context);
|
|
|
|
if (quality == null) return false;
|
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get tracks if missing
|
|
|
|
if (playlist.tracks == null || playlist.tracks.length < playlist.trackCount) {
|
|
|
|
playlist = await deezerAPI.fullPlaylist(playlist.id);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
//Add to DB
|
|
|
|
if (private) {
|
|
|
|
Batch b = db.batch();
|
|
|
|
b.insert('Playlists', playlist.toSQL(), conflictAlgorithm: ConflictAlgorithm.replace);
|
|
|
|
for (Track t in playlist.tracks) {
|
|
|
|
b = await _addTrackToDB(b, t, false);
|
2020-10-10 22:51:20 +02:00
|
|
|
//Cache art
|
|
|
|
DefaultCacheManager().getSingleFile(t.albumArt.thumb);
|
|
|
|
DefaultCacheManager().getSingleFile(t.albumArt.full);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
await b.commit();
|
|
|
|
}
|
|
|
|
|
|
|
|
//Generate downloads
|
|
|
|
List<Map> out = [];
|
|
|
|
for (int i=0; i<playlist.tracks.length; i++) {
|
|
|
|
Track t = playlist.tracks[i];
|
|
|
|
out.add(await Download.jsonFromTrack(t, _generatePath(
|
|
|
|
t,
|
|
|
|
private,
|
|
|
|
playlistName: playlist.title,
|
2020-10-19 21:28:45 +02:00
|
|
|
playlistTrackNumber: i,
|
|
|
|
), private: private, quality: quality));
|
2020-10-09 20:52:45 +02:00
|
|
|
}
|
|
|
|
await platform.invokeMethod('addDownloads', out);
|
|
|
|
await start();
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get track and meta from offline DB
|
|
|
|
Future<Track> getOfflineTrack(String id, {Album album, List<Artist> artists}) async {
|
|
|
|
List tracks = await db.query('Tracks', where: 'id == ?', whereArgs: [id]);
|
2020-06-23 21:23:12 +02:00
|
|
|
if (tracks.length == 0) return null;
|
2020-10-09 20:52:45 +02:00
|
|
|
Track track = Track.fromSQL(tracks[0]);
|
|
|
|
|
|
|
|
//Get album
|
|
|
|
if (album == null) {
|
|
|
|
List rawAlbums = await db.query('Albums', where: 'id == ?', whereArgs: [track.album.id]);
|
|
|
|
if (rawAlbums.length > 0)
|
|
|
|
track.album = Album.fromSQL(rawAlbums[0]);
|
|
|
|
} else {
|
|
|
|
track.album = album;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
//Get artists
|
|
|
|
if (artists == null) {
|
|
|
|
List<Artist> newArtists = [];
|
|
|
|
for (Artist artist in track.artists) {
|
|
|
|
List rawArtist = await db.query('Artists', where: 'id == ?', whereArgs: [artist.id]);
|
|
|
|
if (rawArtist.length > 0)
|
|
|
|
newArtists.add(Artist.fromSQL(rawArtist[0]));
|
|
|
|
}
|
|
|
|
if (newArtists.length > 0)
|
|
|
|
track.artists = newArtists;
|
|
|
|
} else {
|
|
|
|
track.artists = artists;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
return track;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
//Get offline library tracks
|
|
|
|
Future<List<Track>> getOfflineTracks() async {
|
|
|
|
List rawTracks = await db.query('Tracks', where: 'library == 1 AND offline == 1', columns: ['id']);
|
|
|
|
List<Track> out = [];
|
|
|
|
//Load track meta individually
|
|
|
|
for (Map rawTrack in rawTracks) {
|
|
|
|
out.add(await getOfflineTrack(rawTrack['id']));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
return out;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get all offline available tracks
|
|
|
|
Future<List<Track>> allOfflineTracks() async {
|
|
|
|
List rawTracks = await db.query('Tracks', where: 'offline == 1', columns: ['id']);
|
|
|
|
List<Track> out = [];
|
|
|
|
//Load track meta individually
|
|
|
|
for (Map rawTrack in rawTracks) {
|
|
|
|
out.add(await getOfflineTrack(rawTrack['id']));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
return out;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get all offline albums
|
|
|
|
Future<List<Album>> getOfflineAlbums() async {
|
|
|
|
List rawAlbums = await db.query('Albums', where: 'offline == 1', columns: ['id']);
|
|
|
|
List<Album> out = [];
|
|
|
|
//Load each album
|
|
|
|
for (Map rawAlbum in rawAlbums) {
|
|
|
|
out.add(await getOfflineAlbum(rawAlbum['id']));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
return out;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get offline album with meta
|
|
|
|
Future<Album> getOfflineAlbum(String id) async {
|
|
|
|
List rawAlbums = await db.query('Albums', where: 'id == ?', whereArgs: [id]);
|
|
|
|
if (rawAlbums.length == 0) return null;
|
|
|
|
Album album = Album.fromSQL(rawAlbums[0]);
|
2020-06-23 21:23:12 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
List<Track> tracks = [];
|
|
|
|
//Load tracks
|
|
|
|
for (int i=0; i<album.tracks.length; i++) {
|
|
|
|
tracks.add(await getOfflineTrack(album.tracks[i].id, album: album));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
album.tracks = tracks;
|
|
|
|
//Load artists
|
|
|
|
List<Artist> artists = [];
|
|
|
|
for (int i=0; i<album.artists.length; i++) {
|
|
|
|
artists.add((await getOfflineArtist(album.artists[i].id))??album.artists[i]);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
album.artists = artists;
|
2020-06-23 21:23:12 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
return album;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get offline artist METADATA, not tracks
|
|
|
|
Future<Artist> getOfflineArtist(String id) async {
|
|
|
|
List rawArtists = await db.query("Artists", where: 'id == ?', whereArgs: [id]);
|
|
|
|
if (rawArtists.length == 0) return null;
|
|
|
|
return Artist.fromSQL(rawArtists[0]);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get all offline playlists
|
|
|
|
Future<List<Playlist>> getOfflinePlaylists() async {
|
|
|
|
List rawPlaylists = await db.query('Playlists', columns: ['id']);
|
|
|
|
List<Playlist> out = [];
|
|
|
|
for (Map rawPlaylist in rawPlaylists) {
|
|
|
|
out.add(await getPlaylist(rawPlaylist['id']));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
return out;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Get offline playlist
|
|
|
|
Future<Playlist> getPlaylist(String id) async {
|
|
|
|
List rawPlaylists = await db.query('Playlists', where: 'id == ?', whereArgs: [id]);
|
|
|
|
if (rawPlaylists.length == 0) return null;
|
|
|
|
Playlist playlist = Playlist.fromSQL(rawPlaylists[0]);
|
|
|
|
//Load tracks
|
|
|
|
List<Track> tracks = [];
|
2020-06-23 21:23:12 +02:00
|
|
|
for (Track t in playlist.tracks) {
|
2020-10-09 20:52:45 +02:00
|
|
|
tracks.add(await getOfflineTrack(t.id));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
playlist.tracks = tracks;
|
|
|
|
return playlist;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future removeOfflineTracks(List<Track> tracks) async {
|
|
|
|
for (Track t in tracks) {
|
|
|
|
//Check if library
|
|
|
|
List rawTrack = await db.query('Tracks', where: 'id == ?', whereArgs: [t.id], columns: ['favorite']);
|
|
|
|
if (rawTrack.length > 0 && rawTrack[0]['favorite'] == 0) {
|
|
|
|
//Count occurrences in playlists and albums
|
|
|
|
List albums = await db.rawQuery('SELECT (id) FROM Albums WHERE tracks LIKE "%${t.id}%"');
|
|
|
|
List playlists = await db.rawQuery('SELECT (id) FROM Playlists WHERE tracks LIKE "%${t.id}%"');
|
|
|
|
if (albums.length + playlists.length == 0) {
|
|
|
|
//Safe to remove
|
|
|
|
await db.delete('Tracks', where: 'id == ?', whereArgs: [t.id]);
|
|
|
|
//Remove file
|
|
|
|
try {
|
|
|
|
File(p.join(offlinePath, t.id)).delete();
|
|
|
|
} catch (e) {
|
|
|
|
print(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Future removeOfflineAlbum(String id) async {
|
|
|
|
//Get album
|
|
|
|
List rawAlbums = await db.query('Albums', where: 'id == ?', whereArgs: [id]);
|
|
|
|
if (rawAlbums.length == 0) return;
|
|
|
|
Album album = Album.fromSQL(rawAlbums[0]);
|
|
|
|
//Remove album
|
|
|
|
await db.delete('Albums', where: 'id == ?', whereArgs: [id]);
|
|
|
|
//Remove tracks
|
|
|
|
await removeOfflineTracks(album.tracks);
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
Future removeOfflinePlaylist(String id) async {
|
|
|
|
//Fetch playlist
|
|
|
|
List rawPlaylists = await db.query('Playlists', where: 'id == ?', whereArgs: [id]);
|
|
|
|
if (rawPlaylists.length == 0) return;
|
|
|
|
Playlist playlist = Playlist.fromSQL(rawPlaylists[0]);
|
|
|
|
//Remove playlist
|
|
|
|
await db.delete('Playlists', where: 'id == ?', whereArgs: [id]);
|
|
|
|
await removeOfflineTracks(playlist.tracks);
|
|
|
|
}
|
2020-06-23 21:23:12 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Check if album, track or playlist is offline
|
|
|
|
Future<bool> checkOffline({Album album, Track track, Playlist playlist}) async {
|
|
|
|
//Track
|
2020-06-23 21:23:12 +02:00
|
|
|
if (track != null) {
|
2020-10-09 20:52:45 +02:00
|
|
|
List res = await db.query('Tracks', where: 'id == ? AND offline == 1', whereArgs: [track.id]);
|
2020-06-23 21:23:12 +02:00
|
|
|
if (res.length == 0) return false;
|
|
|
|
return true;
|
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
//Album
|
2020-06-23 21:23:12 +02:00
|
|
|
if (album != null) {
|
2020-10-09 20:52:45 +02:00
|
|
|
List res = await db.query('Albums', where: 'id == ? AND offline == 1', whereArgs: [album.id]);
|
2020-06-23 21:23:12 +02:00
|
|
|
if (res.length == 0) return false;
|
|
|
|
return true;
|
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
//Playlist
|
2020-10-19 21:28:45 +02:00
|
|
|
if (playlist != null && playlist.id != null) {
|
2020-10-09 20:52:45 +02:00
|
|
|
List res = await db.query('Playlists', where: 'id == ?', whereArgs: [playlist.id]);
|
2020-06-23 21:23:12 +02:00
|
|
|
if (res.length == 0) return false;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Offline search
|
|
|
|
Future<SearchResults> search(String query) async {
|
2020-10-09 20:52:45 +02:00
|
|
|
SearchResults results = SearchResults(tracks: [], albums: [], artists: [], playlists: []);
|
2020-06-23 21:23:12 +02:00
|
|
|
//Tracks
|
2020-10-15 20:37:36 +02:00
|
|
|
List tracksData = await db.rawQuery('SELECT * FROM Tracks WHERE offline == 1 AND title like "%$query%"');
|
2020-06-23 21:23:12 +02:00
|
|
|
for (Map trackData in tracksData) {
|
2020-10-09 20:52:45 +02:00
|
|
|
results.tracks.add(await getOfflineTrack(trackData['id']));
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
//Albums
|
2020-10-15 20:37:36 +02:00
|
|
|
List albumsData = await db.rawQuery('SELECT (id) FROM Albums WHERE offline == 1 AND title like "%$query%"');
|
2020-10-09 20:52:45 +02:00
|
|
|
for (Map rawAlbum in albumsData) {
|
|
|
|
results.albums.add(await getOfflineAlbum(rawAlbum['id']));
|
|
|
|
}
|
2020-06-23 21:23:12 +02:00
|
|
|
//Playlists
|
2020-10-15 20:37:36 +02:00
|
|
|
List playlists = await db.rawQuery('SELECT * FROM Playlists WHERE title like "%$query%"');
|
2020-06-23 21:23:12 +02:00
|
|
|
for (Map playlist in playlists) {
|
|
|
|
results.playlists.add(await getPlaylist(playlist['id']));
|
|
|
|
}
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Sanitize filename
|
|
|
|
String sanitize(String input) {
|
|
|
|
RegExp sanitize = RegExp(r'[\/\\\?\%\*\:\|\"\<\>]');
|
|
|
|
return input.replaceAll(sanitize, '');
|
|
|
|
}
|
|
|
|
|
|
|
|
//Generate track download path
|
2020-12-04 18:02:50 +01:00
|
|
|
String _generatePath(Track track, bool private, {String playlistName, int playlistTrackNumber, bool isSingleton = false}) {
|
2020-10-09 20:52:45 +02:00
|
|
|
String path;
|
|
|
|
if (private) {
|
|
|
|
path = p.join(offlinePath, track.id);
|
|
|
|
} else {
|
|
|
|
//Download path
|
|
|
|
path = settings.downloadPath;
|
|
|
|
|
|
|
|
if (settings.playlistFolder && playlistName != null)
|
|
|
|
path = p.join(path, sanitize(playlistName));
|
|
|
|
|
|
|
|
if (settings.artistFolder)
|
2020-10-10 22:51:20 +02:00
|
|
|
path = p.join(path, '%artist%');
|
2020-10-09 20:52:45 +02:00
|
|
|
|
|
|
|
//Album folder / with disk number
|
|
|
|
if (settings.albumFolder) {
|
|
|
|
if (settings.albumDiscFolder) {
|
2020-10-15 20:37:36 +02:00
|
|
|
path = p.join(path, '%album%' + ' - Disk ' + (track.diskNumber??1).toString());
|
2020-10-09 20:52:45 +02:00
|
|
|
} else {
|
2020-10-10 22:51:20 +02:00
|
|
|
path = p.join(path, '%album%');
|
2020-10-09 20:52:45 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
//Final path
|
2020-12-04 18:02:50 +01:00
|
|
|
path = p.join(path, isSingleton ? settings.singletonFilename : settings.downloadFilename);
|
2020-10-09 20:52:45 +02:00
|
|
|
//Playlist track number variable (not accessible in service)
|
|
|
|
if (playlistTrackNumber != null) {
|
|
|
|
path = path.replaceAll('%playlistTrackNumber%', playlistTrackNumber.toString());
|
|
|
|
path = path.replaceAll('%0playlistTrackNumber%', playlistTrackNumber.toString().padLeft(2, '0'));
|
|
|
|
} else {
|
|
|
|
path = path.replaceAll('%playlistTrackNumber%', '');
|
|
|
|
path = path.replaceAll('%0playlistTrackNumber%', '');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return path;
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
//Get stats for library screen
|
|
|
|
Future<List<String>> getStats() async {
|
|
|
|
//Get offline counts
|
2020-10-15 20:37:36 +02:00
|
|
|
int trackCount = (await db.rawQuery('SELECT COUNT(*) FROM Tracks WHERE offline == 1'))[0]['COUNT(*)'];
|
|
|
|
int albumCount = (await db.rawQuery('SELECT COUNT(*) FROM Albums WHERE offline == 1'))[0]['COUNT(*)'];
|
|
|
|
int playlistCount = (await db.rawQuery('SELECT COUNT(*) FROM Playlists'))[0]['COUNT(*)'];
|
2020-06-23 21:23:12 +02:00
|
|
|
//Free space
|
|
|
|
double diskSpace = await DiskSpace.getFreeDiskSpace;
|
|
|
|
//Used space
|
2020-10-09 20:52:45 +02:00
|
|
|
List<FileSystemEntity> offlineStat = await Directory(offlinePath).list().toList();
|
2020-06-23 21:23:12 +02:00
|
|
|
int offlineSize = 0;
|
|
|
|
for (var fs in offlineStat) {
|
|
|
|
offlineSize += (await fs.stat()).size;
|
|
|
|
}
|
2020-10-09 20:52:45 +02:00
|
|
|
//Return in list, //TODO: Make into class in future
|
2020-06-23 21:23:12 +02:00
|
|
|
return ([
|
|
|
|
trackCount.toString(),
|
|
|
|
albumCount.toString(),
|
|
|
|
playlistCount.toString(),
|
|
|
|
filesize(offlineSize),
|
|
|
|
filesize((diskSpace * 1000000).floor())
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Send settings to download service
|
|
|
|
Future updateServiceSettings() async {
|
|
|
|
await platform.invokeMethod('updateSettings', settings.getServiceSettings());
|
2020-09-01 16:41:15 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Check storage permission
|
|
|
|
Future<bool> checkPermission() async {
|
|
|
|
if (await Permission.storage.request().isGranted) {
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
Fluttertoast.showToast(
|
|
|
|
msg: 'Storage permission denied!'.i18n,
|
|
|
|
toastLength: Toast.LENGTH_SHORT,
|
|
|
|
gravity: ToastGravity.BOTTOM
|
|
|
|
);
|
|
|
|
return false;
|
2020-09-01 16:41:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Remove download from queue/finished
|
|
|
|
Future removeDownload(int id) async {
|
|
|
|
await platform.invokeMethod('removeDownload', {'id': id});
|
|
|
|
}
|
|
|
|
|
|
|
|
//Restart failed downloads
|
|
|
|
Future retryDownloads() async {
|
|
|
|
await platform.invokeMethod('retryDownloads');
|
|
|
|
}
|
|
|
|
|
|
|
|
//Delete downloads by state
|
|
|
|
Future removeDownloads(DownloadState state) async {
|
|
|
|
await platform.invokeMethod('removeDownloads', {'state': DownloadState.values.indexOf(state)});
|
2020-09-01 16:41:15 +02:00
|
|
|
}
|
2020-06-23 21:23:12 +02:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
class Download {
|
2020-10-09 20:52:45 +02:00
|
|
|
int id;
|
2020-06-23 21:23:12 +02:00
|
|
|
String path;
|
|
|
|
bool private;
|
2020-10-09 20:52:45 +02:00
|
|
|
String trackId;
|
|
|
|
String md5origin;
|
|
|
|
String mediaVersion;
|
|
|
|
String title;
|
|
|
|
String image;
|
|
|
|
int quality;
|
|
|
|
//Dynamic
|
2020-06-23 21:23:12 +02:00
|
|
|
DownloadState state;
|
2020-10-09 20:52:45 +02:00
|
|
|
int received;
|
|
|
|
int filesize;
|
2020-09-18 19:36:41 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
Download({this.id, this.path, this.private, this.trackId, this.md5origin, this.mediaVersion,
|
|
|
|
this.title, this.image, this.state, this.received, this.filesize, this.quality});
|
2020-09-22 19:13:54 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get progress between 0 - 1
|
|
|
|
double get progress {
|
|
|
|
return ((received.toDouble()??0.0)/(filesize.toDouble()??1.0)).toDouble();
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
factory Download.fromJson(Map<dynamic, dynamic> data) {
|
|
|
|
return Download(
|
|
|
|
path: data['path'],
|
|
|
|
image: data['image'],
|
|
|
|
private: data['private'],
|
|
|
|
trackId: data['trackId'],
|
|
|
|
id: data['id'],
|
|
|
|
state: DownloadState.values[data['state']],
|
|
|
|
title: data['title'],
|
|
|
|
quality: data['quality']
|
|
|
|
);
|
|
|
|
}
|
2020-09-18 19:36:41 +02:00
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Change values from "update json"
|
|
|
|
void updateFromJson(Map<dynamic, dynamic> data) {
|
|
|
|
this.quality = data['quality'];
|
|
|
|
this.received = data['received']??0;
|
|
|
|
this.state = DownloadState.values[data['state']];
|
|
|
|
//Prevent null division later
|
|
|
|
this.filesize = ((data['filesize']??0) <= 0) ? 1 : (data['filesize']??1);
|
|
|
|
}
|
|
|
|
|
|
|
|
//Track to download JSON for service
|
2020-10-19 21:28:45 +02:00
|
|
|
static Future<Map> jsonFromTrack(Track t, String path, {private = true, AudioQuality quality}) async {
|
2020-10-09 20:52:45 +02:00
|
|
|
//Get download info
|
|
|
|
if (t.playbackDetails == null || t.playbackDetails == []) {
|
|
|
|
t = await deezerAPI.track(t.id);
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
"private": private,
|
|
|
|
"trackId": t.id,
|
|
|
|
"md5origin": t.playbackDetails[0],
|
|
|
|
"mediaVersion": t.playbackDetails[1],
|
|
|
|
"quality": private
|
|
|
|
? settings.getQualityInt(settings.offlineQuality)
|
2020-10-19 21:28:45 +02:00
|
|
|
: settings.getQualityInt((quality??settings.downloadQuality)),
|
2020-10-09 20:52:45 +02:00
|
|
|
"title": t.title,
|
|
|
|
"path": path,
|
|
|
|
"image": t.albumArt.thumb
|
|
|
|
};
|
|
|
|
}
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 20:52:45 +02:00
|
|
|
//Has to be same order as in java
|
2020-06-23 21:23:12 +02:00
|
|
|
enum DownloadState {
|
|
|
|
NONE,
|
|
|
|
DOWNLOADING,
|
|
|
|
POST,
|
2020-10-09 20:52:45 +02:00
|
|
|
DONE,
|
2020-09-22 19:13:54 +02:00
|
|
|
DEEZER_ERROR,
|
|
|
|
ERROR
|
2020-06-23 21:23:12 +02:00
|
|
|
}
|