forked from files-community/Files
/
FtpHelpers.cs
69 lines (54 loc) · 2.01 KB
/
FtpHelpers.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
// Copyright (c) 2024 Files Community
// Licensed under the MIT License. See the LICENSE.
using Files.Shared.Extensions;
using FluentFTP;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Files.App.Storage.FtpStorage
{
internal static class FtpHelpers
{
public static string GetFtpPath(string path)
{
path = path.Replace("\\", "/", StringComparison.Ordinal);
var schemaIndex = path.IndexOf("://", StringComparison.Ordinal) + 3;
var hostIndex = path.IndexOf("/", schemaIndex, StringComparison.Ordinal);
return hostIndex == -1 ? "/" : path.Substring(hostIndex);
}
public static Task EnsureConnectedAsync(this AsyncFtpClient ftpClient, CancellationToken cancellationToken = default)
{
return ftpClient.IsConnected ? Task.CompletedTask : ftpClient.Connect(cancellationToken);
}
public static string GetFtpHost(string path)
{
var authority = GetFtpAuthority(path);
var index = authority.IndexOf(':', StringComparison.Ordinal);
return index == -1 ? authority : authority.Substring(0, index);
}
public static ushort GetFtpPort(string path)
{
var authority = GetFtpAuthority(path);
var index = authority.IndexOf(':', StringComparison.Ordinal);
if (index != -1)
return ushort.Parse(authority.Substring(index + 1));
return path.StartsWith("ftps://", StringComparison.OrdinalIgnoreCase) ? (ushort)990 : (ushort)21;
}
public static string GetFtpAuthority(string path)
{
path = path.Replace("\\", "/", StringComparison.Ordinal);
var schemaIndex = path.IndexOf("://", StringComparison.Ordinal) + 3;
var hostIndex = path.IndexOf("/", schemaIndex, StringComparison.Ordinal);
if (hostIndex == -1)
hostIndex = path.Length;
return path.Substring(schemaIndex, hostIndex - schemaIndex);
}
public static AsyncFtpClient GetFtpClient(string ftpPath)
{
var host = GetFtpHost(ftpPath);
var port = GetFtpPort(ftpPath);
var credentials = FtpManager.Credentials.Get(host, FtpManager.Anonymous);
return new(host, credentials, port);
}
}
}