diff --git a/SpotifyBackup.py b/SpotifyBackup.py index 483b63a8bf4aa8131d2278a8f3b2f8b822e58682..79470d5af88fdd72dfdb6b0e05f23e0f04308364 100644 --- a/SpotifyBackup.py +++ b/SpotifyBackup.py @@ -3,7 +3,7 @@ import json import logging import os import sys -from datetime import datetime +from datetime import datetime, timedelta import spotipy from spotipy.oauth2 import SpotifyClientCredentials @@ -36,6 +36,7 @@ LOGGER = prepare_logging() class SpotifyBackup: DATE_FORMAT = '%Y-%m-%d_%H-%M-%S' + DATE_FORMAT_SHORT = '%Y-%m-%d' INVALID_CHARS = [' ', '\t', '\n'] REPLACE_CHAR = '_' @@ -53,12 +54,12 @@ class SpotifyBackup: exportPath = self.__determine_export_path(playlist['name']) - LOGGER.info(f'Exporting tracks to "{exportPath}"...') + LOGGER.info(f'>>> Exporting tracks to "{exportPath}"...') self.__export_csv(exportPath, tracks) LOGGER.info('Exporting DONE') def __get_playlist(self, username: str, playlistID: str): - LOGGER.info(f'Fetching playlist with ID: {playlistID} by {username}...') + LOGGER.info(f'>>> Fetching playlist with ID: {playlistID} by {username}...') identifier = f'spotify:user:{username}:playlist:{playlistID}' playlist = self._spotify.playlist(identifier) LOGGER.info(f'Found playlist "{playlist["name"]}"') @@ -101,6 +102,24 @@ class SpotifyBackup: except Exception: LOGGER.exception(f'Error while exporting track "{track}"') + def clean_old_exports(self, daysToKeep): + if not daysToKeep: + LOGGER.info('Skipping deletion of old files') + return + + minimumDate = datetime.today() - timedelta(days=int(daysToKeep)) + LOGGER.info(f'>>> Deleting files older than {minimumDate} ({daysToKeep} days)') + + files = [file for file in sorted(os.listdir(self._exportFolder)) if + os.path.isfile(os.path.join(self._exportFolder, file))] + + for file in files: + parts = file.split('_') + creationDate = datetime.strptime(parts[0], self.DATE_FORMAT_SHORT) + if creationDate < minimumDate: + LOGGER.info(f'Removing old file "{file}"') + os.remove(os.path.join(self._exportFolder, file)) + if __name__ == '__main__': with open('settings.json', 'r', encoding='utf-8') as f: @@ -110,6 +129,8 @@ if __name__ == '__main__': SETTINGS['spotifyAPI']['clientSecret'], SETTINGS['exportFolder']) + spotifyBackup.clean_old_exports(SETTINGS['daysToKeep']) + for playlist in SETTINGS['playlists']: spotifyBackup.backup_playlist(playlist['user'], playlist['id']) diff --git a/settings-example.json b/settings-example.json index 98f46fdcd202635d770c40a95b9920b7bb650f96..d1430aca77176cde3ce6fdd05e0ba8d287fe5e71 100644 --- a/settings-example.json +++ b/settings-example.json @@ -4,6 +4,7 @@ "clientSecret": "" }, "exportFolder": "", + "daysToKeep": "30", "playlists": [ { "user": "",