Skip to content

Commit

Permalink
fixed migration
Browse files Browse the repository at this point in the history
  • Loading branch information
sunmisc committed Jul 22, 2024
1 parent 93e0115 commit 8c7cb60
Show file tree
Hide file tree
Showing 19 changed files with 270 additions and 229 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ private static boolean isAlbumVirtualPlaylist(String accessKey) {
}

private static boolean isOwnCachePlaylist(String ownerId, String id) {
return Objects.equals(ownerId, String.valueOf(AccountManagerUtils.getUserId())) && Objects.equals(id, "-1");
return Objects.equals(ownerId, String.valueOf(AccountManagerUtils.getUserId()))
&& Objects.equals(id, "-1");
}

private static int[] getCountAndOffset(Map<String, String> requestArgs) {
Expand Down Expand Up @@ -87,11 +88,11 @@ private static Observable<AudioGetPlaylist.c> handleMusicCacheImpl(int id, int o
return Observable.c(() -> {
AudioGetPlaylist.c response = new AudioGetPlaylist.c();

response.c = new ArrayList<>(MusicCacheImpl.getPlaylistSongs(ownerId, id, offset, count));

if (isOwnCachePlaylist) {
response.c = (ArrayList<MusicTrack>) TracklistHelper.getMyCachedMusicTracks();
response.b = PlaylistHelper.createCachedPlaylistMetadata();
} else {
response.c = new ArrayList<>(MusicCacheImpl.getPlaylistSongs(ownerId, id, offset, count));
response.b = MusicCacheImpl.getPlaylist(id, ownerId);
}
return response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static void downloadPlaylist(Playlist playlist) {
int notificationId = playlistName.hashCode();
NotificationCompat.Builder notification = MusicNotificationBuilder.buildPlaylistDownloadNotification(playlistName, notificationId);

downloadPlaylist(tracks, playlistName, downloadPath, notification, notificationId);
downloadPlaylist(tracks, downloadPath, notification, notificationId);
});
}

Expand Down Expand Up @@ -107,7 +107,7 @@ public static void downloadAllAudios() {
String downloadPath = getDownloadPath(playlistName);

if (!tracks.isEmpty()) {
downloadPlaylist(tracks, playlistName, downloadPath, notification, notificationId);
downloadPlaylist(tracks, downloadPath, notification, notificationId);
}
});
}
Expand All @@ -124,17 +124,18 @@ private static void downloadM3U8(MusicTrack track, boolean cache) {
Callback cb = MusicCallbackBuilder.buildOneTrackCallback(tempId, notification);

if (cache) {
TrackDownloader.cacheTrack(track, cb, PlaylistHelper.createCachedPlaylistMetadata());
Playlist playlist = PlaylistHelper.createCachedPlaylistMetadata();
TrackDownloader.cacheTrack(track, cb,
PlaylistCacheDbDelegate.getOrCreatePlaylist(playlist));
} else {
TrackDownloader.downloadTrack(track, downloadPath, cb);
}
});
}

private static void downloadPlaylist(List<MusicTrack> tracks, String playlistName, String downloadPath, NotificationCompat.Builder notification, int notificationId) {
private static void downloadPlaylist(List<MusicTrack> tracks, String downloadPath, NotificationCompat.Builder notification, int notificationId) {
PlaylistDownloader.downloadPlaylist(
tracks,
playlistName,
downloadPath,
MusicCallbackBuilder.buildPlaylistCallback(tracks.size(), notification, notificationId)
);
Expand All @@ -151,7 +152,7 @@ public void onProgress(int progress) {

@Override
public void onSuccess() {
PlaylistCacheDbDelegate.addPlaylist(playlist);
PlaylistCacheDbDelegate.getOrCreatePlaylist(playlist);
Log.d("Playlist", "adding to cache with thumbs " + playlist.v1());
}

Expand All @@ -161,7 +162,7 @@ public void onFailure(Throwable e) {
}
}).download(playlist);
} else {
PlaylistCacheDbDelegate.addPlaylist(playlist);
PlaylistCacheDbDelegate.getOrCreatePlaylist(playlist);
Log.d("Playlist", "adding to cache without thumbs " + playlist.a);
}

Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/ru/vtosters/lite/music/cache/DatabaseAccess.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.vtosters.lite.music.cache;

import android.database.sqlite.SQLiteDatabase;

import java.io.Closeable;

public interface DatabaseAccess extends Closeable {

SQLiteDatabase getReadableDatabase();

SQLiteDatabase getWritableDatabase();
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ru.vtosters.lite.music.cache;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.RemoteException;
import bruhcollective.itaysonlab.libvkx.ILibVkxService;
import bruhcollective.itaysonlab.libvkx.client.LibVKXClient;
Expand All @@ -24,7 +25,8 @@
@SuppressWarnings("forRemoval")
public class MusicCacheImpl {

private static final Database connection = new Database();
private static final Database connection =
new Database();

private static final MusicCacheDb musics = new MusicCacheDb(connection);
private static final IPlaylists playlists = new SqlPlaylists(connection);
Expand All @@ -35,13 +37,6 @@ public static void removeTrack(String trackId) {
MusicCacheStorageUtils.removeTrackDirById(trackId);
}

public static List<MusicTrack> getAllOwnTracks() {
return playlists
.playlist(AccountManagerUtils.getUserId(), -1)
.map(IPlaylist::tracks)
.orElse(List.of());
}


public static List<MusicTrack>
getPlaylistSongs(int owner_id, int playlist_id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ public interface Constants {
+ PLAYLIST_ID + " INTEGER NOT NULL,"
+ TRACK_ID + " TEXT NOT NULL,"

+ "PRIMARY KEY (" + OWNER_ID + ", " + PLAYLIST_ID + ", " + TRACK_ID + "),"

+ "FOREIGN KEY (" + OWNER_ID + ", " + PLAYLIST_ID + ") "
+ "REFERENCES " + TABLE_PLAYLIST + "(" + OWNER_ID + ", " + PLAYLIST_ID + ") "
+ "ON DELETE CASCADE,"
Expand Down
71 changes: 40 additions & 31 deletions app/src/main/java/ru/vtosters/lite/music/cache/db/Database.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,25 @@
import androidx.annotation.Nullable;
import com.vk.dto.music.MusicTrack;
import com.vk.dto.music.Playlist;

import ru.vtosters.lite.music.cache.DatabaseAccess;
import ru.vtosters.lite.music.cache.db.old.OldMusicCacheDb;
import ru.vtosters.lite.music.cache.db.old.OldPlaylistCacheDb;
import ru.vtosters.lite.music.cache.helpers.PlaylistHelper;
import ru.vtosters.lite.music.interfaces.IPlaylist;
import ru.vtosters.lite.utils.AccountManagerUtils;
import ru.vtosters.lite.utils.AndroidUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class Database extends SQLiteOpenHelper implements AutoCloseable {
public final class Database extends SQLiteOpenHelper implements DatabaseAccess {


public Database() {
this(AndroidUtils.getGlobalContext());
}


public Database(@Nullable Context context) {
super(context, Constants.DB_NAME, null, Constants.DV_VERSION);
}
Expand All @@ -28,50 +34,53 @@ public void onCreate(SQLiteDatabase db) {
db.execSQL(Constants.CREATE_TABLE_MUSICS);
db.execSQL(Constants.CREATE_TABLE_PLAYLISTS);
db.execSQL(Constants.CREATE_TABLE_PLAYLIST_TRACKS);

}

@Override
public void onUpgrade(SQLiteDatabase db, int prev, int current) {
if (prev < current) {
migrateMusics();
migratePlaylists();
}
}

private void migrateMusics() {
try (OldMusicCacheDb old = new OldMusicCacheDb(AndroidUtils.getGlobalContext())) {
MusicCacheDb musics = new MusicCacheDb(this);
DatabaseAccess access = new DatabaseAccess() {
@Override public void close() { db.close(); }

SQLiteDatabase write = old.getWritableDatabase();
List<MusicTrack> tracks = old.getAllTracks();
@Override public SQLiteDatabase getReadableDatabase() {
return db;
}

write.execSQL(OldMusicCacheDb.Constants.DROP_QUERY);
@Override public SQLiteDatabase getWritableDatabase() {
return db;
}
};
try (OldMusicCacheDb musics = new OldMusicCacheDb()) {
List<MusicTrack> tracks = musics.getAllTracks();

tracks.forEach(musics::addTrack);
}
}
OldPlaylistCacheDb oldPlaylistCacheDb = new OldPlaylistCacheDb(db);

private void migratePlaylists() {
try (OldPlaylistCacheDb old = new OldPlaylistCacheDb(AndroidUtils.getGlobalContext())) {
Map<Playlist, List<MusicTrack>> map = new HashMap<>();
List<String> main = oldPlaylistCacheDb
.getTracksInPlaylist(
AccountManagerUtils.getUserId()+"_-1");
Map<Playlist, List<String>> map = oldPlaylistCacheDb.playlistListMap();

SQLiteDatabase write = old.getWritableDatabase();
oldPlaylistCacheDb.onDelete();

old.getAllPlaylists().forEach(playlist -> {
map.put(playlist, old.getTracksInPlaylist(playlist.v1()));
});
write.execSQL(OldPlaylistCacheDb.Constants.DROP_QUERY);
onCreate(db);

SqlPlaylists playlists = new SqlPlaylists(this);
MusicCacheDb musicCacheDb = new MusicCacheDb(access);

map.forEach((playlist, tracks) -> {
playlists.addPlaylist(playlist);
tracks.forEach(musicCacheDb::addTrack);

playlists.playlist(playlist.b, playlist.a).ifPresent(newPlaylist -> {
tracks.forEach(track -> newPlaylist.addTrack(track.y1()));
SqlPlaylists playlists = new SqlPlaylists(access);
map.forEach((playlist, musicTracks) -> {
IPlaylist iPlaylist = playlists.insertIfAbsent(playlist);
musicTracks.forEach(iPlaylist::addTrack);
});
});

IPlaylist cached = playlists.insertIfAbsent(PlaylistHelper
.createCachedPlaylistMetadata());


main.forEach(cached::addTrack);
}
}
}
}
43 changes: 11 additions & 32 deletions app/src/main/java/ru/vtosters/lite/music/cache/db/MusicCacheDb.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.vk.dto.music.MusicTrack;
import com.vk.dto.music.Thumb;
import org.json.JSONObject;

import ru.vtosters.lite.music.cache.DatabaseAccess;
import ru.vtosters.lite.utils.AndroidUtils;
import ru.vtosters.lite.utils.music.MusicCacheStorageUtils;
import ru.vtosters.lite.utils.music.MusicTrackUtils;
Expand All @@ -24,9 +26,9 @@
*/

public class MusicCacheDb {
private final SQLiteOpenHelper sqlite;
private final DatabaseAccess sqlite;

public MusicCacheDb(SQLiteOpenHelper sqlite) {
public MusicCacheDb(DatabaseAccess sqlite) {
this.sqlite = sqlite;
}

Expand Down Expand Up @@ -119,8 +121,7 @@ public void deleteTrack(String trackId) {
}

public Optional<MusicTrack> getTrackById(String trackId) {
SQLiteDatabase db = sqlite.getReadableDatabase();
try (Cursor cursor = db.query(Constants.TABLE_MUSICS,
try (Cursor cursor = sqlite.getReadableDatabase().query(Constants.TABLE_MUSICS,
null,
Constants.TRACK_ID + " = ?",
new String[]{trackId},
Expand All @@ -134,35 +135,13 @@ public Optional<MusicTrack> getTrackById(String trackId) {

public boolean isDatabaseEmpty() {
SQLiteDatabase db = sqlite.getReadableDatabase();
if (db == null) {
return true; // or throw an exception, depending on your use case
}

Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name=?", new String[]{Constants.TABLE_MUSICS});

if (cursor == null || !cursor.moveToFirst()) {
db.close();
Log.d("MusicCacheDb", "Database is empty and can be null");
return true; // Table does not exist, so the database is considered empty
}

cursor.close();

cursor = db.rawQuery("SELECT EXISTS(SELECT 1 FROM " + Constants.TABLE_MUSICS + " LIMIT 1)", null);

if (cursor == null) {
db.close();
Log.d("MusicCacheDb", "Database is empty");
return true; // or throw an exception, depending on your use case
}

boolean isEmpty = true;
if (cursor.moveToFirst()) {
isEmpty = cursor.getInt(0) == 0;
try (Cursor cursor = db.query(
Constants.TABLE_MUSICS,
null, null,
null, null,
null, null)) {
return cursor == null || !cursor.moveToNext();
}

cursor.close();
db.close();
return isEmpty;
}
}
Loading

0 comments on commit 8c7cb60

Please sign in to comment.