Tranga-Website/Tranga/TrangaTask.cs

153 lines
5.8 KiB
C#
Raw Normal View History

using System.Text.Json.Serialization;
using Logging;
2023-05-31 22:32:37 +02:00
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Tranga.TrangaTasks;
using JsonConverter = Newtonsoft.Json.JsonConverter;
namespace Tranga;
2023-05-18 21:08:09 +02:00
/// <summary>
2023-05-31 21:44:16 +02:00
/// Stores information on Task, when implementing new Tasks also update the serializer
/// </summary>
[JsonDerivedType(typeof(MonitorPublicationTask), 2)]
[JsonDerivedType(typeof(UpdateLibrariesTask), 3)]
[JsonDerivedType(typeof(DownloadChapterTask), 4)]
public abstract class TrangaTask
{
// ReSharper disable once CommentTypo ...Tell me why!
2023-05-20 01:06:12 +02:00
// ReSharper disable once MemberCanBePrivate.Global I want it thaaat way
public TimeSpan reoccurrence { get; }
public DateTime lastExecuted { get; set; }
[Newtonsoft.Json.JsonIgnore] public ExecutionState state { get; set; }
public Task task { get; }
public string taskId { get; }
[Newtonsoft.Json.JsonIgnore] public TrangaTask? parentTask { get; set; }
public string? parentTaskId { get; set; }
[Newtonsoft.Json.JsonIgnore] protected HashSet<TrangaTask> childTasks { get; }
[Newtonsoft.Json.JsonIgnore] public double progress => GetProgress();
2023-06-07 00:27:53 +02:00
[Newtonsoft.Json.JsonIgnore]public DateTime executionStarted { get; private set; }
[Newtonsoft.Json.JsonIgnore]public DateTime lastChange { get; private set; }
[Newtonsoft.Json.JsonIgnore]public DateTime executionApproximatelyFinished => progress != 0 ? lastChange.Add(GetRemainingTime()) : DateTime.MaxValue;
[Newtonsoft.Json.JsonIgnore]public TimeSpan executionApproximatelyRemaining => executionApproximatelyFinished.Subtract(DateTime.Now);
[Newtonsoft.Json.JsonIgnore]public DateTime nextExecution => lastExecuted.Add(reoccurrence);
public enum ExecutionState { Waiting, Enqueued, Running, Failed }
protected TrangaTask(Task task, TimeSpan reoccurrence, TrangaTask? parentTask = null)
{
2023-05-18 21:08:09 +02:00
this.reoccurrence = reoccurrence;
this.lastExecuted = DateTime.Now.Subtract(reoccurrence);
this.task = task;
this.executionStarted = DateTime.UnixEpoch;
this.lastChange = DateTime.MaxValue;
this.taskId = Convert.ToBase64String(BitConverter.GetBytes(new Random().Next()));
this.childTasks = new();
this.parentTask = parentTask;
this.parentTaskId = parentTask?.taskId;
}
/// <summary>
/// BL for concrete Tasks
/// </summary>
/// <param name="taskManager"></param>
2023-05-31 22:32:37 +02:00
/// <param name="logger"></param>
/// <param name="cancellationToken"></param>
protected abstract bool ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null);
public abstract TrangaTask Clone();
protected abstract double GetProgress();
/// <summary>
/// Execute the task
/// </summary>
/// <param name="taskManager">Should be the parent taskManager</param>
/// <param name="logger"></param>
/// <param name="cancellationToken"></param>
public void Execute(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
2023-05-31 22:32:37 +02:00
{
logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
this.state = ExecutionState.Running;
this.executionStarted = DateTime.Now;
this.lastChange = DateTime.Now;
bool success = ExecuteTask(taskManager, logger, cancellationToken);
while(childTasks.Any(ct => ct.state is ExecutionState.Enqueued or ExecutionState.Running))
Thread.Sleep(1000);
if (success)
{
this.lastExecuted = DateTime.Now;
this.state = ExecutionState.Waiting;
}
else
{
this.lastExecuted = DateTime.MaxValue;
this.state = ExecutionState.Failed;
}
logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
2023-05-31 22:32:37 +02:00
}
public void AddChildTask(TrangaTask childTask)
{
this.childTasks.Add(childTask);
}
2023-06-15 18:22:59 +02:00
public void RemoveChildTask(TrangaTask childTask)
{
this.childTasks.Remove(childTask);
2023-05-31 22:32:37 +02:00
}
private TimeSpan GetRemainingTime()
{
if(progress == 0 || lastChange > executionStarted)
return DateTime.MaxValue.Subtract(DateTime.Now.AddYears(1));
TimeSpan elapsed = lastChange.Subtract(executionStarted);
return elapsed.Divide(progress).Subtract(elapsed);
}
2023-05-31 22:26:53 +02:00
public enum Task : byte
{
MonitorPublication = 2,
UpdateLibraries = 3,
DownloadChapter = 4,
DownloadNewChapters = 2 //legacy
}
2023-05-20 00:37:31 +02:00
public override string ToString()
{
return $"{task}, {lastExecuted}, {reoccurrence}, {state}, {progress:P2}, {executionApproximatelyFinished}, {executionApproximatelyRemaining}";
2023-05-20 00:37:31 +02:00
}
public class TrangaTaskJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TrangaTask);
}
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo["task"]!.Value<Int64>() == (Int64)Task.MonitorPublication)
return jo.ToObject<MonitorPublicationTask>(serializer)!;
if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateLibraries)
return jo.ToObject<UpdateLibrariesTask>(serializer)!;
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadChapter)
return jo.ToObject<DownloadChapterTask>(serializer)!;
throw new Exception();
}
public override bool CanWrite => false;
2023-05-31 21:44:16 +02:00
/// <summary>
/// Don't call this
/// </summary>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new Exception("Dont call this");
}
}
}