-
Notifications
You must be signed in to change notification settings - Fork 4
/
FetchYoutubeVideoCommand.cs
81 lines (69 loc) 路 2.91 KB
/
FetchYoutubeVideoCommand.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
锘縰sing System;
using System.Threading;
using System.Threading.Tasks;
using Ethereal.Application.Exceptions;
using Ethereal.Application.ProcessingJobLogger;
using Ethereal.Application.YouTube;
using Ethereal.Domain;
using Ethereal.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Ethereal.Application.Commands;
public class FetchYoutubeVideoCommand
{
private readonly IDatabaseSettings databaseSettings;
private readonly EtherealDbContext dbContext;
private readonly IEtherealSettings settings;
private readonly IYoutubeProvider youtubeProvider;
private bool isDownloaded;
public FetchYoutubeVideoCommand(EtherealDbContext dbContext, IYoutubeProvider youtubeProvider,
IEtherealSettings settings, IDatabaseSettings databaseSettings)
{
this.dbContext = dbContext;
this.youtubeProvider = youtubeProvider;
this.settings = settings;
this.databaseSettings = databaseSettings;
}
public async Task ExecuteAsync(Guid jobId)
{
var job = await dbContext.ProcessingJobs
.Include(j => j.Video)
.FirstOrDefaultAsync(j => j.Id == jobId);
if (job == null)
throw new NotFoundException();
job.Status = ProcessingJobStatus.Processing;
await dbContext.SaveChangesAsync();
await job.LogAsync("Fetching video from youtube...");
var cts = new CancellationTokenSource();
var timeoutDate = DateTime.UtcNow.Add(settings.DownloadingTimeout);
// todo: refactor this
var thread = new Thread(async () =>
{
while (true)
{
// Console.WriteLine(timeoutDate.ToLongTimeString() + " || " + DateTime.UtcNow.ToLongTimeString());
if (DateTime.UtcNow > timeoutDate)
{
// ReSharper disable once InconsistentNaming
await using var _dbContext = new EtherealDbContext(databaseSettings);
// ReSharper disable once MethodSupportsCancellation
// ReSharper disable once InconsistentNaming
var _job = await _dbContext.ProcessingJobs.FirstOrDefaultAsync(j => j.Id == job.Id);
_job.Status = ProcessingJobStatus.Failed;
// ReSharper disable once MethodSupportsCancellation
await _dbContext.SaveChangesAsync();
await _job.LogAsync("Could not fetch video from youtube. It happens sometimes. Try again.");
cts.Cancel();
return;
}
if (isDownloaded)
return;
// ReSharper disable once MethodSupportsCancellation
await Task.Delay(10);
}
});
thread.Start();
await youtubeProvider.DownloadAsync(job, cts);
isDownloaded = true;
await job.LogAsync("Video fetched successfully");
}
}