Files
duplicati/Duplicati/Library/Backend/Mega/MegaBackend.cs
T

316 lines
13 KiB
C#
Raw Normal View History

// Copyright (C) 2026, The Duplicati Team
2025-02-17 16:45:51 +01:00
// https://duplicati.com, hello@duplicati.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2024-02-28 15:45:30 +01:00
// DEALINGS IN THE SOFTWARE.
using CG.Web.MegaApiClient;
2019-06-02 09:46:35 -07:00
using Duplicati.Library.Common.IO;
using Duplicati.Library.Interface;
2025-03-21 14:31:13 +01:00
using Duplicati.Library.Utility;
using Duplicati.Library.Utility.Options;
using OtpNet;
2025-02-17 16:45:51 +01:00
using System.Runtime.CompilerServices;
namespace Duplicati.Library.Backend.Mega
{
2019-06-02 09:46:35 -07:00
// ReSharper disable once UnusedMember.Global
// This class is instantiated dynamically in the BackendLoader.
public class MegaBackend : IBackend, IStreamingBackend, IRenameEnabledBackend
{
2025-03-21 14:31:13 +01:00
private readonly string m_username;
private readonly string m_password;
private readonly string? m_twoFactorKey;
private Dictionary<string, List<INode>>? m_filecache;
private INode? m_currentFolder = null;
private readonly string m_prefix;
private readonly TimeoutOptionsHelper.Timeouts m_timeouts;
2025-03-21 14:31:13 +01:00
private MegaApiClient? m_client;
public MegaBackend()
{
2025-03-21 14:31:13 +01:00
m_username = null!;
m_password = null!;
m_twoFactorKey = null;
m_prefix = null!;
m_timeouts = null!;
}
2025-03-21 14:31:13 +01:00
private async Task<MegaApiClient> GetClient(CancellationToken cancelToken)
{
2025-03-21 14:31:13 +01:00
if (m_client == null)
m_client = await Utility.Utility.WithTimeout(m_timeouts.ShortTimeout, cancelToken, async ct =>
{
var cl = new MegaApiClient();
if (m_twoFactorKey == null)
2025-03-21 14:31:13 +01:00
await cl.LoginAsync(m_username, m_password).ConfigureAwait(false);
else
{
var totp = new Totp(Base32Encoding.ToBytes(m_twoFactorKey)).ComputeTotp();
2025-03-21 14:31:13 +01:00
await cl.LoginAsync(m_username, m_password, totp).ConfigureAwait(false);
}
2025-03-21 14:31:13 +01:00
return cl;
}).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
return m_client;
}
2025-03-21 14:31:13 +01:00
public MegaBackend(string url, Dictionary<string, string?> options)
{
var uri = new Utility.Uri(url);
2025-03-21 14:31:13 +01:00
var auth = AuthOptionsHelper.Parse(options, uri);
if (options.ContainsKey("auth-two-factor-key"))
m_twoFactorKey = options["auth-two-factor-key"];
2025-03-28 15:57:46 +01:00
if (string.IsNullOrWhiteSpace(auth.Username))
throw new UserInformationException(Strings.MegaBackend.NoUsernameError, "MegaNoUsername");
2025-03-28 15:57:46 +01:00
if (string.IsNullOrWhiteSpace(auth.Password))
throw new UserInformationException(Strings.MegaBackend.NoPasswordError, "MegaNoPassword");
2025-03-21 14:31:13 +01:00
(m_username, m_password) = auth.GetCredentials();
m_prefix = uri.HostAndPath ?? "";
2025-03-21 14:31:13 +01:00
m_timeouts = TimeoutOptionsHelper.Parse(options);
}
2025-03-21 14:31:13 +01:00
private async Task<INode> FetchCurrentFolderAsync(bool autocreate, CancellationToken cancelToken)
{
2025-03-21 14:31:13 +01:00
var client = await GetClient(cancelToken).ConfigureAwait(false);
var parts = m_prefix.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
2025-03-21 14:31:13 +01:00
var nodes = await Utility.Utility.WithTimeout(m_timeouts.ListTimeout, cancelToken, _ => client.GetNodes()).ConfigureAwait(false);
INode parent = nodes.First(x => x.Type == NodeType.Root);
foreach (var n in parts)
{
var item = nodes.FirstOrDefault(x => x.Name == n && x.Type == NodeType.Directory && x.ParentId == parent.Id);
if (item == null)
{
if (!autocreate)
throw new FolderMissingException();
2025-03-21 14:31:13 +01:00
item = await client.CreateFolderAsync(n, parent).ConfigureAwait(false);
}
parent = item;
}
m_currentFolder = parent;
await ResetFileCacheAsync(nodes, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
return m_currentFolder;
}
private async Task<INode> GetCurrentFolderAsync(CancellationToken cancelToken)
{
2025-03-21 14:31:13 +01:00
var folder = m_currentFolder;
if (folder == null)
folder = await FetchCurrentFolderAsync(false, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
return folder;
}
private async Task<INode> GetFileNodeAsync(string name, CancellationToken cancelToken)
{
if (m_filecache != null && m_filecache.ContainsKey(name))
2017-08-23 11:48:15 +02:00
return m_filecache[name].OrderByDescending(x => x.ModificationDate).First();
await ResetFileCacheAsync(null, cancelToken).ConfigureAwait(false);
if (m_filecache != null && m_filecache.ContainsKey(name))
2017-08-23 11:48:15 +02:00
return m_filecache[name].OrderByDescending(x => x.ModificationDate).First();
throw new FileMissingException();
}
2025-03-21 14:31:13 +01:00
private async Task<Dictionary<string, List<INode>>> ResetFileCacheAsync(IEnumerable<INode>? list, CancellationToken cancelToken)
{
if (m_currentFolder == null)
{
await FetchCurrentFolderAsync(false, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
// We build it as part of the fetch step
return m_filecache!;
}
else
{
2025-03-21 14:31:13 +01:00
var client = await GetClient(cancelToken).ConfigureAwait(false);
var currentFolder = await GetCurrentFolderAsync(cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
if (list == null)
list = await Utility.Utility.WithTimeout(m_timeouts.ListTimeout, cancelToken, _ => client.GetNodes()).ConfigureAwait(false);
return m_filecache =
list.Where(x => x.Type == NodeType.File && x.ParentId == currentFolder.Id)
.GroupBy(x => x.Name, x => x, (k, g) => new KeyValuePair<string, List<INode>>(k, g.ToList()))
.ToDictionary(x => x.Key, x => x.Value);
}
}
#region IStreamingBackend implementation
2025-03-21 14:31:13 +01:00
public async Task PutAsync(string remotename, Stream stream, CancellationToken cancelToken)
{
try
{
2025-03-21 14:31:13 +01:00
var filecache = m_filecache;
if (filecache == null)
filecache = await ResetFileCacheAsync(null, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
var client = await GetClient(cancelToken).ConfigureAwait(false);
var currentFolder = await GetCurrentFolderAsync(cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
using var ts = stream.ObserveReadTimeout(m_timeouts.ReadWriteTimeout, false);
var el = await client.UploadAsync(ts, remotename, currentFolder, new Progress(), null, cancelToken).ConfigureAwait(false);
if (filecache.ContainsKey(remotename))
2024-09-29 23:04:54 +02:00
await DeleteAsync(remotename, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
filecache[remotename] = [el];
}
catch
{
m_filecache = null;
throw;
}
}
public async Task GetAsync(string remotename, System.IO.Stream stream, CancellationToken cancelToken)
{
2025-03-21 14:31:13 +01:00
var client = await GetClient(cancelToken).ConfigureAwait(false);
var node = await GetFileNodeAsync(remotename, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
using (var s = await Utility.Utility.WithTimeout(m_timeouts.ListTimeout, cancelToken, _ => client.Download(node)).ConfigureAwait(false))
using (var t = s.ObserveReadTimeout(m_timeouts.ReadWriteTimeout))
await Utility.Utility.CopyStreamAsync(t, stream, cancelToken).ConfigureAwait(false);
}
#endregion
#region IBackend implementation
2025-02-17 16:45:51 +01:00
/// <inheritdoc />
public async IAsyncEnumerable<IFileEntry> ListAsync([EnumeratorCancellation] CancellationToken cancelToken)
{
2025-03-21 14:31:13 +01:00
var filecache = m_filecache;
if (filecache == null)
filecache = await ResetFileCacheAsync(null, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
foreach (var n in filecache.Values)
2025-02-17 16:45:51 +01:00
{
var item = n.OrderByDescending(x => x.ModificationDate).First();
yield return new FileEntry(item.Name, item.Size, item.ModificationDate ?? new DateTime(0), item.ModificationDate ?? new DateTime(0));
}
}
2021-06-12 11:30:08 -07:00
public async Task PutAsync(string remotename, string filename, CancellationToken cancelToken)
{
using (var fs = System.IO.File.OpenRead(filename))
await PutAsync(remotename, fs, cancelToken).ConfigureAwait(false);
}
public async Task GetAsync(string remotename, string filename, CancellationToken cancelToken)
{
using (var fs = System.IO.File.Create(filename))
await GetAsync(remotename, fs, cancelToken).ConfigureAwait(false);
}
2024-09-29 23:04:54 +02:00
public async Task DeleteAsync(string remotename, CancellationToken cancelToken)
{
try
{
2025-03-21 14:31:13 +01:00
var filecache = m_filecache;
if (filecache == null || !filecache.ContainsKey(remotename))
filecache = await ResetFileCacheAsync(null, cancelToken).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
if (!filecache.ContainsKey(remotename))
throw new FileMissingException();
2025-03-21 14:31:13 +01:00
var client = await GetClient(cancelToken).ConfigureAwait(false);
foreach (var n in filecache[remotename])
await Utility.Utility.WithTimeout(m_timeouts.ListTimeout, cancelToken, _ => client.DeleteAsync(n, false)).ConfigureAwait(false);
2025-03-21 14:31:13 +01:00
filecache.Remove(remotename);
}
catch
{
m_filecache = null;
throw;
}
}
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
public Task TestAsync(CancellationToken cancelToken)
=> this.TestReadWritePermissionsAsync(cancelToken);
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
public Task CreateFolderAsync(CancellationToken cancelToken)
{
return FetchCurrentFolderAsync(true, cancelToken);
}
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
2025-03-21 14:31:13 +01:00
public string DisplayName => Strings.MegaBackend.DisplayName;
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
2025-03-21 14:31:13 +01:00
public string ProtocolKey => "mega";
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
2025-03-21 14:31:13 +01:00
public IList<ICommandLineArgument> SupportedCommands => [
.. AuthOptionsHelper.GetOptions(),
new CommandLineArgument("auth-two-factor-key", CommandLineArgument.ArgumentType.Password, Strings.MegaBackend.AuthTwoFactorKeyDescriptionShort, Strings.MegaBackend.AuthTwoFactorKeyDescriptionLong),
.. TimeoutOptionsHelper.GetOptions()
];
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
2025-03-21 14:31:13 +01:00
public string Description => Strings.MegaBackend.Description;
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
public bool SupportsStreaming => true;
/// <inheritdoc/>
2024-10-02 09:37:52 +02:00
public Task<string[]> GetDNSNamesAsync(CancellationToken cancelToken) => Task.FromResult(Array.Empty<string>());
public async Task RenameAsync(string oldname, string newname, CancellationToken cancellationToken)
{
var client = await GetClient(cancellationToken).ConfigureAwait(false);
var node = await GetFileNodeAsync(oldname, cancellationToken).ConfigureAwait(false);
await Utility.Utility.WithTimeout(m_timeouts.ShortTimeout, cancellationToken, _ => client.RenameAsync(node, newname)).ConfigureAwait(false);
// Update cache
if (m_filecache != null)
m_filecache.Remove(oldname);
}
#endregion
#region IDisposable implementation
2025-11-03 12:48:37 +01:00
/// <inheritdoc/>
public void Dispose()
{
}
#endregion
2019-03-17 22:14:00 -05:00
private class Progress : IProgress<double>
{
public void Report(double value)
{
// No implementation as we have already wrapped the stream in our own progress reporting stream
}
}
}
}