-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYouTubeChannel.cs
More file actions
208 lines (184 loc) · 8.29 KB
/
Copy pathYouTubeChannel.cs
File metadata and controls
208 lines (184 loc) · 8.29 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
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Channels;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Emby.YouTubePlugin
{
public partial class YouTubeChannel : IChannel, IHasChannelFeatures
{
private static void Log(string msg) => LogPublic(msg);
public static void LogPublic(string msg)
{
var logger = Plugin.PluginLogger;
if (logger != null)
logger.Log(LogLevel.Information, 0, msg, null, (s, _) => s);
else
System.Diagnostics.Debug.WriteLine(msg);
// Always tee to a plugin-owned file. Emby's ILoggerFactory does
// not always surface plugin categories in embyserver.txt, and
// without local logs we cannot diagnose client-specific issues
// such as resume seeks misbehaving on the LG TV app.
PluginFileLog.Write(msg);
}
public string Name => "YouTube";
public string Description => "YouTube integration via official YouTube Data API v3.";
public string Id => "youtube_channel_10";
private const string ChannelDataRevision = "20260908-stats-labels";
// Emby caches the channel's folders/items keyed by DataVersion and only
// re-queries GetChannelItems when it changes. A constant version means a
// saved setting (shorts/trending/categories/sort/saved-channels/API key…)
// is not applied until the cache otherwise expires. Deriving the version
// from the same content hash that gates the save-refresh makes any real
// settings change invalidate the cache so it takes effect on next browse.
public string DataVersion
{
get
{
try
{
var config = Plugin.Instance?.Options;
return config == null
? "1.0.0." + ChannelDataRevision
: "1.0.0." + ChannelDataRevision + "." + PluginEntryPoint.ComputeConfigHash(config);
}
catch
{
return "1.0.0";
}
}
}
public ChannelParentalRating ParentalRating => ChannelParentalRating.GeneralAudience;
public bool IsEnabledByDefault => true;
public ChannelFeatures Features => new ChannelFeatures
{
ShowRootFoldersAtTopLevel = Plugin.Instance?.Options.ShowRootFoldersAtTopLevel == true
};
public ChannelFeatures GetChannelFeatures() => Features;
public async Task<ChannelItemResult> GetChannelItems(
InternalChannelItemQuery query, CancellationToken cancellationToken)
{
var items = new List<ChannelItemInfo>();
var plugin = Plugin.Instance;
if (plugin == null)
return Msg(items, "ERROR: Plugin not initialized.");
var config = plugin.Options;
var apiKey = (config.ApiKey ?? "").Trim();
Log($"[YT] GetChannelItems called. FolderId={query.FolderId ?? "(root)"}, ApiKey={!string.IsNullOrEmpty(apiKey)}, SavedItems={config.SavedItems ?? "(empty)"}");
// Mark the channel pipeline as active so the sort-name / image repair
// queues pause their library.db writes. Covers refreshes started by
// Emby's own scheduled task as well as plugin-triggered ones.
ChannelRefreshInvoker.NoteChannelScanActivity();
if (string.IsNullOrWhiteSpace(apiKey))
return Msg(items, "ERROR: Please configure a YouTube API Key in the plugin settings.");
try
{
// Root: build the visible folders.
if (string.IsNullOrEmpty(query.FolderId))
{
return await BuildRootItemsAsync(apiKey, config, cancellationToken)
.ConfigureAwait(false);
}
// Subfolder: load videos or drop one more level.
if (query.FolderId.Contains(FolderSeparator))
{
var sepIdx = query.FolderId.IndexOf(FolderSeparator, StringComparison.Ordinal);
if (sepIdx < 0) return new ChannelItemResult { Items = items };
string type = query.FolderId.Substring(0, sepIdx);
string term = query.FolderId.Substring(sepIdx + FolderSeparator.Length);
// Channel folders open into Videos / Shorts / Live.
if (type == "channel")
{
return await BuildChannelSubfoldersAsync(apiKey, config, term, cancellationToken)
.ConfigureAwait(false);
}
if (type == "trending")
{
return await LoadTrending(apiKey, cancellationToken,
(config.TrendingRegion ?? "").Trim(),
(config.TrendingCategory ?? "").Trim())
.ConfigureAwait(false);
}
// Root of the categories browser.
if (type == "categories" && term == "root")
{
return await LoadCategoryRootAsync(apiKey, config, cancellationToken)
.ConfigureAwait(false);
}
// A single category just hits the trending endpoint with a category filter.
if (type == "category")
{
var region = string.IsNullOrWhiteSpace(config.TrendingRegion) ? "US" : config.TrendingRegion.Trim();
return await LoadTrending(apiKey, cancellationToken, region, term).ConfigureAwait(false);
}
return await LoadMediaFolderAsync(apiKey, config, type, term, cancellationToken)
.ConfigureAwait(false);
}
return new ChannelItemResult { Items = items };
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
Log($"[YT] GetChannelItems error: {ex}");
return Msg(items, $"ERROR: {ex.Message}");
}
}
public IEnumerable<ImageType> GetSupportedChannelImages() =>
new List<ImageType> { ImageType.Thumb, ImageType.Primary };
public Task<DynamicImageResponse> GetChannelImage(
ImageType type, CancellationToken cancellationToken)
{
var response = new DynamicImageResponse();
var t = GetType();
var stream = t.Assembly.GetManifestResourceStream(t.Namespace + ".thumb.png");
if (stream != null)
{
response.Format = ImageFormat.Png;
response.Stream = stream;
return Task.FromResult(response);
}
var assemblyDir = Path.GetDirectoryName(t.Assembly.Location) ?? "";
var filePath = Path.Combine(assemblyDir, "thumb.png");
if (File.Exists(filePath))
{
response.Format = ImageFormat.Png;
response.Path = filePath;
}
return Task.FromResult(response);
}
private static ChannelItemResult Msg(List<ChannelItemInfo> items, string msg)
{
items.Add(new ChannelItemInfo
{
Name = msg,
Id = "msg",
Type = ChannelItemType.Folder
});
return new ChannelItemResult
{
Items = items,
TotalRecordCount = items.Count
};
}
private static ChannelItemResult ToResult(List<ChannelItemInfo> items) =>
new()
{
Items = items,
TotalRecordCount = items.Count
};
}
}