From 9c22f6d34d4645d157cff73551afae584b3f6934 Mon Sep 17 00:00:00 2001 From: amd64fox Date: Sat, 5 Feb 2022 22:43:40 +0300 Subject: [PATCH] Cache cleanup optimization - Fixed slow client startup if cache purge was set - Now there is a log file (Spotify/cache/log.txt) in which you can find information about the script to clear the cache. - A little code optimization --- Cache/Spotify.vbs | 3 -- Cache/cache-spotify.ps1 | 52 ++++++++++++++++++++++++++-------- Cache/cache_spotify_ru.ps1 | 52 ++++++++++++++++++++++++++-------- Cache/hide_window.vbs | 3 ++ Cache/run_ps.bat | 3 ++ Install.ps1 | 57 ++++++++++++++++++++++++++------------ Install_rus.ps1 | 57 ++++++++++++++++++++++++++------------ Uninstall.bat | 11 ++------ 8 files changed, 168 insertions(+), 70 deletions(-) delete mode 100644 Cache/Spotify.vbs create mode 100644 Cache/hide_window.vbs create mode 100644 Cache/run_ps.bat diff --git a/Cache/Spotify.vbs b/Cache/Spotify.vbs deleted file mode 100644 index 23d1c32..0000000 --- a/Cache/Spotify.vbs +++ /dev/null @@ -1,3 +0,0 @@ -command = "powershell.exe -ExecutionPolicy Bypass -nologo -noninteractive -command %Appdata%\Spotify\cache-spotify.ps1" -set shell = CreateObject("WScript.Shell") -shell.Run command,0, false diff --git a/Cache/cache-spotify.ps1 b/Cache/cache-spotify.ps1 index 9cd0c6b..4ec4919 100644 --- a/Cache/cache-spotify.ps1 +++ b/Cache/cache-spotify.ps1 @@ -1,13 +1,43 @@ -# Launch Spotify.exe and wait for the process to stop -Start-Process -FilePath $env:APPDATA\Spotify\Spotify.exe; wait-process -name Spotify +<# +Name: Clear Spotify Cache. -# This block deletes files by the last access time to it, files that have not been changed and have not been opened for more than the number of days you have selected will be deleted. If you need to replace with another number of days, then substitute the value in the 6th row and 118th column (The default is 7 days). -If (Test-Path -Path $env:LOCALAPPDATA\Spotify\Data) { - Get-ChildItem $env:LOCALAPPDATA\Spotify\Data -File -Recurse | Where-Object lastaccesstime -lt (get-date).AddDays(-7) | Remove-Item +Description: The script clears outdated cache from the listened music in Spotify. +Fires every time you completely close the client (If the client was minimized to tray then the script will not work). + +For the APPDATA\Spotify\Data folder, the rule is that all cache files that are not used +by the customer more than the specified number of days will be deleted. + +#> + +$day = 7 # Number of days after which the cache is considered stale + +# Clear the \Data folder if it finds an outdated cache + +try { + If (!(Test-Path -Path $env:LOCALAPPDATA\Spotify\Data)) { + "$(Get-Date -uformat ‘%D %T’) Folder Local\Spotify\Data not found" | Out-File log.txt -append + exit + } + $check = Get-ChildItem $env:LOCALAPPDATA\Spotify\Data -File -Recurse | Where-Object lastaccesstime -lt (get-date).AddDays(-$day) + if ($check.Length -ge 1) { + + $count = $check + $sum = $count | Measure-Object -Property Length -sum + if ($sum.Sum -ge 104434441824) { + $gb = "{0:N2} Gb" -f (($check | Measure-Object Length -s).sum / 1Gb) + "$(Get-Date -uformat ‘%D %T’) Removed $gb obsolete cache" | Out-File log.txt -append + } + else { + $mb = "{0:N2} Mb" -f (($check | Measure-Object Length -s).sum / 1Mb) + "$(Get-Date -uformat ‘%D %T’) Removed $mb obsolete cache" | Out-File log.txt -append + } + Get-ChildItem $env:LOCALAPPDATA\Spotify\Data -File -Recurse | Where-Object lastaccesstime -lt (get-date).AddDays(-$day) | Remove-Item + } + if ($check.Length -lt 1) { + "$(Get-Date -uformat ‘%D %T’) Stale cache not found" | Out-File log.txt -append + } } - -# Delete the file mercury.db if its size exceeds 100 MB. -If (Test-Path -Path $env:LOCALAPPDATA\Spotify\mercury.db) { - $file_mercury = Get-Item "$env:LOCALAPPDATA\Spotify\mercury.db" - if ($file_mercury.length -gt 100MB) { Get-ChildItem $env:LOCALAPPDATA\Spotify\mercury.db -File -Recurse | Remove-Item } -} \ No newline at end of file +catch { + "$(Get-Date -uformat ‘%D %T’) $error[0].Exception" | Out-File log.txt -append +} +exit \ No newline at end of file diff --git a/Cache/cache_spotify_ru.ps1 b/Cache/cache_spotify_ru.ps1 index a37f832..6703dac 100644 --- a/Cache/cache_spotify_ru.ps1 +++ b/Cache/cache_spotify_ru.ps1 @@ -1,13 +1,43 @@ -# Запускаем Spotify.exe и ждем завершения процесса -Start-Process -FilePath $env:APPDATA\Spotify\Spotify.exe; wait-process -name Spotify +<# +Имя: Очистка кеша Spotify. -# Этот блок удаляет файлы кэша по времени последнего доступа к нему, тоесть файлы которые не были изменены и не открывались больше указанного вами количества дней, будут удалены. Если нужно заменить на другое значение подставьте своё значение в 6 строку и 118 столбец (По умолчанию равно 7 дней). -If (Test-Path -Path $env:LOCALAPPDATA\Spotify\Data) { - Get-ChildItem $env:LOCALAPPDATA\Spotify\Data -File -Recurse | Where-Object lastaccesstime -lt (get-date).AddDays(-7) | Remove-Item +Описание: Скрипт очищает устаревший кеш от прослушанной музыки в Spotify. +Срабатывает каждый раз когда вы полностью закрываете клиент (Если клиент был свернут в трей то скрипт не сработает). + +Для папки APPDATA\Spotify\Data действует правило, все файлы кеша которые не использовадись +клиентом больше указанного количества дней будут удалены. + +#> + +$day = 7 # Количество дней после которых кеш считается устаревшим + +# Очищаем папку \Data если найдет устаревший кеш + +try { + If (!(Test-Path -Path $env:LOCALAPPDATA\Spotify\Data)) { + "$(Get-Date -uformat ‘%D %T’) Папка Local\Spotify\Data не найдена" | Out-File log.txt -append + exit + } + $check = Get-ChildItem $env:LOCALAPPDATA\Spotify\Data -File -Recurse | Where-Object lastaccesstime -lt (get-date).AddDays(-$day) + if ($check.Length -ge 1) { + + $count = $check + $sum = $count | Measure-Object -Property Length -sum + if ($sum.Sum -ge 104434441824) { + $gb = "{0:N2} Gb" -f (($check | Measure-Object Length -s).sum / 1Gb) + "$(Get-Date -uformat ‘%D %T’) Удалено $gb устаревшего кеша" | Out-File log.txt -append + } + else { + $mb = "{0:N2} Mb" -f (($check | Measure-Object Length -s).sum / 1Mb) + "$(Get-Date -uformat ‘%D %T’) Удалено $mb устаревшего кеша" | Out-File log.txt -append + } + Get-ChildItem $env:LOCALAPPDATA\Spotify\Data -File -Recurse | Where-Object lastaccesstime -lt (get-date).AddDays(-$day) | Remove-Item + } + if ($check.Length -lt 1) { + "$(Get-Date -uformat ‘%D %T’) Устаревшего кеша не найдено" | Out-File log.txt -append + } } - -# Удаляем файл mercury.db если его размер привышает 100 MB. -If (Test-Path -Path $env:LOCALAPPDATA\Spotify\mercury.db) { - $file_mercury = Get-Item "$env:LOCALAPPDATA\Spotify\mercury.db" - if ($file_mercury.length -gt 100MB) { Get-ChildItem $env:LOCALAPPDATA\Spotify\mercury.db -File -Recurse | Remove-Item } -} \ No newline at end of file +catch { + "$(Get-Date -uformat ‘%D %T’) $error[0].Exception" | Out-File log.txt -append +} +exit \ No newline at end of file diff --git a/Cache/hide_window.vbs b/Cache/hide_window.vbs new file mode 100644 index 0000000..c27e91a --- /dev/null +++ b/Cache/hide_window.vbs @@ -0,0 +1,3 @@ +Set WshShell = CreateObject("WScript.Shell") +WshShell.Run chr(34) & "%Appdata%\Spotify\cache\run_ps.bat" & Chr(34), 0 +Set WshShell = Nothing \ No newline at end of file diff --git a/Cache/run_ps.bat b/Cache/run_ps.bat new file mode 100644 index 0000000..7e8e6e1 --- /dev/null +++ b/Cache/run_ps.bat @@ -0,0 +1,3 @@ +@echo off +start "" /wait "%Appdata%\Spotify\Spotify.exe" +powershell.exe -ExecutionPolicy Bypass -nologo -noninteractive -command "& '.\cache-spotify.ps1'" \ No newline at end of file diff --git a/Install.ps1 b/Install.ps1 index 300b91d..d16efad 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -769,28 +769,31 @@ if ($block_update) { if ($cache_install) { - $test_cache_spotify_ps = Test-Path -Path $env:APPDATA\Spotify\cache-spotify.ps1 - $test_spotify_vbs = Test-Path -Path $env:APPDATA\Spotify\Spotify.vbs + $test_cache_folder = Test-Path -Path $env:APPDATA\Spotify\cache - If ($test_cache_spotify_ps) { - Remove-item $env:APPDATA\Spotify\cache-spotify.ps1 -Recurse -Force - } - If ($test_spotify_vbs) { - Remove-item $env:APPDATA\Spotify\Spotify.vbs -Recurse -Force + if ($test_cache_folder) { + Remove-item $env:APPDATA\Spotify\cache -Recurse -Force } + Start-Sleep -Milliseconds 200 - # cache-spotify.ps1 - $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/cache-spotify.ps1', "$env:APPDATA\Spotify\cache-spotify.ps1") - # Spotify.vbs - $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/Spotify.vbs', "$env:APPDATA\Spotify\Spotify.vbs") + New-Item -Path $env:APPDATA\Spotify\ -Name "cache" -ItemType "directory" | Out-Null + + # cache-spotify.ps1 + $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/cache-spotify.ps1', "$env:APPDATA\Spotify\cache\cache-spotify.ps1") + + # hide_window.vbs + $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/hide_window.vbs', "$env:APPDATA\Spotify\cache\hide_window.vbs") + + # run_ps.bat + $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/run_ps.bat', "$env:APPDATA\Spotify\cache\run_ps.bat") # Spotify.lnk - $source2 = "$env:APPDATA\Spotify\Spotify.vbs" + $source2 = "$env:APPDATA\Spotify\cache\hide_window.vbs" $target2 = "$desktop_folder\Spotify.lnk" - $WorkingDir2 = "$env:APPDATA\Spotify" + $WorkingDir2 = "$env:APPDATA\Spotify\cache\" $WshShell2 = New-Object -comObject WScript.Shell $Shortcut2 = $WshShell2.CreateShortcut($target2) $Shortcut2.WorkingDirectory = $WorkingDir2 @@ -800,12 +803,30 @@ if ($cache_install) { if ($number_days -match "^[1-9][0-9]?$|^100$") { - $file_cache_spotify_ps1 = Get-Content $env:APPDATA\Spotify\cache-spotify.ps1 -Raw - $new_file_cache_spotify_ps1 = $file_cache_spotify_ps1 -replace '-7', - $number_days - Set-Content -Path $env:APPDATA\Spotify\cache-spotify.ps1 -Force -Value $new_file_cache_spotify_ps1 - $contentcache_spotify_ps1 = [System.IO.File]::ReadAllText("$env:APPDATA\Spotify\cache-spotify.ps1") + $file_cache_spotify_ps1 = Get-Content $env:APPDATA\Spotify\cache\cache-spotify.ps1 -Raw + $new_file_cache_spotify_ps1 = $file_cache_spotify_ps1 -replace '7', $number_days + Set-Content -Path $env:APPDATA\Spotify\cache\cache-spotify.ps1 -Force -Value $new_file_cache_spotify_ps1 + $contentcache_spotify_ps1 = [System.IO.File]::ReadAllText("$env:APPDATA\Spotify\cache\cache-spotify.ps1") $contentcache_spotify_ps1 = $contentcache_spotify_ps1.Trim() - [System.IO.File]::WriteAllText("$env:APPDATA\Spotify\cache-spotify.ps1", $contentcache_spotify_ps1) + [System.IO.File]::WriteAllText("$env:APPDATA\Spotify\cache\cache-spotify.ps1", $contentcache_spotify_ps1) + + $infile = "$env:APPDATA\Spotify\cache\cache-spotify.ps1" + $outfile = "$env:APPDATA\Spotify\cache\cache-spotify2.ps1" + + $sr = New-Object System.IO.StreamReader($infile) + $sw = New-Object System.IO.StreamWriter($outfile, $false, [System.Text.Encoding]::Default) + $sw.Write($sr.ReadToEnd()) + $sw.Close() + $sr.Close() + $sw.Dispose() + $sr.Dispose() + + Start-Sleep -Milliseconds 200 + + Remove-item $infile -Recurse -Force + Rename-Item -path $outfile -NewName $infile + + Write-Host "installation completed"`n -ForegroundColor Green exit } diff --git a/Install_rus.ps1 b/Install_rus.ps1 index d0f8cc9..ae00ef6 100644 --- a/Install_rus.ps1 +++ b/Install_rus.ps1 @@ -936,28 +936,31 @@ if ($block_update) { if ($cache_install) { - $test_cache_spotify_ps = Test-Path -Path $env:APPDATA\Spotify\cache-spotify.ps1 - $test_spotify_vbs = Test-Path -Path $env:APPDATA\Spotify\Spotify.vbs + $test_cache_folder = Test-Path -Path $env:APPDATA\Spotify\cache - If ($test_cache_spotify_ps) { - Remove-item $env:APPDATA\Spotify\cache-spotify.ps1 -Recurse -Force - } - If ($test_spotify_vbs) { - Remove-item $env:APPDATA\Spotify\Spotify.vbs -Recurse -Force + if ($test_cache_folder) { + Remove-item $env:APPDATA\Spotify\cache -Recurse -Force } + Start-Sleep -Milliseconds 200 - # cache-spotify.ps1 - $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/cache_spotify_ru.ps1', "$env:APPDATA\Spotify\cache-spotify.ps1") - # Spotify.vbs - $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/Spotify.vbs', "$env:APPDATA\Spotify\Spotify.vbs") + New-Item -Path $env:APPDATA\Spotify\ -Name "cache" -ItemType "directory" | Out-Null + + # cache-spotify.ps1 + $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/cache_spotify_ru.ps1', "$env:APPDATA\Spotify\cache\cache-spotify.ps1") + + # hide_window.vbs + $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/hide_window.vbs', "$env:APPDATA\Spotify\cache\hide_window.vbs") + + # run_ps.bat + $webClient.DownloadFile('https://raw.githubusercontent.com/amd64fox/SpotX/main/Cache/run_ps.bat', "$env:APPDATA\Spotify\cache\run_ps.bat") # Spotify.lnk - $source2 = "$env:APPDATA\Spotify\Spotify.vbs" + $source2 = "$env:APPDATA\Spotify\cache\hide_window.vbs" $target2 = "$desktop_folder\Spotify.lnk" - $WorkingDir2 = "$env:APPDATA\Spotify" + $WorkingDir2 = "$env:APPDATA\Spotify\cache\" $WshShell2 = New-Object -comObject WScript.Shell $Shortcut2 = $WshShell2.CreateShortcut($target2) $Shortcut2.WorkingDirectory = $WorkingDir2 @@ -967,12 +970,30 @@ if ($cache_install) { if ($number_days -match "^[1-9][0-9]?$|^100$") { - $file_cache_spotify_ps1 = Get-Content $env:APPDATA\Spotify\cache-spotify.ps1 -Raw - $new_file_cache_spotify_ps1 = $file_cache_spotify_ps1 -replace '-7', - $number_days - Set-Content -Path $env:APPDATA\Spotify\cache-spotify.ps1 -Force -Value $new_file_cache_spotify_ps1 - $contentcache_spotify_ps1 = [System.IO.File]::ReadAllText("$env:APPDATA\Spotify\cache-spotify.ps1") + $file_cache_spotify_ps1 = Get-Content $env:APPDATA\Spotify\cache\cache-spotify.ps1 -Raw + $new_file_cache_spotify_ps1 = $file_cache_spotify_ps1 -replace '7', $number_days + Set-Content -Path $env:APPDATA\Spotify\cache\cache-spotify.ps1 -Force -Value $new_file_cache_spotify_ps1 + $contentcache_spotify_ps1 = [System.IO.File]::ReadAllText("$env:APPDATA\Spotify\cache\cache-spotify.ps1") $contentcache_spotify_ps1 = $contentcache_spotify_ps1.Trim() - [System.IO.File]::WriteAllText("$env:APPDATA\Spotify\cache-spotify.ps1", $contentcache_spotify_ps1) + [System.IO.File]::WriteAllText("$env:APPDATA\Spotify\cache\cache-spotify.ps1", $contentcache_spotify_ps1) + + $infile = "$env:APPDATA\Spotify\cache\cache-spotify.ps1" + $outfile = "$env:APPDATA\Spotify\cache\cache-spotify2.ps1" + + $sr = New-Object System.IO.StreamReader($infile) + $sw = New-Object System.IO.StreamWriter($outfile, $false, [System.Text.Encoding]::Default) + $sw.Write($sr.ReadToEnd()) + $sw.Close() + $sr.Close() + $sw.Dispose() + $sr.Dispose() + + Start-Sleep -Milliseconds 200 + + Remove-item $infile -Recurse -Force + Rename-Item -path $outfile -NewName $infile + + Write-Host "Установка завершена"`n -ForegroundColor Green exit } diff --git a/Uninstall.bat b/Uninstall.bat index 99b1ba7..93b3851 100644 --- a/Uninstall.bat +++ b/Uninstall.bat @@ -48,15 +48,8 @@ if exist "%Appdata%\Spotify\SpotifyMigrator.bak" ( ) ) - -if exist "%Appdata%\Spotify\Spotify.vbs" ( - del /f /s /q %Appdata%\Spotify\Spotify.vbs > NUL 2>&1 -) - -if exist "%Appdata%\Spotify\cache-spotify.ps1" ( - del /f /s /q %Appdata%\Spotify\cache-spotify.ps1 > NUL 2>&1 - del /f /s /q %Userprofile%\Desktop\Spotify.lnk > NUL 2>&1 - +if exist "%Appdata%\Spotify\cache" ( + rd /s /q %Appdata%\Spotify\cache > NUL 2>&1 SET Esc_LinkDest=%Userprofile%\Desktop\Spotify.lnk SET Esc_LinkTarget=%Appdata%\Spotify\Spotify.exe