Skip to content
Snippets Groups Projects
Commit caa80a8a authored by Robert Goldmann's avatar Robert Goldmann
Browse files

added option to delete old files after certain days

parent b0b25203
Branches
Tags
No related merge requests found
...@@ -3,7 +3,7 @@ import json ...@@ -3,7 +3,7 @@ import json
import logging import logging
import os import os
import sys import sys
from datetime import datetime from datetime import datetime, timedelta
import spotipy import spotipy
from spotipy.oauth2 import SpotifyClientCredentials from spotipy.oauth2 import SpotifyClientCredentials
...@@ -36,6 +36,7 @@ LOGGER = prepare_logging() ...@@ -36,6 +36,7 @@ LOGGER = prepare_logging()
class SpotifyBackup: class SpotifyBackup:
DATE_FORMAT = '%Y-%m-%d_%H-%M-%S' DATE_FORMAT = '%Y-%m-%d_%H-%M-%S'
DATE_FORMAT_SHORT = '%Y-%m-%d'
INVALID_CHARS = [' ', '\t', '\n'] INVALID_CHARS = [' ', '\t', '\n']
REPLACE_CHAR = '_' REPLACE_CHAR = '_'
...@@ -53,12 +54,12 @@ class SpotifyBackup: ...@@ -53,12 +54,12 @@ class SpotifyBackup:
exportPath = self.__determine_export_path(playlist['name']) 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) self.__export_csv(exportPath, tracks)
LOGGER.info('Exporting DONE') LOGGER.info('Exporting DONE')
def __get_playlist(self, username: str, playlistID: str): 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}' identifier = f'spotify:user:{username}:playlist:{playlistID}'
playlist = self._spotify.playlist(identifier) playlist = self._spotify.playlist(identifier)
LOGGER.info(f'Found playlist "{playlist["name"]}"') LOGGER.info(f'Found playlist "{playlist["name"]}"')
...@@ -101,6 +102,24 @@ class SpotifyBackup: ...@@ -101,6 +102,24 @@ class SpotifyBackup:
except Exception: except Exception:
LOGGER.exception(f'Error while exporting track "{track}"') 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__': if __name__ == '__main__':
with open('settings.json', 'r', encoding='utf-8') as f: with open('settings.json', 'r', encoding='utf-8') as f:
...@@ -110,6 +129,8 @@ if __name__ == '__main__': ...@@ -110,6 +129,8 @@ if __name__ == '__main__':
SETTINGS['spotifyAPI']['clientSecret'], SETTINGS['spotifyAPI']['clientSecret'],
SETTINGS['exportFolder']) SETTINGS['exportFolder'])
spotifyBackup.clean_old_exports(SETTINGS['daysToKeep'])
for playlist in SETTINGS['playlists']: for playlist in SETTINGS['playlists']:
spotifyBackup.backup_playlist(playlist['user'], playlist['id']) spotifyBackup.backup_playlist(playlist['user'], playlist['id'])
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
"clientSecret": "" "clientSecret": ""
}, },
"exportFolder": "", "exportFolder": "",
"daysToKeep": "30",
"playlists": [ "playlists": [
{ {
"user": "", "user": "",
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment