Repository navigation
Expand file tree
/
Copy pathNextcloudShare.Core.psm1
More file actions
2313 lines (2104 loc) · 104 KB
/
Copy pathNextcloudShare.Core.psm1
File metadata and controls
2313 lines (2104 loc) · 104 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$script:ProductVersion = '2.2.2'
$script:UiLanguage = $null
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Net.Http
if (-not ('NextcloudShare.Sharee' -as [type])) {
Add-Type -TypeDefinition @'
namespace NextcloudShare {
public class Sharee {
public string ShareWith { get; set; }
public string Label { get; set; }
public string Display { get; set; }
public override string ToString() {
return string.IsNullOrWhiteSpace(Display) ? ShareWith : Display;
}
}
}
'@
}
function Get-NextcloudShareDataDirectory {
$path = Join-Path $env:LOCALAPPDATA 'NextcloudShare'
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
function Get-NextcloudShareConfigPath {
Join-Path (Get-NextcloudShareDataDirectory) 'user.json'
}
function Get-NextcloudShareAdminConfigPath {
Join-Path (Join-Path $env:ProgramData 'NextcloudShare') 'NextcloudShare.config.json'
}
function Get-NextcloudShareDefaultConfig {
[pscustomobject]@{
SchemaVersion = 1
ServerUrl = ''
Username = ''
EncryptedAppPassword = ''
AuthMethod = ''
LocalNextcloudRoot = ''
RemoteUploadFolder = '/NextcloudShare'
RemoteSyncRoot = '/'
DefaultMode = 'Public'
DefaultExpiryDays = 14
SubscriptionsEnabled = $true
AllowServerUrlOverride = $true
AllowRemoteUploadFolderOverride = $true
AllowShareDefaultsOverride = $true
}
}
function Get-NextcloudShareLanguageFromCulture {
try {
$name = [string](Get-UICulture).Name
if ($name -like 'de*') { return 'de' }
}
catch { }
return 'en'
}
function Set-NextcloudShareUserShellVerbs {
param([string]$Language)
if ([string]::IsNullOrWhiteSpace($Language)) { return }
$shareCaption = if ($Language -eq 'de') { 'Über Nextcloud teilen' } else { 'Share via Nextcloud' }
$optionsCaption = if ($Language -eq 'de') { 'Über Nextcloud teilen (mit Optionen) ...' } else { 'Share via Nextcloud (options) ...' }
$wscriptPath = Join-Path $env:SystemRoot 'System32\wscript.exe'
$launcherPath = Join-Path $PSScriptRoot 'NextcloudShare.vbs'
$user = [Microsoft.Win32.Registry]::CurrentUser
foreach ($entry in @(
@{ Name = 'NextcloudShare'; Caption = $shareCaption; Mode = 'Quick' },
@{ Name = 'NextcloudShareOptions'; Caption = $optionsCaption; Mode = 'Options' }
)) {
$key = $user.CreateSubKey("Software\Classes\*\shell\$($entry.Name)")
if ($null -eq $key) { continue }
try {
$key.SetValue('MUIVerb', [string]$entry.Caption, [Microsoft.Win32.RegistryValueKind]::String)
$key.SetValue('Icon', 'shell32.dll,167', [Microsoft.Win32.RegistryValueKind]::String)
$key.SetValue('MultiSelectModel', 'Player', [Microsoft.Win32.RegistryValueKind]::String)
$commandKey = $key.CreateSubKey('command')
if ($null -eq $commandKey) { continue }
try {
$command = '"{0}" "{1}" {2} "%1"' -f $wscriptPath, $launcherPath, [string]$entry.Mode
$commandKey.SetValue('', $command, [Microsoft.Win32.RegistryValueKind]::String)
}
finally {
$commandKey.Dispose()
}
}
finally {
$key.Dispose()
}
}
}
$script:NextcloudShareText = @{
de = @{
AppTitle = 'Nextcloud-Freigabe'
ErrorTitle = 'Nextcloud-Freigabe – Fehler'
ShareDialogTitle = 'Über Nextcloud teilen'
ShareTypeLabel = 'Freigabeart:'
ShareTypePublic = 'Externer Link'
ShareTypeInternal = 'Interner Link (Berechtigung erforderlich)'
ShareTypeInternalShort = 'Interner Link'
PermissionLabel = 'Berechtigung:'
PermissionRead = 'Nur lesen'
PermissionReadWrite = 'Lesen und bearbeiten'
PermissionFull = 'Lesen, bearbeiten, erstellen und löschen'
ExpiryLabel = 'Gültig in Tagen:'
PasswordLabel = 'Optionales Passwort:'
NotifyLabel = 'Benachrichtigen bei:'
NotifyDownload = 'Download'
NotifyUpload = 'Upload'
NotifyModify = 'Änderung'
NotifyDelete = 'Löschung'
UsersLabel = 'Benutzer:'
RemoveUser = 'Entfernen'
ShareButton = 'Teilen'
CancelButton = 'Abbrechen'
SelectUserRequired = 'Bitte wählen Sie mindestens einen Benutzer aus, der Zugriff erhalten soll.'
ShareHintPublic = 'Die Auswahl erstellt oder aktualisiert das Abonnement für diese Datei beziehungsweise diesen Ordner.'
ShareHintInternal = 'Die ausgewählten Benutzer erhalten Zugriff mit der oben gewählten Berechtigung und Ablaufzeit. Der interne Link wird in die Zwischenablage kopiert und alle Benutzer per E-Mail benachrichtigt.'
SearchUsersTip = 'Name oder Benutzername eingeben'
UserSearchTitle = 'Benutzersuche'
SharedFilesFolder = '{0} Dateien – gemeinsamer Link zu einem neuen Ordner'
ItemCountFiles = '{0} Dateien'
PasswordDialogTitle = 'Passwort für öffentlichen Nextcloud-Link'
PasswordRequiredHint = 'Der Nextcloud-Server verlangt für öffentliche Links ein Passwort. Ein sicheres Passwort wurde automatisch erzeugt.'
RegeneratePassword = 'Neu erzeugen'
PasswordCopyHint = 'Nach erfolgreicher Freigabe werden Link und Passwort gemeinsam in die Zwischenablage kopiert.'
CreateLink = 'Link erstellen'
PasswordRequired = 'Bitte geben Sie ein Passwort ein.'
ConfigureTitle = 'Nextcloud-Freigabe konfigurieren'
LabelServerUrl = 'Nextcloud-URL'
LabelUsername = 'Nextcloud-Benutzer'
LabelLocalRoot = 'Lokaler Nextcloud-Ordner (optional)'
LabelRemoteRoot = 'Serverpfad des lokalen Ordners'
LabelUploadFolder = 'Upload-Ordner'
Browse = 'Durchsuchen'
DefaultShareType = 'Standard-Freigabeart'
DefaultExpiry = 'Standard-Ablaufzeit (Tage)'
ConnectionLabel = 'Nextcloud-Verbindung'
ConnectedAs = 'Verbunden als {0}'
NotConnected = 'Noch nicht verbunden'
ConnectNextcloud = 'Mit Nextcloud verbinden'
LoginSecurityHint = 'Die Anmeldung wird im Standardbrowser durchgeführt. Nach „Grant access“ speichert Windows den von Nextcloud ausgestellten Zugriffstoken verschlüsselt mit DPAPI.'
Save = 'Speichern'
LocalFolderMissing = 'Der angegebene lokale Nextcloud-Ordner existiert nicht. Bitte wählen Sie einen vorhandenen Ordner oder lassen Sie das Feld leer.'
LoginCancelled = 'Die Nextcloud-Anmeldung wurde abgebrochen.'
ResolvingWebDav = 'WebDAV-Benutzer-ID wird ermittelt ...'
ConnectionFailed = 'Verbindung fehlgeschlagen'
LoginDialogTitle = 'Nextcloud-Anmeldung'
ConfigDialogTitle = 'Nextcloud-Konfiguration'
LoginAlreadyOpen = 'Eine Nextcloud-Anmeldung ist bereits geöffnet. Bitte schließen Sie den vorhandenen Browser-Dialog oder warten Sie kurz.'
LoginPreparing = 'Nextcloud-Anmeldung wird vorbereitet ...'
LoginBrowserOpened = 'Browser wurde geöffnet. Bitte Zugriff in Nextcloud erlauben ...'
LoginWaiting = 'Warte auf Freigabe im Browser ...'
LoginFailed = 'Die Nextcloud-Anmeldung ist fehlgeschlagen: {0}'
LoginTimeout = 'Die Nextcloud-Anmeldung wurde nicht innerhalb von {0} Minuten abgeschlossen.'
LoginFlowStartFailed = 'Der Nextcloud Login Flow konnte nicht gestartet werden: {0}'
MissingServerUrl = 'Die Nextcloud-URL fehlt.'
InvalidServerUrl = 'Die Nextcloud-URL ist ungültig.'
HttpsRequired = 'Aus Sicherheitsgründen ist für Nextcloud HTTPS erforderlich.'
MissingUsername = 'Der Nextcloud-Benutzername fehlt.'
MissingToken = 'Der Nextcloud-Zugriffstoken fehlt.'
ConfiguredFolderMissing = 'Der konfigurierte lokale Nextcloud-Ordner existiert nicht. Bitte wählen Sie einen vorhandenen Ordner oder lassen Sie das Feld leer.'
MissingUploadFolder = 'Der Upload-Ordner fehlt.'
InvalidShareMode = 'Der Standard-Freigabemodus ist ungültig.'
SelectFile = 'Bitte wählen Sie mindestens eine Datei im Windows-Explorer aus.'
FileUnavailable = 'Die ausgewählte Datei ist nicht mehr verfügbar: {0}'
FileNotSynced = 'Die Datei ist noch nicht auf dem Nextcloud-Server vorhanden. Bitte warten Sie auf die Synchronisierung und versuchen Sie es erneut.'
MultiSelectFailed = 'Die Mehrfachauswahl konnte nicht gesammelt werden. Bitte versuchen Sie es erneut.'
MultiSelectIncomplete = 'Die Mehrfachauswahl konnte nicht abgeschlossen werden. Bitte versuchen Sie es erneut.'
ProgressConnecting = 'Verbindung mit Nextcloud wird hergestellt ...'
ProgressCreateFolder = 'Zielordner wird in Nextcloud angelegt ...'
ProgressUploadFile = 'Datei {0} von {1} wird hochgeladen ...'
ProgressUpload = 'Datei wird nach Nextcloud hochgeladen ...'
ProgressSyncCheck = 'Synchronisierte Datei wird geprüft ...'
ProgressCreateLink = 'Freigabelink wird erzeugt ...'
ProgressUserShares = 'Benutzerfreigaben werden erstellt ...'
ProgressNotifications = 'E-Mail-Benachrichtigungen werden aktiviert ...'
ProgressInternalLink = 'Interner Link wird erzeugt ...'
ProgressPasswordLink = 'Passwortgeschützter Freigabelink wird erzeugt ...'
NotificationsNoShareId = 'Die E-Mail-Benachrichtigungen konnten nicht aktiviert werden, weil keine Freigabe-ID ermittelt wurde. Bereits erstellte Benutzerfreigaben wurden automatisch zurückgenommen.'
UserSharesRolledBack = '{0} Bereits erstellte Benutzerfreigaben wurden automatisch zurückgenommen.'
PublicShareRolledBack = '{0} Die unvollständige Freigabe wurde automatisch zurückgenommen.'
PublicShareRollbackFailed = '{0} Die Freigabe konnte anschließend nicht automatisch zurückgenommen werden: {1}'
ClipboardBlocked = 'Die Freigabe wurde erfolgreich erstellt, aber die Windows-Zwischenablage ist momentan blockiert. Markieren Sie den Text und kopieren Sie ihn mit Strg+C oder versuchen Sie es erneut.'
ClipboardHint = 'Link und gegebenenfalls Passwort bleiben hier sichtbar.'
CopyAgain = 'Erneut kopieren'
ClipboardStillBlocked = 'Zwischenablage weiterhin blockiert. Bitte Strg+C verwenden.'
Close = 'Schließen'
ClipboardDialogTitle = 'Nextcloud-Freigabe erstellt'
SuccessLinkCopied = 'Der Link wurde in die Zwischenablage kopiert.'
SuccessLinkAndPassword = 'Link und Passwort wurden in die Zwischenablage kopiert.'
SuccessInternalNotified = 'Der Link wurde in die Zwischenablage kopiert und alle Benutzer per E-Mail benachrichtigt.'
ClipboardLinkPassword = "Link: {0}`r`nPasswort: {1}"
ShellShare = 'Über Nextcloud teilen'
ShellShareOptions = 'Über Nextcloud teilen (mit Optionen) ...'
ConfigureShortcutName = 'Nextcloud-Freigabe konfigurieren.lnk'
BatchFolderPrefix = 'Freigabe-'
NotificationsFailed = 'Die E-Mail-Benachrichtigungen konnten nicht aktiviert werden: {0}'
ShareCreateFailed = 'Der Freigabelink konnte nicht erzeugt werden: {0}'
UserShareFailed = 'Die Freigabe für den Benutzer konnte nicht erzeugt werden: {0}'
UserSearchFailed = 'Die Benutzersuche ist fehlgeschlagen: {0}'
InternalLinkFailed = 'Der interne Link konnte nicht ermittelt werden: {0}'
UploadFailed = 'Die Datei konnte nicht nach Nextcloud hochgeladen werden: {0}'
}
en = @{
AppTitle = 'Nextcloud Share'
ErrorTitle = 'Nextcloud Share – Error'
ShareDialogTitle = 'Share via Nextcloud'
ShareTypeLabel = 'Share type:'
ShareTypePublic = 'Public link'
ShareTypeInternal = 'Internal link (permission required)'
ShareTypeInternalShort = 'Internal link'
PermissionLabel = 'Permission:'
PermissionRead = 'Read only'
PermissionReadWrite = 'Read and edit'
PermissionFull = 'Read, edit, create and delete'
ExpiryLabel = 'Valid for days:'
PasswordLabel = 'Optional password:'
NotifyLabel = 'Notify on:'
NotifyDownload = 'Download'
NotifyUpload = 'Upload'
NotifyModify = 'Modification'
NotifyDelete = 'Deletion'
UsersLabel = 'Users:'
RemoveUser = 'Remove'
ShareButton = 'Share'
CancelButton = 'Cancel'
SelectUserRequired = 'Please select at least one user who should receive access.'
ShareHintPublic = 'This selection creates or updates the subscription for this file or folder.'
ShareHintInternal = 'Selected users receive access with the permission and expiry chosen above. The internal link is copied to the clipboard and all users are notified by email.'
SearchUsersTip = 'Enter a name or username'
UserSearchTitle = 'User search'
SharedFilesFolder = '{0} files – shared link to a new folder'
ItemCountFiles = '{0} files'
PasswordDialogTitle = 'Password for public Nextcloud link'
PasswordRequiredHint = 'The Nextcloud server requires a password for public links. A secure password was generated automatically.'
RegeneratePassword = 'Generate new'
PasswordCopyHint = 'After a successful share, the link and password are copied to the clipboard together.'
CreateLink = 'Create link'
PasswordRequired = 'Please enter a password.'
ConfigureTitle = 'Configure Nextcloud Share'
LabelServerUrl = 'Nextcloud URL'
LabelUsername = 'Nextcloud user'
LabelLocalRoot = 'Local Nextcloud folder (optional)'
LabelRemoteRoot = 'Server path of the local folder'
LabelUploadFolder = 'Upload folder'
Browse = 'Browse'
DefaultShareType = 'Default share type'
DefaultExpiry = 'Default expiry (days)'
ConnectionLabel = 'Nextcloud connection'
ConnectedAs = 'Connected as {0}'
NotConnected = 'Not connected yet'
ConnectNextcloud = 'Connect to Nextcloud'
LoginSecurityHint = 'Sign-in opens in your default browser. After “Grant access”, Windows stores the Nextcloud app password encrypted with DPAPI.'
Save = 'Save'
LocalFolderMissing = 'The specified local Nextcloud folder does not exist. Please choose an existing folder or leave the field empty.'
LoginCancelled = 'Nextcloud sign-in was cancelled.'
ResolvingWebDav = 'Determining WebDAV user ID ...'
ConnectionFailed = 'Connection failed'
LoginDialogTitle = 'Nextcloud sign-in'
ConfigDialogTitle = 'Nextcloud configuration'
LoginAlreadyOpen = 'A Nextcloud sign-in is already open. Please close the existing browser dialog or wait a moment.'
LoginPreparing = 'Preparing Nextcloud sign-in ...'
LoginBrowserOpened = 'The browser was opened. Please grant access in Nextcloud ...'
LoginWaiting = 'Waiting for approval in the browser ...'
LoginFailed = 'Nextcloud sign-in failed: {0}'
LoginTimeout = 'Nextcloud sign-in was not completed within {0} minutes.'
LoginFlowStartFailed = 'The Nextcloud login flow could not be started: {0}'
MissingServerUrl = 'The Nextcloud URL is missing.'
InvalidServerUrl = 'The Nextcloud URL is invalid.'
HttpsRequired = 'HTTPS is required for Nextcloud for security reasons.'
MissingUsername = 'The Nextcloud user name is missing.'
MissingToken = 'The Nextcloud access token is missing.'
ConfiguredFolderMissing = 'The configured local Nextcloud folder does not exist. Please choose an existing folder or leave the field empty.'
MissingUploadFolder = 'The upload folder is missing.'
InvalidShareMode = 'The default share mode is invalid.'
SelectFile = 'Please select at least one file in Windows Explorer.'
FileUnavailable = 'The selected file is no longer available: {0}'
FileNotSynced = 'The file is not yet on the Nextcloud server. Please wait for synchronization and try again.'
MultiSelectFailed = 'The multiple selection could not be collected. Please try again.'
MultiSelectIncomplete = 'The multiple selection could not be completed. Please try again.'
ProgressConnecting = 'Connecting to Nextcloud ...'
ProgressCreateFolder = 'Creating the destination folder in Nextcloud ...'
ProgressUploadFile = 'Uploading file {0} of {1} ...'
ProgressUpload = 'Uploading the file to Nextcloud ...'
ProgressSyncCheck = 'Checking the synchronized file ...'
ProgressCreateLink = 'Creating the share link ...'
ProgressUserShares = 'Creating user shares ...'
ProgressNotifications = 'Enabling email notifications ...'
ProgressInternalLink = 'Creating the internal link ...'
ProgressPasswordLink = 'Creating the password-protected share link ...'
NotificationsNoShareId = 'Email notifications could not be enabled because no share ID was returned. User shares created so far were rolled back automatically.'
UserSharesRolledBack = '{0} User shares created so far were rolled back automatically.'
PublicShareRolledBack = '{0} The incomplete share was rolled back automatically.'
PublicShareRollbackFailed = '{0} The share could not be rolled back automatically afterwards: {1}'
ClipboardBlocked = 'The share was created successfully, but the Windows clipboard is currently blocked. Select the text and copy it with Ctrl+C, or try again.'
ClipboardHint = 'The link and password, if any, remain visible here.'
CopyAgain = 'Copy again'
ClipboardStillBlocked = 'Clipboard still blocked. Please use Ctrl+C.'
Close = 'Close'
ClipboardDialogTitle = 'Nextcloud share created'
SuccessLinkCopied = 'The link was copied to the clipboard.'
SuccessLinkAndPassword = 'The link and password were copied to the clipboard.'
SuccessInternalNotified = 'The link was copied to the clipboard and all users were notified by email.'
ClipboardLinkPassword = "Link: {0}`r`nPassword: {1}"
ShellShare = 'Share via Nextcloud'
ShellShareOptions = 'Share via Nextcloud (options) ...'
ConfigureShortcutName = 'Configure Nextcloud Share.lnk'
BatchFolderPrefix = 'Share-'
NotificationsFailed = 'Email notifications could not be enabled: {0}'
ShareCreateFailed = 'The share link could not be created: {0}'
UserShareFailed = 'The user share could not be created: {0}'
UserSearchFailed = 'User search failed: {0}'
InternalLinkFailed = 'The internal link could not be determined: {0}'
UploadFailed = 'The file could not be uploaded to Nextcloud: {0}'
}
}
function Get-NextcloudShareUiLanguage {
if (-not [string]::IsNullOrWhiteSpace([string]$script:UiLanguage)) {
return [string]$script:UiLanguage
}
$script:UiLanguage = Get-NextcloudShareLanguageFromCulture
try { Set-NextcloudShareUserShellVerbs -Language $script:UiLanguage } catch { }
return $script:UiLanguage
}
function Get-NextcloudShareText {
param(
[Parameter(Mandatory = $true)][string]$Key,
[object[]]$FormatArgs
)
$lang = Get-NextcloudShareUiLanguage
$table = $script:NextcloudShareText[$lang]
if ($null -eq $table -or -not $table.ContainsKey($Key)) {
$table = $script:NextcloudShareText['de']
}
$text = [string]$table[$Key]
if ([string]::IsNullOrWhiteSpace($text)) { $text = $Key }
if ($null -ne $FormatArgs -and @($FormatArgs).Count -gt 0) {
return ($text -f $FormatArgs)
}
return $text
}
function Get-NextcloudShareAdminConfig {
$path = Get-NextcloudShareAdminConfigPath
$config = Get-NextcloudShareDefaultConfig
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
return $config
}
try {
$admin = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json
foreach ($name in @('SchemaVersion', 'ServerUrl', 'RemoteUploadFolder', 'RemoteSyncRoot', 'SubscriptionsEnabled')) {
if ($admin.PSObject.Properties.Name -contains $name) {
Add-Member -InputObject $config -MemberType NoteProperty -Name $name -Value $admin.$name -Force
}
}
if ($admin.PSObject.Properties.Name -contains 'Defaults') {
if ($admin.Defaults.PSObject.Properties.Name -contains 'ShareMode') { $config.DefaultMode = [string]$admin.Defaults.ShareMode }
if ($admin.Defaults.PSObject.Properties.Name -contains 'ExpiryDays') { $config.DefaultExpiryDays = [int]$admin.Defaults.ExpiryDays }
}
if ($admin.PSObject.Properties.Name -contains 'UserOverrides') {
if ($admin.UserOverrides.PSObject.Properties.Name -contains 'ServerUrl') { $config.AllowServerUrlOverride = [bool]$admin.UserOverrides.ServerUrl }
if ($admin.UserOverrides.PSObject.Properties.Name -contains 'RemoteUploadFolder') { $config.AllowRemoteUploadFolderOverride = [bool]$admin.UserOverrides.RemoteUploadFolder }
if ($admin.UserOverrides.PSObject.Properties.Name -contains 'ShareDefaults') { $config.AllowShareDefaultsOverride = [bool]$admin.UserOverrides.ShareDefaults }
}
return $config
}
catch {
throw "Die zentrale Konfiguration '$path' konnte nicht gelesen werden: $($_.Exception.Message)"
}
}
function Get-NextcloudClientSyncRoot {
param([string]$ServerUrl = '')
$configPaths = @()
if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) {
$configPaths += Join-Path $env:APPDATA 'Nextcloud\nextcloud.cfg'
}
if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
$configPaths += Join-Path $env:LOCALAPPDATA 'Nextcloud\nextcloud.cfg'
}
$configuredFolders = @()
foreach ($configPath in ($configPaths | Select-Object -Unique)) {
if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) { continue }
try {
$accountUrls = @{}
$folderEntries = @()
foreach ($line in (Get-Content -LiteralPath $configPath -Encoding UTF8 -ErrorAction Stop)) {
if ($line -match '^\s*(\d+)\\url=(.*?)\s*$') {
$accountUrls[$matches[1]] = $matches[2].Trim().TrimEnd('/')
}
elseif ($line -match '^\s*(\d+)\\Folders\\\d+\\localPath=(.*?)\s*$') {
$folderEntries += [pscustomobject]@{
Account = $matches[1]
Path = $matches[2].Trim()
}
}
}
foreach ($entry in $folderEntries) {
$candidate = ([Environment]::ExpandEnvironmentVariables([string]$entry.Path)).TrimEnd('/', '\').Replace('/', '\')
if ([string]::IsNullOrWhiteSpace($candidate) -or
-not (Test-Path -LiteralPath $candidate -PathType Container)) { continue }
$accountUrl = if ($accountUrls.ContainsKey([string]$entry.Account)) { [string]$accountUrls[[string]$entry.Account] } else { '' }
$configuredFolders += [pscustomobject]@{
Path = $candidate
ServerMatch = -not [string]::IsNullOrWhiteSpace($ServerUrl) -and
[string]::Equals($accountUrl, $ServerUrl.Trim().TrimEnd('/'), [StringComparison]::OrdinalIgnoreCase)
}
}
}
catch {
# Eine unlesbare Client-Konfiguration verhindert die Freigabe nicht.
}
}
$match = $configuredFolders | Where-Object ServerMatch | Select-Object -First 1
if ($null -ne $match) { return [string]$match.Path }
$first = $configuredFolders | Select-Object -First 1
if ($null -ne $first) { return [string]$first.Path }
$defaultPath = Join-Path $env:USERPROFILE 'Nextcloud'
if (Test-Path -LiteralPath $defaultPath -PathType Container) { return $defaultPath }
return ''
}
function Protect-AppPassword {
param([Parameter(Mandatory = $true)][string]$PlainText)
$secure = ConvertTo-SecureString -String $PlainText -AsPlainText -Force
return ConvertFrom-SecureString -SecureString $secure
}
function Unprotect-AppPassword {
param([Parameter(Mandatory = $true)][string]$CipherText)
$secure = ConvertTo-SecureString -String $CipherText
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try {
return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
}
finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr)
}
}
function Get-NextcloudShareConfig {
$path = Get-NextcloudShareConfigPath
$admin = Get-NextcloudShareAdminConfig
if (-not (Test-Path -LiteralPath $path)) {
if (-not [string]::IsNullOrWhiteSpace([string]$admin.ServerUrl)) { return $admin }
return $null
}
try {
$config = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json
$userServerUrl = if ($config.PSObject.Properties.Name -contains 'ServerUrl') {
[string]$config.ServerUrl
}
else { '' }
$changed = $false
foreach ($property in $admin.PSObject.Properties) {
if (-not ($config.PSObject.Properties.Name -contains $property.Name)) {
Add-Member -InputObject $config -MemberType NoteProperty -Name $property.Name -Value $property.Value -Force
}
}
if (-not $admin.AllowServerUrlOverride -or [string]::IsNullOrWhiteSpace([string]$config.ServerUrl)) {
$config.ServerUrl = [string]$admin.ServerUrl
}
if (-not $admin.AllowRemoteUploadFolderOverride) {
$config.RemoteUploadFolder = [string]$admin.RemoteUploadFolder
}
if (-not $admin.AllowShareDefaultsOverride) {
$config.DefaultMode = [string]$admin.DefaultMode
$config.DefaultExpiryDays = [int]$admin.DefaultExpiryDays
}
$config.SubscriptionsEnabled = [bool]$admin.SubscriptionsEnabled
if ($config.PSObject.Properties.Name -contains 'Language') {
$config.PSObject.Properties.Remove('Language')
}
$authenticatedServerUrl = if ($config.PSObject.Properties.Name -contains 'AuthenticatedServerUrl') {
[string]$config.AuthenticatedServerUrl
}
else { $userServerUrl }
if (-not [string]::IsNullOrWhiteSpace($authenticatedServerUrl) -and
-not [string]::Equals(
$authenticatedServerUrl.TrimEnd('/'),
([string]$config.ServerUrl).TrimEnd('/'),
[StringComparison]::OrdinalIgnoreCase
)) {
$config.EncryptedAppPassword = ''
$config.AuthMethod = ''
$changed = $true
}
$configuredLocalRoot = if ($config.PSObject.Properties.Name -contains 'LocalNextcloudRoot') {
[string]$config.LocalNextcloudRoot
}
else { '' }
if ([string]::IsNullOrWhiteSpace($configuredLocalRoot) -or
-not (Test-Path -LiteralPath $configuredLocalRoot -PathType Container)) {
$detectedLocalRoot = Get-NextcloudClientSyncRoot -ServerUrl ([string]$config.ServerUrl)
if (-not [string]::Equals($configuredLocalRoot, $detectedLocalRoot, [StringComparison]::OrdinalIgnoreCase)) {
Add-Member -InputObject $config -MemberType NoteProperty -Name LocalNextcloudRoot -Value $detectedLocalRoot -Force
$changed = $true
}
}
if ($changed) { Save-NextcloudShareConfig $config }
return $config
}
catch {
throw "Die Konfiguration '$path' konnte nicht gelesen werden: $($_.Exception.Message)"
}
}
function Save-NextcloudShareConfig {
param([Parameter(Mandatory = $true)]$Config)
if ($Config.PSObject.Properties.Name -contains 'Language') {
$Config.PSObject.Properties.Remove('Language')
}
$Config | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Get-NextcloudShareConfigPath) -Encoding UTF8
}
function Test-NextcloudShareConfig {
param([Parameter(Mandatory = $true)]$Config)
if ([string]::IsNullOrWhiteSpace($Config.ServerUrl)) { throw (Get-NextcloudShareText 'MissingServerUrl') }
$uri = $null
if (-not [Uri]::TryCreate($Config.ServerUrl, [UriKind]::Absolute, [ref]$uri)) { throw (Get-NextcloudShareText 'InvalidServerUrl') }
if ($uri.Scheme -ne 'https' -and $uri.Host -notin @('localhost', '127.0.0.1')) {
throw (Get-NextcloudShareText 'HttpsRequired')
}
if ([string]::IsNullOrWhiteSpace($Config.Username)) { throw (Get-NextcloudShareText 'MissingUsername') }
if ([string]::IsNullOrWhiteSpace($Config.EncryptedAppPassword)) { throw (Get-NextcloudShareText 'MissingToken') }
$localRoot = if ($Config.PSObject.Properties.Name -contains 'LocalNextcloudRoot') {
[string]$Config.LocalNextcloudRoot
}
else { '' }
if (-not [string]::IsNullOrWhiteSpace($localRoot) -and
-not (Test-Path -LiteralPath $localRoot -PathType Container)) {
throw (Get-NextcloudShareText 'ConfiguredFolderMissing')
}
if ([string]::IsNullOrWhiteSpace($Config.RemoteUploadFolder)) { throw (Get-NextcloudShareText 'MissingUploadFolder') }
if ($Config.DefaultMode -notin @('Public', 'Internal')) { throw (Get-NextcloudShareText 'InvalidShareMode') }
}
function Test-NextcloudServerUrl {
param([Parameter(Mandatory = $true)][string]$ServerUrl)
if ([string]::IsNullOrWhiteSpace($ServerUrl)) { throw (Get-NextcloudShareText 'MissingServerUrl') }
$uri = $null
if (-not [Uri]::TryCreate($ServerUrl, [UriKind]::Absolute, [ref]$uri)) { throw (Get-NextcloudShareText 'InvalidServerUrl') }
if ($uri.Scheme -ne 'https' -and $uri.Host -notin @('localhost', '127.0.0.1')) {
throw (Get-NextcloudShareText 'HttpsRequired')
}
}
function ConvertTo-EncodedPath {
param([Parameter(Mandatory = $true)][string]$Path)
$parts = $Path.Trim('/') -split '/'
return ($parts | Where-Object { $_ -ne '' } | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/'
}
function Get-WebDavUri {
param(
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$RemotePath
)
$base = $Config.ServerUrl.TrimEnd('/')
$encoded = ConvertTo-EncodedPath $RemotePath
$endpointMode = 'Modern'
if ($Config.PSObject.Properties.Name -contains 'WebDavEndpoint') {
$endpointMode = [string]$Config.WebDavEndpoint
}
if ($endpointMode -eq 'Legacy') {
if ($encoded) { return "$base/remote.php/webdav/$encoded" }
return "$base/remote.php/webdav/"
}
$webDavUserId = [string]$Config.Username
if ($Config.PSObject.Properties.Name -contains 'WebDavUserId' -and
-not [string]::IsNullOrWhiteSpace([string]$Config.WebDavUserId)) {
$webDavUserId = [string]$Config.WebDavUserId
}
$user = [Uri]::EscapeDataString($webDavUserId)
if ($encoded) { return "$base/remote.php/dav/files/$user/$encoded" }
return "$base/remote.php/dav/files/$user/"
}
function New-NextcloudHttpClient {
param([Parameter(Mandatory = $true)]$Config)
$password = Unprotect-AppPassword $Config.EncryptedAppPassword
try {
$bytes = [Text.Encoding]::UTF8.GetBytes("$($Config.Username):$password")
$token = [Convert]::ToBase64String($bytes)
}
finally {
$password = $null
}
$client = [System.Net.Http.HttpClient]::new()
$client.Timeout = [TimeSpan]::FromHours(4)
$client.DefaultRequestHeaders.Authorization = [System.Net.Http.Headers.AuthenticationHeaderValue]::new('Basic', $token)
$client.DefaultRequestHeaders.UserAgent.ParseAdd("NextcloudShare/$script:ProductVersion")
return $client
}
function Invoke-HttpRequest {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)][string]$Method,
[Parameter(Mandatory = $true)][string]$Uri,
[System.Net.Http.HttpContent]$Content,
[hashtable]$Headers
)
$request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::new($Method), $Uri)
try {
if ($null -ne $Content) { $request.Content = $Content }
if ($Headers) {
foreach ($name in $Headers.Keys) {
$null = $request.Headers.TryAddWithoutValidation($name, [string]$Headers[$name])
}
}
$response = $Client.SendAsync($request).GetAwaiter().GetResult()
try {
$body = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
return [pscustomobject]@{
IsSuccess = $response.IsSuccessStatusCode
StatusCode = [int]$response.StatusCode
Reason = $response.ReasonPhrase
Body = $body
}
}
finally {
$response.Dispose()
}
}
finally {
$request.Dispose()
}
}
function Start-NextcloudLoginFlow {
param(
[Parameter(Mandatory = $true)][string]$ServerUrl,
[scriptblock]$StatusCallback,
[int]$TimeoutMinutes = 20
)
Test-NextcloudServerUrl $ServerUrl
$baseUrl = $ServerUrl.TrimEnd('/')
$mutex = [Threading.Mutex]::new($false, 'Local\NextcloudShare.LoginFlow')
$ownsMutex = $false
try {
try { $ownsMutex = $mutex.WaitOne(0) }
catch [Threading.AbandonedMutexException] { $ownsMutex = $true }
if (-not $ownsMutex) {
throw (Get-NextcloudShareText 'LoginAlreadyOpen')
}
}
catch {
$mutex.Dispose()
throw
}
$client = [System.Net.Http.HttpClient]::new()
$client.Timeout = [TimeSpan]::FromSeconds(30)
$client.DefaultRequestHeaders.UserAgent.ParseAdd("NextcloudShare/$script:ProductVersion")
try {
if ($StatusCallback) { & $StatusCallback (Get-NextcloudShareText 'LoginPreparing') }
$startResponse = Invoke-HttpRequest -Client $client -Method 'POST' -Uri "$baseUrl/index.php/login/v2"
if (-not $startResponse.IsSuccess) {
throw (Get-NextcloudShareText 'LoginFlowStartFailed' -FormatArgs @(Get-HttpErrorText $startResponse))
}
try { $flow = $startResponse.Body | ConvertFrom-Json }
catch { throw 'Nextcloud hat keine gültige Login-Flow-Antwort geliefert.' }
if ([string]::IsNullOrWhiteSpace($flow.login) -or
[string]::IsNullOrWhiteSpace($flow.poll.token) -or
[string]::IsNullOrWhiteSpace($flow.poll.endpoint)) {
throw 'Die Login-Flow-Antwort von Nextcloud ist unvollständig.'
}
if ($StatusCallback) { & $StatusCallback (Get-NextcloudShareText 'LoginBrowserOpened') }
Start-Process -FilePath ([string]$flow.login) | Out-Null
$deadline = (Get-Date).AddMinutes($TimeoutMinutes)
while ((Get-Date) -lt $deadline) {
[Windows.Forms.Application]::DoEvents()
Start-Sleep -Milliseconds 1000
$pairs = New-Object 'System.Collections.Generic.List[System.Collections.Generic.KeyValuePair[string,string]]'
$pairs.Add([Collections.Generic.KeyValuePair[string,string]]::new('token', [string]$flow.poll.token))
$content = [System.Net.Http.FormUrlEncodedContent]::new($pairs)
$pollResponse = Invoke-HttpRequest -Client $client -Method 'POST' -Uri ([string]$flow.poll.endpoint) -Content $content
if ($pollResponse.StatusCode -eq 404) {
if ($StatusCallback) { & $StatusCallback (Get-NextcloudShareText 'LoginWaiting') }
continue
}
if (-not $pollResponse.IsSuccess) {
throw (Get-NextcloudShareText 'LoginFailed' -FormatArgs @(Get-HttpErrorText $pollResponse))
}
try { $credentials = $pollResponse.Body | ConvertFrom-Json }
catch { throw 'Nextcloud hat keine gültigen Anmeldedaten geliefert.' }
if ([string]::IsNullOrWhiteSpace($credentials.server) -or
[string]::IsNullOrWhiteSpace($credentials.loginName) -or
[string]::IsNullOrWhiteSpace($credentials.appPassword)) {
throw 'Die von Nextcloud gelieferten Anmeldedaten sind unvollständig.'
}
if ($StatusCallback) { & $StatusCallback (Get-NextcloudShareText 'ConnectedAs' -FormatArgs @($credentials.loginName)) }
return [pscustomobject]@{
ServerUrl = ([string]$credentials.server).TrimEnd('/')
Username = [string]$credentials.loginName
AppPassword = [string]$credentials.appPassword
}
}
throw (Get-NextcloudShareText 'LoginTimeout' -FormatArgs @($TimeoutMinutes))
}
finally {
$client.Dispose()
if ($ownsMutex) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
}
function Get-HttpErrorText {
param($Response)
if (-not [string]::IsNullOrWhiteSpace($Response.Body)) {
try {
$json = $Response.Body | ConvertFrom-Json
if ($json.ocs.meta.message) { return [string]$json.ocs.meta.message }
}
catch { }
if ($Response.Body.Length -le 500 -and $Response.Body -notmatch '<html') { return $Response.Body }
}
return "HTTP $($Response.StatusCode) $($Response.Reason)"
}
function Test-OcsSuccess {
param([Parameter(Mandatory = $true)]$Result)
$status = ''
$statusCode = 0
if ($Result.ocs.meta.PSObject.Properties.Name -contains 'status') {
$status = [string]$Result.ocs.meta.status
}
if ($Result.ocs.meta.PSObject.Properties.Name -contains 'statuscode') {
$statusCode = [int]$Result.ocs.meta.statuscode
}
return $status.Equals('ok', [StringComparison]::OrdinalIgnoreCase) -or $statusCode -in @(100, 200)
}
function Get-NextcloudCurrentUserId {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config
)
$uri = Get-OcsUri $Config 'cloud/user?format=json'
$response = Invoke-HttpRequest -Client $Client -Method 'GET' -Uri $uri -Headers @{
'OCS-APIRequest' = 'true'
'Accept' = 'application/json'
}
if (-not $response.IsSuccess) {
throw "Die Nextcloud-Benutzer-ID konnte nicht ermittelt werden: $(Get-HttpErrorText $response)"
}
try { $result = $response.Body | ConvertFrom-Json }
catch { throw 'Nextcloud hat keine gültigen Benutzerdaten geliefert.' }
if (-not (Test-OcsSuccess $result) -or
[string]::IsNullOrWhiteSpace([string]$result.ocs.data.id)) {
throw "Die Nextcloud-Benutzer-ID konnte nicht ermittelt werden: $($result.ocs.meta.message)"
}
return [string]$result.ocs.data.id
}
function Test-NextcloudWebDavRoot {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config
)
$response = Invoke-HttpRequest -Client $Client -Method 'PROPFIND' -Uri (Get-WebDavUri $Config '/') -Headers @{ 'Depth' = '0' }
if (-not $response.IsSuccess) {
throw "Das Nextcloud-Dateiverzeichnis konnte nicht geöffnet werden: $(Get-HttpErrorText $response)"
}
}
function Initialize-NextcloudWebDavIdentity {
param(
[Parameter(Mandatory = $true)]$Config,
[switch]$Force
)
$hasUserId = $Config.PSObject.Properties.Name -contains 'WebDavUserId' -and
-not [string]::IsNullOrWhiteSpace([string]$Config.WebDavUserId)
$hasEndpoint = $Config.PSObject.Properties.Name -contains 'WebDavEndpoint' -and
[string]$Config.WebDavEndpoint -in @('Modern', 'Legacy')
if (-not $Force -and $hasUserId -and $hasEndpoint) { return $Config }
$client = New-NextcloudHttpClient $Config
try {
$modernError = $null
try {
$userId = Get-NextcloudCurrentUserId -Client $client -Config $Config
Add-Member -InputObject $Config -MemberType NoteProperty -Name WebDavUserId -Value $userId -Force
Add-Member -InputObject $Config -MemberType NoteProperty -Name WebDavEndpoint -Value 'Modern' -Force
Test-NextcloudWebDavRoot -Client $client -Config $Config
}
catch {
$modernError = $_.Exception.Message
Add-Member -InputObject $Config -MemberType NoteProperty -Name WebDavUserId -Value ([string]$Config.Username) -Force
Add-Member -InputObject $Config -MemberType NoteProperty -Name WebDavEndpoint -Value 'Legacy' -Force
try {
Test-NextcloudWebDavRoot -Client $client -Config $Config
}
catch {
throw "Das Nextcloud-Dateiverzeichnis ist weder über die ermittelte Benutzer-ID noch über den kompatiblen WebDAV-Endpunkt erreichbar.`r`n`r`nModerner Endpunkt: $modernError`r`nKompatibler Endpunkt: $($_.Exception.Message)"
}
}
}
finally {
$client.Dispose()
}
Save-NextcloudShareConfig $Config
return $Config
}
function Test-RemoteExists {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$RemotePath
)
$response = Invoke-HttpRequest -Client $Client -Method 'HEAD' -Uri (Get-WebDavUri $Config $RemotePath)
if ($response.StatusCode -eq 404) { return $false }
if (-not $response.IsSuccess) { throw "Nextcloud konnte nicht erreicht werden: $(Get-HttpErrorText $response)" }
return $true
}
function Ensure-RemoteFolder {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$RemoteFolder
)
$current = ''
foreach ($part in ($RemoteFolder.Trim('/') -split '/')) {
if ([string]::IsNullOrWhiteSpace($part)) { continue }
$current += "/$part"
$response = Invoke-HttpRequest -Client $Client -Method 'MKCOL' -Uri (Get-WebDavUri $Config $current)
if (-not $response.IsSuccess -and $response.StatusCode -ne 405) {
throw "Der Nextcloud-Ordner '$current' konnte nicht angelegt werden: $(Get-HttpErrorText $response)"
}
}
}
function Join-RemotePath {
param([string]$Left, [string]$Right)
return '/' + (($Left.Trim('/') + '/' + $Right.Trim('/')).Trim('/'))
}
function Get-UniqueRemotePathInFolder {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$RemoteFolder,
[Parameter(Mandatory = $true)][string]$FileName
)
$candidate = Join-RemotePath $RemoteFolder $FileName
if (-not (Test-RemoteExists -Client $Client -Config $Config -RemotePath $candidate)) { return $candidate }
$base = [IO.Path]::GetFileNameWithoutExtension($FileName)
$extension = [IO.Path]::GetExtension($FileName)
for ($number = 2; $number -le 9999; $number++) {
$candidate = Join-RemotePath $RemoteFolder ("{0}-{1}{2}" -f $base, $number, $extension)
if (-not (Test-RemoteExists -Client $Client -Config $Config -RemotePath $candidate)) { return $candidate }
}
throw "Für die Datei '$FileName' konnte kein eindeutiger Name im Nextcloud-Zielordner erzeugt werden."
}
function New-RemoteUploadBatchFolder {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config
)
$monthFolder = Join-RemotePath ([string]$Config.RemoteUploadFolder) (Get-Date -Format 'yyyy-MM')
Ensure-RemoteFolder -Client $Client -Config $Config -RemoteFolder $monthFolder
$baseName = (Get-NextcloudShareText 'BatchFolderPrefix') + (Get-Date -Format 'yyyyMMdd-HHmmss')
for ($number = 1; $number -le 9999; $number++) {
$folderName = if ($number -eq 1) { $baseName } else { "$baseName-$number" }
$candidate = Join-RemotePath $monthFolder $folderName
if (-not (Test-RemoteExists -Client $Client -Config $Config -RemotePath $candidate)) {
Ensure-RemoteFolder -Client $Client -Config $Config -RemoteFolder $candidate
return $candidate
}
}
throw 'Für die Mehrfachauswahl konnte kein eindeutiger Nextcloud-Zielordner erzeugt werden.'
}
function Get-RemotePathForLocalItem {
param(
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$LocalPath
)
$localRoot = if ($Config.PSObject.Properties.Name -contains 'LocalNextcloudRoot') {
[string]$Config.LocalNextcloudRoot
}
else { '' }
if ([string]::IsNullOrWhiteSpace($localRoot) -or
-not (Test-Path -LiteralPath $localRoot -PathType Container)) {
return $null
}
$root = [IO.Path]::GetFullPath($localRoot).TrimEnd('\')
$full = [IO.Path]::GetFullPath($LocalPath)
if ($full.Equals($root, [StringComparison]::OrdinalIgnoreCase)) { return [string]$Config.RemoteSyncRoot }
if (-not $full.StartsWith($root + '\', [StringComparison]::OrdinalIgnoreCase)) { return $null }
$relative = $full.Substring($root.Length).TrimStart('\').Replace('\', '/')
return Join-RemotePath ([string]$Config.RemoteSyncRoot) $relative
}
function Get-UniqueRemoteUploadPath {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$FileName
)
$folder = Join-RemotePath ([string]$Config.RemoteUploadFolder) (Get-Date -Format 'yyyy-MM')
Ensure-RemoteFolder -Client $Client -Config $Config -RemoteFolder $folder
$candidate = Join-RemotePath $folder $FileName
if (-not (Test-RemoteExists -Client $Client -Config $Config -RemotePath $candidate)) { return $candidate }
$base = [IO.Path]::GetFileNameWithoutExtension($FileName)
$extension = [IO.Path]::GetExtension($FileName)
return Join-RemotePath $folder ("{0}-{1}{2}" -f $base, (Get-Date -Format 'yyyyMMdd-HHmmss'), $extension)
}
function Send-FileToNextcloud {
param(
[Parameter(Mandatory = $true)][System.Net.Http.HttpClient]$Client,
[Parameter(Mandatory = $true)]$Config,
[Parameter(Mandatory = $true)][string]$LocalPath,
[Parameter(Mandatory = $true)][string]$RemotePath
)
$stream = [IO.File]::OpenRead($LocalPath)
try {
$content = [System.Net.Http.StreamContent]::new($stream)
$content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::new('application/octet-stream')
$response = Invoke-HttpRequest -Client $Client -Method 'PUT' -Uri (Get-WebDavUri $Config $RemotePath) -Content $content
if (-not $response.IsSuccess) {
throw (Get-NextcloudShareText 'UploadFailed' -FormatArgs @(Get-HttpErrorText $response))
}
}
finally {
$stream.Dispose()
}
}
function Get-OcsUri {
param([Parameter(Mandatory = $true)]$Config, [Parameter(Mandatory = $true)][string]$Relative)
return $Config.ServerUrl.TrimEnd('/') + '/ocs/v2.php/' + $Relative.TrimStart('/')
}