-
Notifications
You must be signed in to change notification settings - Fork 0
/
Download-Playlists.ps1
290 lines (237 loc) · 8.91 KB
/
Download-Playlists.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<#
.SYNOPSIS
Download playlists using yt-dlp / youtube-dl
.VERSION 2023.10.10
#>
param(
[string]$YamlFile,
[string[]]$YamlFiles,
[string]$DlCmd = 'yt-dlp',
[switch]$Install
)
function Invoke-WarningChime {
Add-Type -AssemblyName 'System.Media'
$player = New-Object System.Media.SoundPlayer
$player.SoundLocation = 'C:\Windows\Media\chimes.wav'
$player.Load()
$player.Play()
}
# End this PowerShell script if the parent process (Scheduled Task Job) has exited
$HaltScriptOnParentExit = { Start-Job -ScriptBlock {
param($ScriptPid, $LogPath)
$parentProcessId = (Get-WmiObject Win32_Process -Filter "processid='$ScriptPid'").ParentProcessId
$PSParent = Get-Process -Id $parentProcessId
while (!$PSParent.HasExited) {
Start-Sleep -Milliseconds 500
}
# Stop the PowerShell script
# Append to the end of the logfile
Stop-Transcript
# For some reason this never gets executed.
'INFO: Parent process has exited. Stopping the script.' >> $LogPath
Stop-Process $ScriptPid
} -ArgumentList $pid, $LogPath | Out-Null
}
&$HaltScriptOnParentExit
$DebugPreference = 'Continue'
Write-Debug "Executing $PSCommandPath"
Write-Debug "YamlFiles: $YamlFiles"
# function IsRunningAsScript {
# $shellNames = @('cmd', 'powershell', 'ConEmuC', 'ConEmuC64')
# $parentPID = (Get-WmiObject Win32_Process -Filter "ProcessId=$($PID)").ParentProcessId
# $parentName = (Get-Process -Id $ParentPID).Name
# return ($parentName -in $shellNames)
# }
# function PauseIfNotScript {
# if (!(IsRunningAsScript)) {
# Read-Host 'Press ENTER to continue' | Out-Null
# }
# }
$ScriptRoot = $PSScriptRoot
if (!$ScriptRoot) {
$ScriptRoot = 'N:/Videos'
}
. "${ScriptRoot}/../src/useful/ps-winhelpers/_PS-WinHelpers.ps1"
$MyScript = $MyInvocation.MyCommand.Source
$ScriptName = Split-Path $MyScript -Leaf
$Timestamp = Get-Date -Format 'yyyMMdd-HHmmss'
$LogPath = "$env:LOCALAPPDATA\Temp\${ScriptName}-$Timestamp.log"
$LogYtOut = "$env:LOCALAPPDATA\Temp\${ScriptName}-$Timestamp-yt-out.log"
$LogYtErr = "$env:LOCALAPPDATA\Temp\${ScriptName}-$Timestamp-yt-err.log"
Start-Transcript -Path $LogPath -Append
if (!$YamlFile -and !$YamlFiles) {
Write-Verbose 'Starting the Invoke-FilePicker dialog..'
[string[]]$YamlFiles = Invoke-FilePicker -Path "$ScriptRoot/_defs" -Filter 'Yaml files (*.ya?ml)|*.yaml;*.yml' -Multiselect $true
Write-Verbose 'Generating the Show-Command string..'
$YamlInfoText = "@('" + ($YamlFiles -join "','") + "')"
$DebugPreference = 'Continue'
Write-Debug "Executing command: $PSCommandPath -YamlFiles $YamlInfoText"
$DebugPreference = $TempDebugPreference
Remove-Variable -Name TempDebugPreference
if (!$Install) {
Start-Sleep 3
}
}
if ($Install) {
Register-PowerShellScheduledTask -ScriptPath $PSCommandPath -Parameters @{YamlFiles = $YamlInfoText } -DailyAt '04:00'
Write-Information 'Scheduled task created.'
exit 0
}
Install-ModuleIfNotPresent 'PowerShell-YAML'
$NamingStyles = @{
'playlist/date-title' = '%(playlist)s/%(upload_date)s - %(title)s.%(ext)s'
'playlist/index-title' = '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s'
'playlist/default' = '%(playlist)s/%(title)s-%(id)s.%(ext)s' # Default
'root/default' = '%(title)s-%(id)s.%(ext)s'
'default' = '%(title)s-%(id)s.%(ext)s'
'root/date-title' = '%(upload_date)s - %(title)s.%(ext)s'
'root/index-title' = '%(playlist_index)s - %(title)s.%(ext)s'
'root/channel-title' = '%(channel)s - %(title)s.%(ext)s'
'root/date-channel-title' = '%(upload_date)s - %(channel)s - %(title)s.%(ext)s'
}
$archiveFileName = '_downloaded.txt'
$tempPath = "$ScriptRoot\~dl_tmp"
$Playlists = @()
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
if ($YamlFile) {
$YamlFiles += $YamlFile
}
foreach ($YamlFile in $YamlFiles) {
Write-Debug "Processing $YamlFile"
$Yaml = Get-Content $YamlFile -Raw | ConvertFrom-Yaml
$Playlists += $Yaml.Playlists
}
####
#Region Preflight checks
####
[System.Collections.Generic.Queue[String]]$DlTools = @(
'yt-dlp',
'youtube-dl'
)
while (!$DlCmd -and $DlTools) {
Write-Verbose "Checking for $($DlTools.Peek()).."
$DlCmd = $DlTools.Dequeue()
$DlCmd = Get-Command -Name $DlCmd -ErrorAction SilentlyContinue
$DlCmd = $DlCmd.Source
if ($DlCmd) { Write-Verbose "Found: $DlCmd" }
else { Write-Verbose 'Not found.' }
}
if (!$DlCmd) {
$Raise_Error = "ERROR: Neither `yt-dlp` nor `youtube-dl` were found in %PATH%."; Throw $Raise_Error
}
Write-Debug "Starting $dlcmd to cache the binary before suspending Dropbox."
&$DlCmd --version | Out-Null
# Test FFMPEG
if (!(Get-Command -Name 'ffmpeg' -ErrorAction SilentlyContinue)) {
Write-Warning 'WARNING: FFMPEG not found in %PATH%. Some features might not be available. Press ENTER to continue..'
Read-Host | Out-Null
}
else {
&ffmpeg -version | Out-Null
}
if (!(Get-Command -Name pssuspend -ErrorAction SilentlyContinue)) {
Write-Warning 'Sysinternals'' PSSuspend not found. We won''t be able to suspend the dropbox sync. Press ENTER to continue..'
Read-Host | Out-Null
}
&pssuspend -nobanner | Out-Null
#######
#Region Set up staging area
#######
if (!(Test-Path $tempPath)) {
New-Item -ItemType Directory -Path $TempPath -ErrorAction Stop | Out-Null
}
Set-DropboxIgnoredPath -Path $tempPath
#######
#Endregion
#######
###
### Processing Youtube-DL playlists
###
foreach ($playlist in $Playlists) {
if ($playlist.stepTitle) {
$step = $playlist.stepTitle
}
else {
$step = $playlist.url
}
Write-Information ">>> [PROCESSING]: $step"
Write-Information ">>> [OutPath]: $outPath"
$outPath = $playlist.outPath
if (![System.IO.Path]::IsPathRooted($outPath)) {
$outPath = "$ScriptRoot\$outPath"
}
if (!(Test-Path $outPath)) {
New-Item -ItemType Directory -Path $outPath -Force -Verbose -ErrorAction Stop
}
$outPath = $outPath | Resolve-Path
# Backup archive file
$archivePath = "$outPath\$archiveFileName"
$archiveFileBase = $archiveFileName -replace '\.[^.]+$', ''
$archiveFileExt = $archiveFileName -replace '^.*\.', ''
$archiveBackupDir = "$outPath\_downloaded_old\"
$archiveBackupPath = "${archiveBackupDir}/${archiveFileBase}-${timestamp}.${archiveFileExt}"
if (Test-Path $archivePath) {
if (!(Test-Path -PathType Container $archiveBackupDir)) {
New-Item -ItemType Directory -Path $archiveBackupDir -Force -ErrorAction Stop
}
Copy-Item $archivePath $archiveBackupPath -Verbose
}
if (!$playlist.naming) {
# Default playlist naming style
$playlist.naming = 'playlist/default'
}
if (!($NamingStyles[$playlist.naming])) {
$Raise_Error = "ERROR: Invalid naming style: $($playlist.naming)"; Throw $Raise_Error
}
$Options = @(
'-ciw',
'--download-archive', "`"$archivePath`"",
'-P', "`"$outPath`"",
'-P', "temp:`"$tempPath`"",
'-o', "`"$($NamingStyles[$playlist.naming])`""
'--add-metadata',
'--restrict-filenames'
)
if ($playlist.options) {
$playlist.options.GetEnumerator() | ForEach-Object { $Options += "--$($_.Name)"; $Options += "$($_.Value)" }
}
$Options = $Options | Where-Object { $_ } # Remove empty elements from array
$Options += $playlist.url
$ProcessAborted = $true
try {
Write-Debug 'Suspending Dropbox..'
Start-Process pssuspend -ArgumentList '-nobanner', 'dropbox' -NoNewWindow -Wait
Write-Debug "Starting: $dlcmd $($Options -join ' ') "
$process = Start-Process -FilePath $dlcmd -ArgumentList $Options -NoNewWindow -PassThru -Wait -RedirectStandardOutput $LogYtOut -RedirectStandardError $LogYtErr
Get-Content $LogYtOut
Get-Content $LogYtErr
$ProcessAborted = $false
}
finally {
Write-Debug 'Resuming Dropbox..'
Start-Process pssuspend -ArgumentList '-nobanner', '-r', 'dropbox' -NoNewWindow -Wait
if ($ProcessAborted -eq $true) {
Stop-Transcript
}
}
if ($process.ExitCode -ne 0) {
Write-Error "Process: $($process.Id) $($process.Path) exited with $($process.ExitCode)"
Start-Sleep 5
}
$aOldHash = Get-FileHash $archiveBackupPath -Algorithm SHA256 -ErrorAction SilentlyContinue
$aNewHash = Get-FileHash $archivePath -Algorithm SHA256
if ($aOldHash.Hash -eq $aNewHash.Hash) {
Write-Verbose 'Archive file unchanged. Removing backup archive file..'
Remove-Item $archiveBackupPath -Force -Verbose
}
###
### Sync - unfinished, not working
###
if ($playlist.sync -eq $true ) {
$syncDrive = Get-SyncDevice $playlist.syncToDevice
$syncPath = "${syncDrive}$($playlist.syncRoot)"
Invoke-FileSync -Source $outPath -Destination $syncPath
}
}
Write-Debug 'Download complete.'
Stop-Transcript