-
Notifications
You must be signed in to change notification settings - Fork 44
/
Client.cs
2570 lines (2208 loc) · 90.1 KB
/
Client.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Text.Json;
using System.Xml.Linq;
using WebDAVClient.Exceptions;
using WebDAVClient.Types;
using DecaTec.WebDav;
using DecaTec.WebDav.WebDavArtifacts;
using WebDAVClient.WebDav;
using WebDAVClient.Extensions;
using DecaTec.WebDav.Tools;
using System.Net.Http;
using System.Net;
using DecaTec.WebDav.Headers;
using System.Globalization;
using System.Net.Http.Headers;
//fork from https://github.com/nextcloud/windows-universal
namespace WebDAVClient
{
/// <summary>
/// Nextcloud OCS and DAV access client
/// </summary>
public class Client : IDisposable
{
#region PRIVATE PROPERTIES
/// <summary>
/// WebDavNet instance.
/// </summary>
private readonly WebDavSession _dav;
/// <summary>
/// Server Base URL.
/// </summary>
private readonly string _url;
/// <summary>
/// The client
/// </summary>
private readonly HttpClient _client;
/// <summary>
/// The HTTP handler
/// </summary>
private readonly HttpClientHandler _httpClientHandler;
/// <summary>
/// Nextcloud WebDAV access path.
/// </summary>
private const string Davpath = "remote.php/webdav";
/// <summary>
/// Nextcloud OCS API access path.
/// </summary>
private const string Ocspath = "ocs/v1.php";
/// <summary>
/// OCS Share API path.
/// </summary>
private const string OcsServiceShare = "apps/files_sharing/api/v1";
private const string OcsServiceData = "privatedata";
/// <summary>
/// OCS Provisioning API path.
/// </summary>
private const string OcsServiceCloud = "cloud";
private readonly PropFind _webDAVPropFind;
private readonly Version HttpVersion = new Version(2, 0);
/// <summary>
/// JSON serializer settings.
/// </summary>
private static JsonSerializerOptions _jsonSettings = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
#endregion
#region CONSTRUCTORS
/// <summary>
/// Initializes a new instance of the <see cref="Client" /> class.
/// </summary>
/// <param name="url">WebDAV instance URL.</param>
/// <param name="userId">User identifier.</param>
/// <param name="password">Password.</param>
public Client(string url, string userId, string password, bool ignoreServerCertificateErrors = false)
: this(url, new NetworkCredential(userId, password), ignoreServerCertificateErrors)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebDAVClient"/> class.
/// </summary>
/// <param name="url">Nextcloud instance URL.</param>
/// <param name="httpClientHandler">The HTTP base protocol filter.</param>
public Client(string url, NetworkCredential passwordCredential, bool ignoreServerCertificateErrors = false)
{
if (url == null)
{
return;
}
// In case URL has a trailing slash remove it
if (url.EndsWith("/", StringComparison.InvariantCulture))
{
url = url.TrimEnd('/');
}
// Create PropFind which contains all NC specific properties.
PropFind propFind = PropFind.CreatePropFindWithEmptyPropertiesAll();
Prop prop = (Prop)propFind.Item;
XNamespace nsOc = "http://owncloud.org/ns";
List<XElement> xElementList = new List<XElement>();
XElement xElement = new XElement(nsOc + WebDAVPropNameConstants.Checksums);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.CommentsCount);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.CommentsHref);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.CommentsUnread);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.Favorite);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.FileId);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.HasPreview);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.Id);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.OwnerDisplayName);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.OwnerId);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.ShareTypes);
xElementList.Add(xElement);
xElement = new XElement(nsOc + WebDAVPropNameConstants.Size);
xElementList.Add(xElement);
prop.AdditionalProperties = xElementList.ToArray();
_webDAVPropFind = propFind;
_url = url;
_httpClientHandler = new HttpClientHandler()
{
PreAuthenticate = true,
ClientCertificateOptions = ClientCertificateOption.Automatic,
// Specify the user credentials.
Credentials = passwordCredential
};
_httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (ignoreServerCertificateErrors)
{
IgnoreServerCertificateErrors = true;
// Specify which certificate errors should be ignored.
//TODO check if other errors should be ignored
return errors == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
{
switch (errors)
{
case System.Net.Security.SslPolicyErrors.None:
return true;
case System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors:
case System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch:
case System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable:
default:
return false;
}
}
};
_client = new HttpClient(_httpClientHandler);
_client.DefaultRequestHeaders.Add("Pragma", "no-cache");
string encoded =
Convert.ToBase64String(
Encoding.GetEncoding("ISO-8859-1").GetBytes(
passwordCredential.UserName + ":" +
passwordCredential.Password
));
_client.BaseAddress = new Uri(_url);
//_client.DefaultRequestHeaders.Add("OCS-APIRequest", "true");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
_dav = new WebDavSession(_url, _httpClientHandler, HttpVersion)
{
Timeout = Timeout.InfiniteTimeSpan
};
}
#endregion
#region Settings
/// <summary>
/// Gets or sets a value indicating whether to ignore server certificate errors.
/// Be careful, setting this to <c>true</c> will allow MITM attacks!
/// </summary>
/// <value>
/// <c>true</c> if server certificate errors are ignored; otherwise, <c>false</c>.
/// </value>
public bool IgnoreServerCertificateErrors
{
get;
set;
}
#endregion
#region DAV
/// <summary>
/// List the specified remote path.
/// </summary>
/// <param name="path">remote Path.</param>
/// <returns>List of Resources.</returns>
public async Task<List<ResourceInfoModel>> List(string path)
{
List<ResourceInfoModel> resources = new List<ResourceInfoModel>();
IList<WebDavSessionItem> result = await _dav.ListAsync(GetDavUri(path), _webDAVPropFind);
Uri baseUri = new Uri(_url);
baseUri = new Uri(baseUri, baseUri.AbsolutePath + (baseUri.AbsolutePath.EndsWith("/") ? "" : "/") + Davpath);
foreach (WebDavSessionItem item in result)
{
ResourceInfoModel res = item.ToResourceInfo(baseUri);
if (!res.IsDirectory)
{
// if resource not a directory, remove the file name from remote path.
res.Path = res.Path.Replace("/" + res.Name, "");
}
resources.Add(res);
}
return resources;
}
/// <summary>
/// Gets the resource info for the remote path.
/// </summary>
/// <returns>The resource info.</returns>
/// <param name="path">remote Path.</param>
/// <param name="name">name of resource to get</param>
public async Task<ResourceInfoModel> GetResourceInfoAsync(string path, string name)
{
Uri baseUri = new Uri(_url);
baseUri = new Uri(baseUri, baseUri.AbsolutePath + (baseUri.AbsolutePath.EndsWith("/") ? "" : "/") + Davpath);
var temp = await _dav.ListAsync(GetDavUri(path), _webDAVPropFind);
IList<WebDavSessionItem> result = await _dav.ListAsync(GetDavUri(path), _webDAVPropFind);
if (!result.Any())
{
return null;
}
foreach (WebDavSessionItem item in result)
{
if (item.Name.Equals(name, StringComparison.Ordinal))
{
ResourceInfoModel res = item.ToResourceInfo(baseUri);
if (!res.IsDirectory)
{
// if resource not a directory, remove the file name from remote path.
res.Path = res.Path.Replace("/" + res.Name, "");
}
return res;
}
}
return null;
}
/// <summary>
/// Finds remote outgoing shares.
/// </summary>
/// <returns>List of shares.</returns>
public async Task<List<ResourceInfoModel>> GetSharesView(string viewname)
{
Tuple<string, string> param = new Tuple<string, string>("shared_with_me", "false");
if (viewname == "sharesIn")
{
param = new Tuple<string, string>("shared_with_me", "true");
}
List<Share> shares = await GetShares(param);
List<ResourceInfoModel> sharesList = new List<ResourceInfoModel>();
foreach (Share item in shares)
{
if (viewname == "sharesLink")
{
string type = item.GetType().ToString();
if (type != "NextcloudClient.Types.PublicShare")
{
continue;
}
ResourceInfoModel itemShare = await GetResourceInfoByPath(item.Path);
sharesList.Add(itemShare);
}
else
{
ResourceInfoModel itemShare = await GetResourceInfoByPath(item.Path);
sharesList.Add(itemShare);
}
}
return sharesList;
}
/// <summary>
/// Finds user favorites.
/// </summary>
/// <returns>List of favorites.</returns>
public async Task<List<ResourceInfoModel>> GetFavorites()
{
UrlBuilder url = new UrlBuilder(_url + "/remote.php/webdav");
// See: https://docs.nextcloud.com/server/12/developer_manual/client_apis/WebDAV/index.html#listing-favorites
// Also, for Props see: https://docs.nextcloud.com/server/12/developer_manual/client_apis/WebDAV/index.html
const string content = "<?xml version=\"1.0\"?>"
+ "<oc:filter-files xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">"
+ "<d:prop>"
+ "<oc:favorite />"
+ "</d:prop>"
+ "<oc:filter-rules>"
+ "<oc:favorite>1</oc:favorite>"
+ "</oc:filter-rules>"
+ "</oc:filter-files>";
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("REPORT"), url.ToUri())
{
Content = new StringContent(content, UnicodeEncoding.UTF8, "application/xml")
};
HttpResponseMessage response = await _client.SendAsync(request);
string contentString = await response.Content.ReadAsStringAsync();
Multistatus multistatus = WebDavResponseContentParser.ParseMultistatusResponseContentString(contentString);
List<ResourceInfoModel> favoritesList = new List<ResourceInfoModel>();
if (multistatus.Response != null)
{
foreach (Response msResponse in multistatus.Response)
{
foreach (object item in msResponse.Items)
{
string href = item as string;
if (string.IsNullOrEmpty(href) || !href.Contains(Davpath))
{
continue;
}
href = href.TrimEnd('/');
href = href.Replace("/remote.php/webdav", "");
ResourceInfoModel itemFav = await GetResourceInfoByPath(href);
favoritesList.Add(itemFav);
}
}
}
return favoritesList;
}
/// <summary>
/// Finds resource info for item by searching its parent.
/// </summary>
/// <returns>Resource Info if given item.</returns>
/// <param name="path">Path to the Item.</param>
private async Task<ResourceInfoModel> GetResourceInfoByPath(string path)
{
path = Uri.UnescapeDataString(path);
string targetPath = "/" + path.Split('/')[path.Split('/').Length - 1];
string parentPath = path.Replace(targetPath, "/");
string itemName = targetPath.Replace("/", "");
List<ResourceInfoModel> parentResource = await List(parentPath);
ResourceInfoModel itemResource = new ResourceInfoModel();
foreach (ResourceInfoModel item in parentResource)
{
if (item.Name == itemName)
{
itemResource = item;
}
}
return itemResource;
}
/// <summary>
/// Download the specified file.
/// </summary>
/// <param name="path">File remote Path.</param>
/// <param name="localStream"></param>
/// <param name="cancellationToken"></param>
/// <param name="progress"></param>
/// <returns>File contents.</returns>
public Task<bool> Download(string path, Stream localStream, IProgress<WebDavProgress> progress, CancellationToken cancellationToken)
{
return _dav.DownloadFileWithProgressAsync(GetDavUri(path, true), localStream, progress, cancellationToken);
}
public async Task<Stream> GetImage(ResourceInfoModel file)
{
if (!file.ContentType.StartsWith(@"image/", StringComparison.InvariantCulture))
{
return null;
}
Uri uri = new Uri(GetDavUri(file.Path, true) + "/" + Uri.EscapeDataString(file.Name));
_client.DefaultRequestHeaders.Add("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
HttpResponseMessage response = await _client.GetAsync(uri);
_client.DefaultRequestHeaders.Remove("Cookie");
if (response != null)
{
return await response.Content.ReadAsStreamAsync();
}
// TODO: Errorhandling
Debug.WriteLine("Empty WebResponse @'GetImage'" + Environment.NewLine + uri);
return null;
}
/// <summary>
/// Upload the specified file to the specified path.
/// </summary>
/// <param name="path">remote Path.</param>
/// <param name="stream"></param>
/// <param name="contentType">File content type.</param>
/// <param name="cancellationToken"></param>
/// <returns><c>true</c>, if upload successful, <c>false</c> otherwise.</returns>
public async Task<bool> UploadAsync(
string path,
Stream stream,
string contentType,
CancellationToken cancellationToken,
List<(string Key, string Value)> headerKeyValuePair)
{
var streamContent = new StreamContent(stream); //stream.Length
if (!string.IsNullOrEmpty(contentType))
streamContent.Headers.Add(HttpHeaderNames.ContentType, contentType);
streamContent.Headers.Add(HttpHeaderNames.ContentLength, stream.Length.ToString(CultureInfo.InvariantCulture));
for (int i = 0; i < headerKeyValuePair.Count; i++)
{
streamContent.Headers.Add(headerKeyValuePair[i].Key, headerKeyValuePair[i].Value);
}
var requestMethod = new HttpRequestMessage(HttpMethod.Put, GetDavUri(path, true))
{
Content = streamContent
};
requestMethod.Version = HttpVersion;
var result = await _client.SendAsync(requestMethod, cancellationToken);
return result.IsSuccessStatusCode;
}
/// <summary>
/// Upload the specified file to the specified path.
/// </summary>
/// <param name="path">remote Path.</param>
/// <param name="stream"></param>
/// <param name="contentType">File content type.</param>
/// <param name="cancellationToken"></param>
/// <param name="progress"></param>
/// <returns><c>true</c>, if upload successful, <c>false</c> otherwise.</returns>
//public async Task<bool> UploadAsync(
// string path,
// Stream stream,
// string contentType,
// CancellationToken cancellationToken,
// IProgress<WebDavProgress> progress,
// List<(string Key, string Value)> headerKeyValuePair)
//{
// var streamContent = new WebDavProgressStreamContent(stream, stream.Length, cancellationToken, progress);
// if (!string.IsNullOrEmpty(contentType))
// streamContent.Headers.Add(HttpHeaderNames.ContentType, contentType);
// streamContent.Headers.Add(HttpHeaderNames.ContentLength, stream.Length.ToString(CultureInfo.InvariantCulture));
// for (int i = 0; i < headerKeyValuePair.Count; i++)
// {
// streamContent.Headers.Add(headerKeyValuePair[i].Key, headerKeyValuePair[i].Value);
// }
// //if (lockToken != null)
// // streamContent.Headers.Add(WebDavRequestHeader.If, lockToken.IfHeaderNoTagListFormat.ToString());
// var requestMethod = new HttpRequestMessage(HttpMethod.Put, GetDavUri(path, true))
// {
// Content = streamContent
// };
// requestMethod.Version = HttpVersion;
// var result = await _client.SendAsync(requestMethod, cancellationToken);
// return result.IsSuccessStatusCode;
// //return _client.SendAsync(requestMethod, cancellationToken);
// //return _dav.UploadFileWithProgressAsync(GetDavUri(path, true), stream, contentType, progress, cancellationToken);
// //return _dav.UploadFileAsync(GetDavUri(path, true), stream, contentType, progress, cancellationToken, headerKeyValuePair);
//}
/// <summary>
/// Checks if the specified remote path exists.
/// </summary>
/// <param name="path">remote Path.</param>
/// <param name="fullPath">combine the full path of the server.</param>
/// <returns><c>true</c>, if remote path exists, <c>false</c> otherwise.</returns>
public Task<bool> ExistsAsync(string path, bool fullPath = false)
{
return _dav.ExistsAsync(GetDavUri(path));
}
/// <summary>
/// Creates a new directory at remote path.
/// </summary>
/// <returns><c>true</c>, if directory was created, <c>false</c> otherwise.</returns>
/// <param name="path">remote Path.</param>
public Task<bool> CreateDirectory(string path)
{
return _dav.CreateDirectoryAsync(GetDavUri(path));
}
/// <summary>
/// Delete resource at the specified remote path.
/// </summary>
/// <param name="path">remote Path.</param>
/// <returns><c>true</c>, if resource was deleted, <c>false</c> otherwise.</returns>
public Task<bool> Delete(string path)
{
return _dav.DeleteAsync(GetDavUri(path));
}
/// <summary>
/// Copy the specified source to destination.
/// </summary>
/// <param name="source">Source resoure path.</param>
/// <param name="destination">Destination resource path.</param>
/// <returns><c>true</c>, if resource was copied, <c>false</c> otherwise.</returns>
public Task<bool> Copy(string source, string destination)
{
return _dav.CopyAsync(GetDavUri(source), GetDavUri(destination));
}
/// <summary>
/// Move the specified source and destination.
/// </summary>
/// <param name="source">Source resource path.</param>
/// <param name="destination">Destination resource path.</param>
/// <returns><c>true</c>, if resource was moved, <c>false</c> otherwise.</returns>
public Task<bool> Move(string source, string destination)
{
return _dav.MoveAsync(GetDavUri(source), GetDavUri(destination));
}
/// <summary>
/// Downloads a remote directory as zip.
/// </summary>
/// <param name="path">File remote Path.</param>
/// <param name="localStream"></param>
/// <param name="cancellationToken"></param>
/// <param name="progress"></param>
/// <returns>File contents.</returns>
public Task<bool> DownloadDirectoryAsZip(string path, Stream localStream, IProgress<WebDavProgress> progress, CancellationToken cancellationToken)
{
return _dav.DownloadFileWithProgressAsync(GetDavUriZip(path), localStream, progress, cancellationToken);
}
public async Task<bool> ToggleFavorite(ResourceInfoModel res)
{
string path = GetParentPath(res);
IList<WebDavSessionItem> items = await _dav.ListAsync(GetDavUri(path), _webDAVPropFind);
WebDavSessionItem item = items.FirstOrDefault(x => x.Name == res.Name);
if (item == null)
{
return false;
}
string favString = item.AdditionalProperties[WebDAVPropNameConstants.Favorite];
if (string.IsNullOrEmpty(favString) || string.CompareOrdinal(favString, "0") == 0)
{
item.AdditionalProperties[WebDAVPropNameConstants.Favorite] = "1";
}
else
{
item.AdditionalProperties[WebDAVPropNameConstants.Favorite] = "0";
}
return await _dav.UpdateItemAsync(item);
}
private static string GetParentPath(ResourceInfoModel resourceInfo)
{
string path = resourceInfo.Path.TrimEnd('/');
string[] split = path.Split('/');
if (resourceInfo.IsDirectory)
{
path = string.Empty;
for (int i = 1; i < split.Length - 1; i++)
{
path += "/" + split[i];
}
//path = "/" + split[split.Length - 2];
}
//else
// path = "/" + split[split.Length - 1];
return path;
}
#endregion
#region WebDAV
#region Remote Shares
/// <summary>
/// Gets the server status.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="ignoreServerCertificateErrors">if set to <c>true</c> [ignore server certificate errors].</param>
/// <returns></returns>
/// <exception cref="ResponseError">The certificate authority is invalid or incorrect
/// or
/// The remote server returned an error: (401) Unauthorized. - 401
/// or</exception>
public static async Task<Status> GetServerStatus(string serverUrl, bool ignoreServerCertificateErrors = false)
{
serverUrl = serverUrl.TrimEnd('/');
if (serverUrl.EndsWith("owncloud") || serverUrl.EndsWith("nextcloud") || serverUrl.EndsWith("ownCloud"))
{
serverUrl += "/status.php";
}
else if (serverUrl.EndsWith("remote.php/webdav"))
{
serverUrl = serverUrl.Replace("remote.php/webdav", "status.php");
}
else
{
serverUrl += "/status.php";
}
string url;
if (Uri.IsWellFormedUriString(serverUrl, UriKind.Absolute))
{
url = serverUrl;
}
else
{
return null;
}
HttpClientHandler httpClientHandler = new HttpClientHandler
{
AllowAutoRedirect = false
};
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (ignoreServerCertificateErrors)
{
// Specify which certificate errors should be ignored.
if (errors == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
{
return true;
}
else
{
return false;
}
}
else
{
switch (errors)
{
case System.Net.Security.SslPolicyErrors.None:
return true;
case System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors:
case System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch:
case System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable:
default:
return false;
}
}
};
HttpClient client = new HttpClient(httpClientHandler);
client.DefaultRequestHeaders.Add("Pragma", "no-cache");
HttpResponseMessage response = null;
try
{
response = await client.GetAsync(url);
}
catch (Exception e)
{
if (e.Message.Contains("The certificate authority is invalid or incorrect"))
{
throw new ResponseError("The certificate authority is invalid or incorrect");
}
}
if (response == null)
{
return null;
}
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new ResponseError("The remote server returned an error: (401) Unauthorized.", "401");
}
string content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(content))
{
throw new ResponseError(response.ReasonPhrase);
}
try
{
return JsonSerializer.Deserialize<Status>(content, _jsonSettings);
}
catch
{
return null;
}
}
/// <summary>
/// Checks the user login.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="userId">The user identifier.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
public static Task<bool> CheckUserLogin(string serverUrl, string userId, string password)
{
return CheckUserLogin(serverUrl, userId, password, false);
}
/// <summary>
/// Checks the user login.
/// </summary>
/// <param name="serverUrl">The server URL.</param>
/// <param name="userId">The user identifier.</param>
/// <param name="password">The password.</param>
/// <param name="ignoreServerCertificateErrors">if set to <c>true</c> [ignore server certificate errors].</param>
/// <returns></returns>
public static async Task<bool> CheckUserLogin(string serverUrl, string userId, string password, bool ignoreServerCertificateErrors)
{
if (string.IsNullOrEmpty(serverUrl) || string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(password))
{
return false;
}
// This method is also called on app reset.
// Only using a HEAD request doesn't seem to work, because in subsequent calls (with wrong user/password), the server always returns HTTP 200 (OK).
// So we're using an API call here.
if (!serverUrl.EndsWith("/"))
{
serverUrl += "/";
}
Client client = new Client(serverUrl, userId, password, ignoreServerCertificateErrors);
User user = null;
try
{
user = await client.GetUserAttributes(userId);
}
catch(Exception ex)
{
// ignored
}
return user != null;
}
/// <summary>
/// List all remote shares.
/// </summary>
/// <returns>List of remote shares.</returns>
public async Task<object> ListOpenRemoteShare()
{
string response = await DoApiRequest(
"GET",
"/" + GetOcsPath(OcsServiceShare, "remote_shares")
);
//Debug.Assert(response.StatusCode == HttpStatusCode.OK);
// TODO: Parse response
return response;
}
/// <summary>
/// List all remote shares.
/// </summary>
/// <returns>List of remote shares.</returns>
public async Task<object> ListShare()
{
string response = await DoApiRequest(
"GET",
"/" + GetOcsPath(OcsServiceShare, "shares")
);
//Debug.Assert(response.StatusCode == HttpStatusCode.OK);
// TODO: Parse response
return response;
}
/// <summary>
/// Accepts a remote share
/// </summary>
/// <returns><c>true</c>, if remote share was accepted, <c>false</c> otherwise.</returns>
/// <param name="shareId">Share identifier.</param>
public async Task<bool> AcceptRemoteShare(int shareId)
{
string response = await DoApiRequest(
"POST",
"/" + GetOcsPath(OcsServiceShare, "remote_shares") + "/" + shareId
);
OCS responseObj = JsonSerializer.Deserialize<OCS>(response, _jsonSettings);
if (responseObj == null)
{
return false;
}
if (responseObj.Meta.StatusCode == 100)
{
return true;
}
throw new OcsResponseError(responseObj.Meta.Message, responseObj.Meta.StatusCode.ToString());
}
/// <summary>
/// Declines a remote share.
/// </summary>
/// <returns><c>true</c>, if remote share was declined, <c>false</c> otherwise.</returns>
/// <param name="shareId">Share identifier.</param>
public async Task<bool> DeclineRemoteShare(int shareId)
{
string response = await DoApiRequest(
"DELETE",
"/" + GetOcsPath(OcsServiceShare, "remote_shares") + "/" + shareId
);
OCS responseObj =
JsonSerializer.Deserialize<OCS>(response, _jsonSettings);
if (responseObj == null)
{
return false;
}
if (responseObj.Meta.StatusCode == 100)
{
return true;
}
throw new OcsResponseError(responseObj.Meta.Message, responseObj.Meta.StatusCode.ToString());
}
#endregion
#region Shares
/// <summary>
/// Unshares a file or directory.
/// </summary>
/// <returns><c>true</c>, if share was deleted, <c>false</c> otherwise.</returns>
/// <param name="shareId">Share identifier.</param>
public async Task<bool> DeleteShare(int shareId)
{
string response = await DoApiRequest(
"DELETE",
"/" + GetOcsPath(OcsServiceShare, "remote_shares") + "/" + shareId
);
OCS responseObj =
JsonSerializer.Deserialize<OCS>(response, _jsonSettings);
if (responseObj == null)
{
return false;
}
if (responseObj.Meta.StatusCode == 100)
{
return true;
}
throw new OcsResponseError(responseObj.Meta.Message, responseObj.Meta.StatusCode.ToString());
}
/// <summary>
/// Updates a given share. NOTE: Only one of the update parameters can be specified at once.
/// </summary>
/// <returns><c>true</c>, if share was updated, <c>false</c> otherwise.</returns>
/// <param name="shareId">Share identifier.</param>
/// <param name="perms">(optional) update permissions.</param>
/// <param name="password">(optional) updated password for public link Share.</param>
/// <param name="publicUpload">(optional) If set to <c>true</c> enables public upload for public shares.</param>
public async Task<bool> UpdateShare(int shareId, int perms = -1, string password = null,
OcsBoolParam publicUpload = OcsBoolParam.None)
{
if ((perms == Convert.ToInt32(OcsPermission.None)) && (password == null) &&
(publicUpload == OcsBoolParam.None))
{
return false;
}
//var parameters = new List<KeyValuePair<string, string>>();
Dictionary<string, string> parameters = new Dictionary<string, string>();
if (perms != Convert.ToInt32(OcsPermission.None))
{
parameters.Add("permissions", Convert.ToInt32(perms).ToString());
}
if (password != null)
{
parameters.Add("password", password);
}
switch (publicUpload)
{
case OcsBoolParam.True:
parameters.Add("publicUpload", "true");
break;
case OcsBoolParam.False:
parameters.Add("publicUpload", "false");
break;
case OcsBoolParam.None:
break;
default:
throw new ArgumentOutOfRangeException(nameof(publicUpload), publicUpload, null);
}
string response = await DoApiRequest(
"PUT",
"/" + GetOcsPath(OcsServiceShare, "shares") + "/" + shareId,
parameters
);
OCS responseObj =
JsonSerializer.Deserialize<OCS>(response, _jsonSettings);
if (responseObj == null)
{
return false;
}
if (responseObj.Meta.StatusCode == 100)
{
return true;
}
throw new OcsResponseError(responseObj.Meta.Message, responseObj.Meta.StatusCode.ToString());
}
/// <summary>
/// Unlocks a file or directory at the URL specified.
/// </summary>
/// <param name="url">The URL of the file or directory to unlock.</param>
/// <returns>The <see cref="Task"/> representing the asynchronous operation.</returns>
public Task<bool> UnlockAsync(string url)
{
return _dav.UnlockAsync(GetDavUri(url, true));
}