-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathCommon.cs
More file actions
556 lines (484 loc) · 16 KB
/
Common.cs
File metadata and controls
556 lines (484 loc) · 16 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Model.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Gelato;
public sealed class StremioUri
{
public StremioMediaType MediaType { get; }
public string ExternalId { get; }
private readonly string? _streamId;
public StremioUri(StremioMediaType mediaType, string? externalId, string? streamId = null)
{
if (string.IsNullOrWhiteSpace(externalId))
throw new ArgumentException("externalId cannot be null or empty.", nameof(externalId));
MediaType = mediaType;
ExternalId = externalId;
_streamId = string.IsNullOrWhiteSpace(streamId) ? null : streamId;
}
public static StremioUri? FromBaseItem(BaseItem item)
{
ArgumentNullException.ThrowIfNull(item);
var kind = item.GetBaseItemKind();
var mediaType = kind switch
{
BaseItemKind.Movie => StremioMediaType.Movie,
BaseItemKind.Series or BaseItemKind.Episode => StremioMediaType.Series,
_ => throw new NotSupportedException($"Unsupported BaseItemKind: {kind}"),
};
var stremioId = item.GetProviderId("Stremio");
StremioUri? uri = null;
if (!string.IsNullOrWhiteSpace(stremioId))
uri = new StremioUri(mediaType, stremioId);
switch (kind)
{
case BaseItemKind.Movie:
{
var imdb = item.GetProviderId(MetadataProvider.Imdb);
return string.IsNullOrWhiteSpace(imdb)
? uri
: new StremioUri(StremioMediaType.Movie, imdb);
}
case BaseItemKind.Series:
{
var imdb = item.GetProviderId(MetadataProvider.Imdb);
return string.IsNullOrWhiteSpace(imdb)
? uri
: new StremioUri(StremioMediaType.Series, imdb);
}
case BaseItemKind.Episode:
{
var ep = (Episode)item;
var seriesImdb = ep.Series?.GetProviderId(MetadataProvider.Imdb);
if (
string.IsNullOrWhiteSpace(seriesImdb)
|| ep.ParentIndexNumber is null
|| ep.IndexNumber is null
)
return uri;
var ext = $"{seriesImdb}:{ep.ParentIndexNumber}:{ep.IndexNumber}";
return new StremioUri(StremioMediaType.Series, ext);
}
}
return null;
}
public override string ToString()
{
var type = MediaType == StremioMediaType.Movie ? "movie" : "series";
return _streamId is null
? $"stremio://{type}/{ExternalId}"
: $"stremio://{type}/{ExternalId}/{_streamId}";
}
public Guid ToGuid()
{
var hash = MD5.HashData(Encoding.UTF8.GetBytes(ToString()));
return new Guid(hash);
}
}
public static class Utils
{
public static long? ParseToTicks(string? input)
{
if (string.IsNullOrWhiteSpace(input))
return null;
input = input.Trim().ToLowerInvariant();
// Try built-in parse (hh:mm:ss)
if (TimeSpan.TryParse(input, out var ts))
return ts.Ticks;
// Try XML ISO8601 style (PT2H29M)
try
{
ts = System.Xml.XmlConvert.ToTimeSpan(input);
return ts.Ticks;
}
catch
{
// ignore
}
// Regex fallback for human formats like "2h29min"
var h = Regex.Match(input, @"(\d+)\s*h");
var m = Regex.Match(input, @"(\d+)\s*min");
var s = Regex.Match(input, @"(\d+)\s*s(ec)?");
var hours = h.Success ? int.Parse(h.Groups[1].Value) : 0;
var mins = m.Success ? int.Parse(m.Groups[1].Value) : 0;
var secs = s.Success ? int.Parse(s.Groups[1].Value) : 0;
// If plain number like "149" → minutes
if (!h.Success && !m.Success && !s.Success && int.TryParse(input, out var onlyNum))
mins = onlyNum;
return new TimeSpan(hours, mins, secs).Ticks;
}
}
public sealed class KeyLock
{
private readonly ConcurrentDictionary<Guid, SemaphoreSlim> _queues = new();
private readonly ConcurrentDictionary<Guid, Lazy<Task>> _inflight = new();
public Task RunSingleFlightAsync(
Guid key,
Func<CancellationToken, Task> action,
CancellationToken ct = default
)
{
var lazy = _inflight.GetOrAdd(
key,
_ => new Lazy<Task>(
() => Once(key, action, ct),
LazyThreadSafetyMode.ExecutionAndPublication
)
);
return lazy.Value;
}
public async Task RunQueuedAsync(
Guid key,
Func<CancellationToken, Task> action,
CancellationToken ct = default
)
{
var sem = _queues.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
await sem.WaitAsync(ct).ConfigureAwait(false);
try
{
await action(ct).ConfigureAwait(false);
}
finally
{
ReleaseAndMaybeRemove(key, sem);
}
}
private async Task Once(Guid key, Func<CancellationToken, Task> action, CancellationToken ct)
{
try
{
await action(ct).ConfigureAwait(false);
}
finally
{
_inflight.TryRemove(key, out _);
}
}
private void ReleaseAndMaybeRemove(Guid key, SemaphoreSlim sem)
{
sem.Release();
if (sem.CurrentCount == 1 && sem.Wait(0))
{
sem.Release();
_queues.TryRemove(key, out _);
}
}
}
public static class EnumMappingExtensions
{
public static StremioMediaType ToStremio(this BaseItemKind kind)
{
return kind switch
{
BaseItemKind.Movie => StremioMediaType.Movie,
BaseItemKind.Series or BaseItemKind.Season or BaseItemKind.Episode =>
StremioMediaType.Series,
_ => StremioMediaType.Unknown,
};
}
public static BaseItemKind ToBaseItem(this StremioMediaType type)
{
return type switch
{
StremioMediaType.Movie => BaseItemKind.Movie,
StremioMediaType.Series => BaseItemKind.Series,
_ => throw new ArgumentOutOfRangeException(
nameof(type),
type,
"Unknown StremioMediaType"
),
};
}
}
public static class ActionContextExtensions
{
private static readonly string[] RouteGuidKeys =
[
"id",
"Id",
"ID",
"itemId",
"ItemId",
"ItemID",
];
private static readonly string[] IdsGuidKeys = ["ids", "Ids", "IDs"];
private static readonly HashSet<string> SearchActionNames = new(
StringComparer.OrdinalIgnoreCase
)
{
"GetItems",
"GetItemsByUserIdLegacy",
};
private static readonly HashSet<string> BaseItemListActionNames = new(
StringComparer.OrdinalIgnoreCase
)
{
"GetItems",
"GetItemsByUserIdLegacy",
"NextUp",
"GetResumeItems",
"GetResumeItemsLegacy",
"GetNextUp",
"GetEpisodes",
"GetSeasons",
"GetSimilarItems",
"GetLatestMedia",
"GetLatestMediaLegacy",
"GetUpcomingEpisodes",
"GetRecommendedItems",
"GetMovieRecommendations",
"GetSuggestionsLegacy",
"GetSuggestions",
"GetItemCounts",
"GetSectionContent",
};
private static readonly HashSet<string> InsertableActionNames = new(
StringComparer.OrdinalIgnoreCase
)
{
"GetItems",
"GetItem",
"GetItemLegacy",
"GetItemsByUserIdLegacy",
"GetPlaybackInfo",
"GetPostedPlaybackInfo",
"GetVideoStream",
"GetDownload",
"GetSubtitleWithTicks",
};
private static readonly HashSet<string> InsertableListActionNames = new(
StringComparer.OrdinalIgnoreCase
)
{
"GetItems",
"GetItemsByUserIdLegacy",
};
public static string? GetActionName(this ActionExecutingContext ctx) =>
(ctx.ActionDescriptor as ControllerActionDescriptor)?.ActionName;
public static string? GetActionName(this HttpContext ctx) =>
ctx.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>()?.ActionName;
public static bool IsApiListing(this HttpContext ctx)
{
var actionName = ctx.GetActionName();
return actionName != null && BaseItemListActionNames.Contains(actionName);
}
public static bool IsHomeScreenSectionListing(this HttpContext ctx)
{
var action = ctx.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>();
if (
action is not null
&& string.Equals(
action.ControllerName,
"HomeScreen",
StringComparison.OrdinalIgnoreCase
)
&& string.Equals(
action.ActionName,
"GetSectionContent",
StringComparison.OrdinalIgnoreCase
)
)
{
return true;
}
var path = ctx.Request.Path;
return path.HasValue
&& path.Value?.Contains("/HomeScreen/Section/", StringComparison.OrdinalIgnoreCase)
== true;
}
public static bool IsApiSearchAction(this ActionExecutingContext ctx) =>
ctx.GetActionName() is { } actionName && SearchActionNames.Contains(actionName);
public static bool IsInsertableAction(this HttpContext ctx)
{
var actionName = ctx.GetActionName();
return actionName != null
&& InsertableActionNames.Contains(actionName)
&& (
!InsertableListActionNames.Contains(actionName)
|| InsertableListActionNames.Contains(actionName) && IsSingleItemList(ctx)
);
}
public static bool IsInsertableAction(this ActionExecutingContext ctx) =>
ctx.HttpContext.IsInsertableAction();
public static bool IsSingleItemList(this HttpContext ctx)
{
var q = ctx.Request.Query;
if (!q.TryGetValue("ids", out var idsRaw))
return false;
var ids = idsRaw
.SelectMany(v =>
v.ToString()
.Split(
',',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
)
)
.ToArray();
return ids.Length == 1;
}
public static bool IsSingleItemList(this ActionExecutingContext ctx) =>
ctx.HttpContext.IsSingleItemList();
public static bool TryGetRouteGuid(this ActionExecutingContext ctx, out Guid value)
{
value = Guid.Empty;
return ctx.TryGetRouteGuidString(out var s) && Guid.TryParse(s, out value);
}
private static bool TryGetRouteGuidString(this ActionExecutingContext ctx, out string value)
{
value = string.Empty;
// Check if already resolved
if (ctx.HttpContext.Items["GuidResolved"] is Guid g)
{
value = g.ToString("N");
return true;
}
var rd = ctx.RouteData.Values;
// Check route values
foreach (var key in RouteGuidKeys)
{
if (
rd.TryGetValue(key, out var raw)
&& raw?.ToString() is { } s
&& !string.IsNullOrWhiteSpace(s)
)
{
value = s;
return true;
}
}
// Fallback: check query string "ids"
var query = ctx.HttpContext.Request.Query;
if (
query.TryGetValue("ids", out var ids)
&& ids.Count == 1
&& !string.IsNullOrWhiteSpace(ids[0])
)
{
value = ids[0]!;
return true;
}
return false;
}
public static void ReplaceGuid(this ActionExecutingContext ctx, Guid value)
{
var rd = ctx.RouteData.Values;
foreach (var key in RouteGuidKeys)
{
if (rd.TryGetValue(key, out var raw) && raw is not null)
{
rd[key] = value.ToString();
ctx.ActionArguments[key] = value;
}
}
// Also replace ids query-parameter argument (used by list actions like GetItems)
foreach (var key in IdsGuidKeys)
{
if (ctx.ActionArguments.ContainsKey(key))
{
ctx.ActionArguments[key] = new[] { value };
break;
}
}
ctx.HttpContext.Items["GuidResolved"] = value;
}
public static bool TryGetUserId(this ActionExecutingContext ctx, out Guid userId)
{
return ctx.HttpContext.TryGetUserId(out userId);
}
public static bool TryGetUserId(this HttpContext ctx, out Guid userId)
{
userId = Guid.Empty;
var userIdStr =
ctx.User.Claims.FirstOrDefault(c => c.Type is "UserId" or "Jellyfin-UserId")?.Value
?? ctx.Request.Query["userId"].FirstOrDefault();
if (!Guid.TryParse(userIdStr, out userId))
return false;
return userId != Guid.Empty;
}
public static bool TryGetActionArgument<T>(
this ActionExecutingContext ctx,
string key,
out T value,
T defaultValue = default
)
{
if (ctx.ActionArguments.TryGetValue(key, out var objValue) && objValue is T typedValue)
{
value = typedValue;
return true;
}
value = defaultValue;
return false;
}
}
public static class BaseItemExtensions
{
public static bool IsGelato(this BaseItem item)
{
return !string.IsNullOrWhiteSpace(item.GetProviderId("Stremio"));
}
public static bool HasStreamTag(this BaseItem item)
{
return item.Tags is not null
&& item.Tags.Contains(GelatoManager.StreamTag, StringComparer.OrdinalIgnoreCase);
}
public static bool IsPrimaryVersion(this BaseItem item)
{
return !item.HasStreamTag()
&& string.IsNullOrWhiteSpace((item as Video)?.PrimaryVersionId)
&& !item.IsVirtualItem;
}
public static bool IsStream(this BaseItem item)
{
return !string.IsNullOrWhiteSpace(item.GetProviderId("Stremio"))
&& !item.IsPrimaryVersion();
}
public static T? GelatoData<T>(this BaseItem item, string key)
{
if (string.IsNullOrEmpty(item.ExternalId))
return default;
try
{
var dict = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(item.ExternalId);
return dict != null && dict.TryGetValue(key, out var el)
? el.Deserialize<T>()
: default;
}
catch
{
return default;
}
}
public static void SetGelatoData<T>(this BaseItem item, string key, T value)
{
Dictionary<string, JsonElement> data;
try
{
data = string.IsNullOrEmpty(item.ExternalId)
? new Dictionary<string, JsonElement>()
: JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(item.ExternalId)
?? new Dictionary<string, JsonElement>();
}
catch
{
data = new Dictionary<string, JsonElement>();
}
data[key] = JsonSerializer.SerializeToElement(value);
item.ExternalId = JsonSerializer.Serialize(data);
}
}
public static class StringExtensions
{
public static bool IsUrl(this string s) =>
s.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| s.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
}