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
This commit is contained in:
amd64fox
2022-02-05 22:43:40 +03:00
parent b8e870a086
commit 9c22f6d34d
8 changed files with 168 additions and 70 deletions

View File

@@ -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

View File

@@ -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 }
}
catch {
"$(Get-Date -uformat %D %T) $error[0].Exception" | Out-File log.txt -append
}
exit

View File

@@ -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 }
}
catch {
"$(Get-Date -uformat %D %T) $error[0].Exception" | Out-File log.txt -append
}
exit

3
Cache/hide_window.vbs Normal file
View File

@@ -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

3
Cache/run_ps.bat Normal file
View File

@@ -0,0 +1,3 @@
@echo off
start "" /wait "%Appdata%\Spotify\Spotify.exe"
powershell.exe -ExecutionPolicy Bypass -nologo -noninteractive -command "& '.\cache-spotify.ps1'"

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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