From caa80a8ae68600e24b5c5a0e120792a204535a1a Mon Sep 17 00:00:00 2001
From: Robert Goldmann <deadlocker@gmx.de>
Date: Thu, 9 Apr 2020 23:19:53 +0200
Subject: [PATCH] added option to delete old files after certain days

---
 SpotifyBackup.py      | 27 ++++++++++++++++++++++++---
 settings-example.json |  1 +
 2 files changed, 25 insertions(+), 3 deletions(-)

diff --git a/SpotifyBackup.py b/SpotifyBackup.py
index 483b63a..79470d5 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 98f46fd..d1430ac 100644
--- a/settings-example.json
+++ b/settings-example.json
@@ -4,6 +4,7 @@
         "clientSecret": ""
     },
     "exportFolder": "",
+    "daysToKeep": "30",
     "playlists": [
         {
             "user": "",
-- 
GitLab