-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrailerTask.cs
More file actions
230 lines (201 loc) · 8.47 KB
/
TrailerTask.cs
File metadata and controls
230 lines (201 loc) · 8.47 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
using System.Text.Json;
using System.Text.Json.Nodes;
using Jellyfin.Data.Enums;
namespace TrailerFinPlugin
{
public class TrailerTask : IScheduledTask
{
private readonly ILibraryManager _libraryManager;
private readonly ILogger<TrailerTask> _logger;
private readonly HttpClient _httpClient;
private readonly MediaBrowser.Controller.MediaEncoding.IMediaEncoder _mediaEncoder;
private const string LogPath = @"C:\Users\pinae\Documents\TrailerFin_Log.txt";
private void LogToFile(string message)
{
try
{
File.AppendAllText(LogPath, $"{DateTime.Now}: {message}{Environment.NewLine}");
}
catch { /* Ignore logging errors */ }
}
public string Name => "Scan IMDb Trailers";
public string Key => "TrailerFinScan";
public string Description => "Scrapes IMDb for trailers and downloads trailer.mp4 via FFmpeg.";
public string Category => "Library";
public TrailerTask(ILibraryManager libraryManager, ILogger<TrailerTask> logger, MediaBrowser.Controller.MediaEncoding.IMediaEncoder mediaEncoder)
{
_libraryManager = libraryManager;
_logger = logger;
_mediaEncoder = mediaEncoder;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
_httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.9");
}
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
return Enumerable.Empty<TaskTriggerInfo>();
}
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
{
try
{
LogToFile("Starting TrailerFin Download Task...");
var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
{
IncludeItemTypes = new[] { BaseItemKind.Movie },
Recursive = true
});
if (itemIds == null || itemIds.Count == 0)
{
LogToFile("No movies found.");
return;
}
var total = itemIds.Count;
var current = 0;
foreach (var id in itemIds)
{
if (cancellationToken.IsCancellationRequested)
{
LogToFile("Scan cancelled.");
return;
}
var item = _libraryManager.GetItemById(id);
if (item is Movie movie)
{
if (movie.ProviderIds.TryGetValue("Imdb", out var imdbId) && !string.IsNullOrEmpty(imdbId))
{
await ProcessMovie(movie, imdbId);
}
}
current++;
progress.Report((double)current / total * 100);
}
LogToFile("TrailerFin Download Completed.");
}
catch (Exception ex)
{
LogToFile($"CRITICAL ERROR: {ex}");
_logger.LogError(ex, "Critical error in TrailerFin task.");
}
}
private async Task ProcessMovie(Movie movie, string imdbId)
{
try
{
var folderPath = movie.ContainingFolderPath;
if (string.IsNullOrEmpty(folderPath)) return;
// Standard Jellyfin local trailer naming
var trailerPath = Path.Combine(folderPath, "trailer.mp4");
// Skip if exists
if (File.Exists(trailerPath)) return;
LogToFile($"Downloading trailer for {movie.Name} [{imdbId}]");
var videoUrl = await GetImdbVideoUrl(imdbId);
if (string.IsNullOrEmpty(videoUrl))
{
LogToFile($"No trailer URL found for {movie.Name}");
return;
}
await DownloadTrailer(videoUrl, trailerPath);
}
catch (Exception ex)
{
LogToFile($"Error processing {movie.Name}: {ex.Message}");
}
}
private async Task DownloadTrailer(string url, string outputPath)
{
try
{
var ffmpegPath = _mediaEncoder.EncoderPath;
if (string.IsNullOrEmpty(ffmpegPath))
{
LogToFile("FFmpeg path not found!");
return;
}
var args = $"-i \"{url}\" -c copy -y \"{outputPath}\"";
var process = new System.Diagnostics.Process
{
StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = ffmpegPath,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
// Wait for exit with timeout (e.g. 5 minutes per trailer)
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromMinutes(5));
if (process.ExitCode != 0)
{
LogToFile($"FFmpeg failed with exit code {process.ExitCode}");
// Clean up failed file
if (File.Exists(outputPath)) File.Delete(outputPath);
}
else
{
LogToFile($"Successfully downloaded to {outputPath}");
}
}
catch (Exception ex)
{
LogToFile($"Download failed: {ex.Message}");
}
}
private bool IsExpired(string url)
{
// Simple check for 'Expires' query param usually found in IMDb video links
var match = Regex.Match(url, @"Expires=(\d+)");
if (match.Success && long.TryParse(match.Groups[1].Value, out long expireTime))
{
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
return now >= expireTime;
}
return true;
}
private async Task<string?> GetImdbVideoUrl(string imdbId)
{
try
{
var galleryUrl = $"https://www.imdb.com/title/{imdbId}/videogallery/?sort=date,desc";
var html = await _httpClient.GetStringAsync(galleryUrl);
var linkMatch = Regex.Match(html, @"/video/vi\d+");
if (!linkMatch.Success) return null;
var videoPageUrl = $"https://www.imdb.com{linkMatch.Value}";
var videoHtml = await _httpClient.GetStringAsync(videoPageUrl);
var jsonMatch = Regex.Match(videoHtml, @"<script id=""__NEXT_DATA__"" type=""application/json"">(.*?)</script>");
if (!jsonMatch.Success) return null;
var json = jsonMatch.Groups[1].Value;
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("props", out var props) &&
props.TryGetProperty("pageProps", out var pageProps) &&
pageProps.TryGetProperty("videoPlaybackData", out var playbackData) &&
playbackData.TryGetProperty("video", out var video) &&
video.TryGetProperty("playbackURLs", out var urls))
{
foreach (var urlItem in urls.EnumerateArray())
{
if (urlItem.GetProperty("videoMimeType").GetString() == "MP4")
{
return urlItem.GetProperty("url").GetString();
}
}
}
}
catch
{
return null;
}
return null;
}
}
}