Repository navigation
Expand file tree
/
Copy pathNextcloudShare.ps1
More file actions
313 lines (292 loc) · 15.6 KB
/
Copy pathNextcloudShare.ps1
File metadata and controls
313 lines (292 loc) · 15.6 KB
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
[CmdletBinding()]
param(
[ValidateSet('Quick', 'Options', 'Configure')]
[string]$Mode = 'Quick',
[string]$Path
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$diagnosticDirectory = Join-Path $env:LOCALAPPDATA 'NextcloudShare'
$diagnosticLogPath = Join-Path $diagnosticDirectory 'NextcloudShare.log'
$logRotationChecked = $false
function Write-NextcloudShareLog {
param([string]$Message)
try {
if (-not (Test-Path -LiteralPath $diagnosticDirectory)) {
New-Item -ItemType Directory -Path $diagnosticDirectory -Force | Out-Null
}
if (-not $script:logRotationChecked) {
$script:logRotationChecked = $true
if ((Test-Path -LiteralPath $diagnosticLogPath -PathType Leaf) -and
(Get-Item -LiteralPath $diagnosticLogPath).Length -gt 2097152) {
$oldLogPath = $diagnosticLogPath + '.old'
if (Test-Path -LiteralPath $oldLogPath) { Remove-Item -LiteralPath $oldLogPath -Force }
Move-Item -LiteralPath $diagnosticLogPath -Destination $oldLogPath -Force
}
}
[IO.File]::AppendAllText($diagnosticLogPath, "$(Get-Date -Format s) $Message`r`n", [Text.Encoding]::UTF8)
}
catch { }
}
function Join-NextcloudShareExplorerBatch {
param(
[Parameter(Mandatory = $true)][string]$Mode,
[Parameter(Mandatory = $true)][string]$SelectedPath
)
if (-not (Test-Path -LiteralPath $diagnosticDirectory -PathType Container)) {
New-Item -ItemType Directory -Path $diagnosticDirectory -Force | Out-Null
}
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$mutexName = "Local\NextcloudShare.Batch.$sid.$Mode"
$batchPath = Join-Path $diagnosticDirectory ("ExplorerBatch-{0}.txt" -f $Mode)
$mutex = [Threading.Mutex]::new($false, $mutexName)
$ownsMutex = $false
$isLeader = $false
try {
try { $ownsMutex = $mutex.WaitOne(5000) }
catch [Threading.AbandonedMutexException] { $ownsMutex = $true }
if (-not $ownsMutex) { throw (Get-NextcloudShareText 'MultiSelectFailed') }
$useExistingBatch = $false
if (Test-Path -LiteralPath $batchPath -PathType Leaf) {
$age = [DateTime]::UtcNow - (Get-Item -LiteralPath $batchPath).LastWriteTimeUtc
$useExistingBatch = $age.TotalSeconds -le 5
}
if ($useExistingBatch) {
[IO.File]::AppendAllText($batchPath, $SelectedPath + "`r`n", [Text.Encoding]::UTF8)
}
else {
[IO.File]::WriteAllText($batchPath, $SelectedPath + "`r`n", [Text.Encoding]::UTF8)
$isLeader = $true
}
}
finally {
if ($ownsMutex) { $mutex.ReleaseMutex(); $ownsMutex = $false }
}
if (-not $isLeader) {
$mutex.Dispose()
return [pscustomobject]@{ IsLeader = $false; Paths = @() }
}
# Explorer startet Legacy-Verben je nach Windows-Version einmal oder mehrfach.
# Das kurze Zeitfenster fasst die Aufrufe derselben Auswahl zu einem Vorgang zusammen.
Start-Sleep -Milliseconds 700
try {
try { $ownsMutex = $mutex.WaitOne(5000) }
catch [Threading.AbandonedMutexException] { $ownsMutex = $true }
if (-not $ownsMutex) { throw (Get-NextcloudShareText 'MultiSelectIncomplete') }
$collected = if (Test-Path -LiteralPath $batchPath -PathType Leaf) {
@([IO.File]::ReadAllLines($batchPath, [Text.Encoding]::UTF8))
}
else { @($SelectedPath) }
if (Test-Path -LiteralPath $batchPath -PathType Leaf) {
Remove-Item -LiteralPath $batchPath -Force
}
}
finally {
if ($ownsMutex) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$paths = New-Object 'Collections.Generic.List[string]'
foreach ($candidate in $collected) {
if ([string]::IsNullOrWhiteSpace($candidate)) { continue }
if ($seen.Add($candidate)) { $paths.Add($candidate) }
}
return [pscustomobject]@{ IsLeader = $true; Paths = [string[]]$paths.ToArray() }
}
try {
Write-NextcloudShareLog "Start: Mode=$Mode"
Import-Module (Join-Path $PSScriptRoot 'NextcloudShare.Core.psm1') -Force -DisableNameChecking
Write-NextcloudShareLog "Modul geladen. UI-Sprache=$(Get-NextcloudShareUiLanguage)"
if ($Mode -eq 'Configure') {
Show-ConfigurationDialog | Out-Null
exit 0
}
if ([string]::IsNullOrWhiteSpace($Path) -or -not (Test-Path -LiteralPath $Path -PathType Leaf)) {
throw (Get-NextcloudShareText 'SelectFile')
}
$batch = Join-NextcloudShareExplorerBatch -Mode $Mode -SelectedPath $Path
if (-not $batch.IsLeader) {
Write-NextcloudShareLog 'Explorer-Aufruf wurde einer Mehrfachauswahl hinzugefügt.'
exit 0
}
[string[]]$paths = @($batch.Paths)
foreach ($selectedPath in $paths) {
if (-not (Test-Path -LiteralPath $selectedPath -PathType Leaf)) {
throw (Get-NextcloudShareText 'FileUnavailable' -FormatArgs @($selectedPath))
}
}
$itemCount = $paths.Count
$itemDescription = if ($itemCount -eq 1) { [IO.Path]::GetFileName($paths[0]) } else { Get-NextcloudShareText 'ItemCountFiles' -FormatArgs @($itemCount) }
Write-NextcloudShareLog "Explorer-Auswahl gesammelt. Anzahl=$itemCount"
$config = Get-NextcloudShareConfig
$usesLoginFlow = $false
if ($null -ne $config -and $config.PSObject.Properties.Name -contains 'AuthMethod') {
$usesLoginFlow = ($config.AuthMethod -eq 'LoginFlowV2')
}
if ($null -eq $config -or -not $usesLoginFlow) {
if (-not (Show-ConfigurationDialog)) { exit 1 }
$config = Get-NextcloudShareConfig
}
Test-NextcloudShareConfig $config
$config = Initialize-NextcloudWebDavIdentity -Config $config
$hasLocalSync = -not [string]::IsNullOrWhiteSpace([string]$config.LocalNextcloudRoot)
Write-NextcloudShareLog "Konfiguration geprüft. Server=$($config.ServerUrl); Modus=$($config.DefaultMode); Lokale Synchronisation=$hasLocalSync"
$choice = if ($Mode -eq 'Options') {
Write-NextcloudShareLog 'Optionsdialog wird geöffnet.'
$optionsResult = Show-ShareOptionsDialog -Config $config -LocalPaths $paths
Write-NextcloudShareLog "Optionsdialog geschlossen: Auswahl vorhanden=$($null -ne $optionsResult)"
$optionsResult
}
else {
[pscustomobject]@{ Mode = $config.DefaultMode; ExpiryDays = [int]$config.DefaultExpiryDays; Password = ''; Permissions = 1; NotificationEvents = 0; ShareWith = @() }
}
if ($null -eq $choice) { exit 0 }
$sharePassword = [string]$choice.Password
$progress = Show-ProgressWindow (Get-NextcloudShareText 'ProgressConnecting')
$client = $null
try {
$client = New-NextcloudHttpClient $config
if ($itemCount -gt 1) {
Write-NextcloudShareLog 'Mehrfachauswahl wird in einen neuen Nextcloud-Ordner hochgeladen.'
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressCreateFolder')
$remotePath = New-RemoteUploadBatchFolder -Client $client -Config $config
for ($index = 0; $index -lt $itemCount; $index++) {
$currentPath = $paths[$index]
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressUploadFile' -FormatArgs @(($index + 1), $itemCount))
$remoteFilePath = Get-UniqueRemotePathInFolder -Client $client -Config $config -RemoteFolder $remotePath -FileName ([IO.Path]::GetFileName($currentPath))
Send-FileToNextcloud -Client $client -Config $config -LocalPath $currentPath -RemotePath $remoteFilePath
}
Write-NextcloudShareLog "Mehrfachupload erfolgreich abgeschlossen. Anzahl=$itemCount"
}
else {
$remotePath = Get-RemotePathForLocalItem -Config $config -LocalPath $paths[0]
if ($null -eq $remotePath) {
Write-NextcloudShareLog 'Datei liegt außerhalb eines lokalen Syncordners und wird per WebDAV hochgeladen.'
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressUpload')
$remotePath = Get-UniqueRemoteUploadPath -Client $client -Config $config -FileName ([IO.Path]::GetFileName($paths[0]))
Send-FileToNextcloud -Client $client -Config $config -LocalPath $paths[0] -RemotePath $remotePath
Write-NextcloudShareLog 'WebDAV-Upload erfolgreich abgeschlossen.'
}
else {
Write-NextcloudShareLog 'Datei liegt in einem lokalen Syncordner; Serverdatei wird geprüft.'
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressSyncCheck')
$found = $false
for ($attempt = 0; $attempt -lt 6; $attempt++) {
if (Test-RemoteExists -Client $client -Config $config -RemotePath $remotePath) { $found = $true; break }
Start-Sleep -Milliseconds 500
[Windows.Forms.Application]::DoEvents()
}
if (-not $found) { throw (Get-NextcloudShareText 'FileNotSynced') }
}
}
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressCreateLink')
$shareWithUsers = @()
if ($choice.PSObject.Properties.Name -contains 'ShareWith' -and $null -ne $choice.ShareWith) {
$shareWithUsers = @($choice.ShareWith | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | ForEach-Object { [string]$_ })
}
Write-NextcloudShareLog "Freigabe wird erstellt. Typ=$($choice.Mode); AblaufTage=$($choice.ExpiryDays); Berechtigungen=$([int]$choice.Permissions); Benachrichtigungsmaske=$([int]$choice.NotificationEvents); Empfänger=$($shareWithUsers.Count)"
if ($choice.Mode -eq 'Internal') {
$createdShareIds = New-Object 'System.Collections.Generic.List[string]'
if ($shareWithUsers.Count -gt 0) {
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressUserShares')
try {
foreach ($shareWith in $shareWithUsers) {
$userShare = New-UserShare -Client $client -Config $config -RemotePath $remotePath -ShareWith $shareWith -ExpiryDays ([int]$choice.ExpiryDays) -Permissions ([int]$choice.Permissions)
if (-not [string]::IsNullOrWhiteSpace([string]$userShare.ShareId)) {
$createdShareIds.Add([string]$userShare.ShareId)
}
}
}
catch {
$shareError = $_.Exception.Message
foreach ($shareId in $createdShareIds) {
try { Remove-PublicShare -Client $client -Config $config -ShareId $shareId } catch { }
}
throw (Get-NextcloudShareText 'UserSharesRolledBack' -FormatArgs @($shareError))
}
}
if ([int]$choice.NotificationEvents -gt 0) {
$notifyShareId = $null
if ($createdShareIds.Count -gt 0) {
$notifyShareId = [string]$createdShareIds[0]
}
else {
$existingIds = @(Get-NextcloudShareIdsForPath -Client $client -Config $config -RemotePath $remotePath)
if ($existingIds.Count -gt 0) { $notifyShareId = [string]$existingIds[0] }
}
if ([string]::IsNullOrWhiteSpace($notifyShareId)) {
foreach ($shareId in $createdShareIds) {
try { Remove-PublicShare -Client $client -Config $config -ShareId $shareId } catch { }
}
throw (Get-NextcloudShareText 'NotificationsNoShareId')
}
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressNotifications')
try {
Enable-PublicShareNotifications -Client $client -Config $config -ShareId $notifyShareId -EventMask ([int]$choice.NotificationEvents)
Write-NextcloudShareLog "E-Mail-Benachrichtigungen für die Freigabe aktiviert. Maske=$([int]$choice.NotificationEvents)"
}
catch {
$activationError = $_.Exception.Message
foreach ($shareId in $createdShareIds) {
try { Remove-PublicShare -Client $client -Config $config -ShareId $shareId } catch { }
}
throw (Get-NextcloudShareText 'UserSharesRolledBack' -FormatArgs @($activationError))
}
}
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressInternalLink')
$link = Get-InternalFileLink -Client $client -Config $config -RemotePath $remotePath
}
else {
try {
$publicShare = New-PublicShare -Client $client -Config $config -RemotePath $remotePath -ExpiryDays $choice.ExpiryDays -Password $sharePassword -Permissions ([int]$choice.Permissions)
}
catch {
if ($_.Exception.Data['NextcloudShareError'] -ne 'PasswordRequired') { throw }
if ($null -ne $progress) {
$progress.Close()
$progress.Dispose()
$progress = $null
}
$sharePassword = Show-RequiredSharePasswordDialog -ItemDescription $itemDescription
if ([string]::IsNullOrWhiteSpace($sharePassword)) { exit 0 }
$progress = Show-ProgressWindow (Get-NextcloudShareText 'ProgressPasswordLink')
$publicShare = New-PublicShare -Client $client -Config $config -RemotePath $remotePath -ExpiryDays $choice.ExpiryDays -Password $sharePassword -Permissions ([int]$choice.Permissions)
}
$link = [string]$publicShare.Link
if ([int]$choice.NotificationEvents -gt 0) {
Set-ProgressText $progress (Get-NextcloudShareText 'ProgressNotifications')
try {
Enable-PublicShareNotifications -Client $client -Config $config -ShareId ([string]$publicShare.ShareId) -EventMask ([int]$choice.NotificationEvents)
Write-NextcloudShareLog "E-Mail-Benachrichtigungen für die Freigabe aktiviert. Maske=$([int]$choice.NotificationEvents)"
}
catch {
$activationError = $_.Exception.Message
try {
Remove-PublicShare -Client $client -Config $config -ShareId ([string]$publicShare.ShareId)
Write-NextcloudShareLog 'Freigabe nach fehlgeschlagener Aktivierung der E-Mail-Benachrichtigungen zurückgenommen.'
}
catch {
throw (Get-NextcloudShareText 'PublicShareRollbackFailed' -FormatArgs @($activationError, $_.Exception.Message))
}
throw (Get-NextcloudShareText 'PublicShareRolledBack' -FormatArgs @($activationError))
}
}
}
Write-NextcloudShareLog 'Freigabelink erfolgreich erstellt.'
}
finally {
if ($null -ne $client) { $client.Dispose() }
if ($null -ne $progress) { $progress.Close(); $progress.Dispose() }
}
Show-SuccessNotification -Link $link -Password $sharePassword -Mode $choice.Mode
Write-NextcloudShareLog 'Freigabevorgang erfolgreich abgeschlossen.'
}
catch {
Write-NextcloudShareLog ("Fehler: " + ($_ | Out-String))
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue
[Windows.Forms.MessageBox]::Show($_.Exception.Message, (Get-NextcloudShareText 'ErrorTitle'), 'OK', 'Error') | Out-Null
}
catch { }
exit 1
}