osu/osu.Game/Online/API/APIDownloadRequest.cs

52 lines
1.5 KiB
C#
Raw Normal View History

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
2018-04-13 09:19:50 +00:00
using System;
using System.IO;
2018-04-13 09:19:50 +00:00
using osu.Framework.IO.Network;
namespace osu.Game.Online.API
{
public abstract class APIDownloadRequest : APIRequest
{
private string filename;
/// <summary>
2019-06-13 11:25:41 +00:00
/// Used to set the extension of the file returned by this request.
/// </summary>
protected virtual string FileExtension { get; } = @".tmp";
protected APIDownloadRequest()
{
base.Success += () => Success?.Invoke(filename);
}
2018-04-13 09:19:50 +00:00
protected override WebRequest CreateWebRequest()
{
string file = Path.GetTempFileName();
File.Move(file, filename = Path.ChangeExtension(file, FileExtension));
var request = new FileWebRequest(filename, Uri);
2018-04-13 09:19:50 +00:00
request.DownloadProgress += request_Progress;
return request;
}
2019-01-31 10:08:45 +00:00
private void request_Progress(long current, long total) => API.Schedule(() => Progressed?.Invoke(current, total));
2018-04-13 09:19:50 +00:00
protected void TriggerSuccess(string filename)
2018-04-13 09:19:50 +00:00
{
if (this.filename != null)
throw new InvalidOperationException("Attempted to trigger success more than once");
this.filename = filename;
TriggerSuccess();
2018-04-13 09:19:50 +00:00
}
2019-01-31 10:08:45 +00:00
public event APIProgressHandler Progressed;
2018-04-13 09:19:50 +00:00
public new event APISuccessHandler<string> Success;
2018-04-13 09:19:50 +00:00
}
}