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
|
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.LocalMetadata.Savers
{
/// <inheritdoc />
public abstract class BaseXmlSaver : IMetadataFileSaver
{
/// <summary>
/// Initializes a new instance of the <see cref="BaseXmlSaver"/> class.
/// </summary>
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
/// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="logger">Instance of the <see cref="ILogger{BaseXmlSaver}"/> interface.</param>
protected BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger<BaseXmlSaver> logger)
{
FileSystem = fileSystem;
ConfigurationManager = configurationManager;
LibraryManager = libraryManager;
Logger = logger;
}
/// <summary>
/// Gets the file system.
/// </summary>
protected IFileSystem FileSystem { get; private set; }
/// <summary>
/// Gets the configuration manager.
/// </summary>
protected IServerConfigurationManager ConfigurationManager { get; private set; }
/// <summary>
/// Gets the library manager.
/// </summary>
protected ILibraryManager LibraryManager { get; private set; }
/// <summary>
/// Gets the logger.
/// </summary>
protected ILogger<BaseXmlSaver> Logger { get; private set; }
/// <inheritdoc />
public string Name => XmlProviderUtils.Name;
/// <inheritdoc />
public string GetSavePath(BaseItem item)
{
return GetLocalSavePath(item);
}
/// <summary>
/// Gets the save path.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>System.String.</returns>
protected abstract string GetLocalSavePath(BaseItem item);
/// <summary>
/// Gets the name of the root element.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>System.String.</returns>
protected virtual string GetRootElementName(BaseItem item)
=> "Item";
/// <summary>
/// Determines whether [is enabled for] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <param name="updateType">Type of the update.</param>
/// <returns><c>true</c> if [is enabled for] [the specified item]; otherwise, <c>false</c>.</returns>
public abstract bool IsEnabledFor(BaseItem item, ItemUpdateType updateType);
/// <inheritdoc />
public async Task SaveAsync(BaseItem item, CancellationToken cancellationToken)
{
var path = GetSavePath(item);
var directory = Path.GetDirectoryName(path) ?? throw new InvalidDataException($"Provided path ({path}) is not valid.");
Directory.CreateDirectory(directory);
// On Windows, savint the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false);
var fileStreamOptions = new FileStreamOptions()
{
Mode = FileMode.Create,
Access = FileAccess.Write,
Share = FileShare.None
};
var filestream = new FileStream(path, fileStreamOptions);
await using (filestream.ConfigureAwait(false))
{
var settings = new XmlWriterSettings
{
Indent = true,
Encoding = Encoding.UTF8,
Async = true
};
var writer = XmlWriter.Create(filestream, settings);
await using (writer.ConfigureAwait(false))
{
var root = GetRootElementName(item);
await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
await writer.WriteStartElementAsync(null, root, null).ConfigureAwait(false);
var baseItem = item;
if (baseItem is not null)
{
await AddCommonNodesAsync(baseItem, writer).ConfigureAwait(false);
}
await WriteCustomElementsAsync(item, writer).ConfigureAwait(false);
await writer.WriteEndElementAsync().ConfigureAwait(false);
await writer.WriteEndDocumentAsync().ConfigureAwait(false);
}
}
if (ConfigurationManager.Configuration.SaveMetadataHidden)
{
SetHidden(path, true);
}
}
private void SetHidden(string path, bool hidden)
{
try
{
FileSystem.SetHidden(path, hidden);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error setting hidden attribute on {Path}", path);
}
}
/// <summary>
/// Write custom elements.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="writer">The xml writer.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
protected abstract Task WriteCustomElementsAsync(BaseItem item, XmlWriter writer);
/// <summary>
/// Adds the common nodes.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="writer">The xml writer.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
private async Task AddCommonNodesAsync(BaseItem item, XmlWriter writer)
{
if (!string.IsNullOrEmpty(item.OfficialRating))
{
await writer.WriteElementStringAsync(null, "ContentRating", null, item.OfficialRating).ConfigureAwait(false);
}
await writer.WriteElementStringAsync(null, "Added", null, item.DateCreated.ToLocalTime().ToString("G", CultureInfo.InvariantCulture)).ConfigureAwait(false);
await writer.WriteElementStringAsync(null, "LockData", null, item.IsLocked.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()).ConfigureAwait(false);
if (item.LockedFields.Length > 0)
{
await writer.WriteElementStringAsync(null, "LockedFields", null, string.Join('|', item.LockedFields)).ConfigureAwait(false);
}
if (item.CriticRating.HasValue)
{
await writer.WriteElementStringAsync(null, "CriticRating", null, item.CriticRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(item.Overview))
{
await writer.WriteElementStringAsync(null, "Overview", null, item.Overview).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(item.OriginalTitle))
{
await writer.WriteElementStringAsync(null, "OriginalTitle", null, item.OriginalTitle).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(item.CustomRating))
{
await writer.WriteElementStringAsync(null, "CustomRating", null, item.CustomRating).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(item.Name) && item is not Episode)
{
await writer.WriteElementStringAsync(null, "LocalTitle", null, item.Name).ConfigureAwait(false);
}
var forcedSortName = item.ForcedSortName;
if (!string.IsNullOrEmpty(forcedSortName))
{
await writer.WriteElementStringAsync(null, "SortTitle", null, forcedSortName).ConfigureAwait(false);
}
if (item.PremiereDate.HasValue)
{
if (item is Person)
{
await writer.WriteElementStringAsync(null, "BirthDate", null, item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
else if (item is not Episode)
{
await writer.WriteElementStringAsync(null, "PremiereDate", null, item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
}
if (item.EndDate.HasValue)
{
if (item is Person)
{
await writer.WriteElementStringAsync(null, "DeathDate", null, item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
else if (item is not Episode)
{
await writer.WriteElementStringAsync(null, "EndDate", null, item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
}
if (item.RemoteTrailers.Count > 0)
{
await writer.WriteStartElementAsync(null, "Trailers", null).ConfigureAwait(false);
foreach (var trailer in item.RemoteTrailers)
{
await writer.WriteElementStringAsync(null, "Trailer", null, trailer.Url).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
if (item.ProductionLocations.Length > 0)
{
await writer.WriteStartElementAsync(null, "Countries", null).ConfigureAwait(false);
foreach (var name in item.ProductionLocations)
{
await writer.WriteElementStringAsync(null, "Country", null, name).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
if (item is IHasDisplayOrder hasDisplayOrder && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
{
await writer.WriteElementStringAsync(null, "DisplayOrder", null, hasDisplayOrder.DisplayOrder).ConfigureAwait(false);
}
if (item.CommunityRating.HasValue)
{
await writer.WriteElementStringAsync(null, "Rating", null, item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
if (item.ProductionYear.HasValue && item is not Person)
{
await writer.WriteElementStringAsync(null, "ProductionYear", null, item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
if (item is IHasAspectRatio hasAspectRatio)
{
if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
{
await writer.WriteElementStringAsync(null, "AspectRatio", null, hasAspectRatio.AspectRatio).ConfigureAwait(false);
}
}
if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
{
await writer.WriteElementStringAsync(null, "Language", null, item.PreferredMetadataLanguage).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
{
await writer.WriteElementStringAsync(null, "CountryCode", null, item.PreferredMetadataCountryCode).ConfigureAwait(false);
}
// Use original runtime here, actual file runtime later in MediaInfo
var runTimeTicks = item.RunTimeTicks;
if (runTimeTicks.HasValue)
{
var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
await writer.WriteElementStringAsync(null, "RunningTime", null, Math.Floor(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
if (item.ProviderIds is not null)
{
foreach (var providerKey in item.ProviderIds.Keys)
{
var providerId = item.ProviderIds[providerKey];
if (!string.IsNullOrEmpty(providerId))
{
await writer.WriteElementStringAsync(null, providerKey + "Id", null, providerId).ConfigureAwait(false);
}
}
}
if (!string.IsNullOrWhiteSpace(item.Tagline))
{
await writer.WriteStartElementAsync(null, "Taglines", null).ConfigureAwait(false);
await writer.WriteElementStringAsync(null, "Tagline", null, item.Tagline).ConfigureAwait(false);
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
if (item.Genres.Length > 0)
{
await writer.WriteStartElementAsync(null, "Genres", null).ConfigureAwait(false);
foreach (var genre in item.Genres)
{
await writer.WriteElementStringAsync(null, "Genre", null, genre).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
if (item.Studios.Length > 0)
{
await writer.WriteStartElementAsync(null, "Studios", null).ConfigureAwait(false);
foreach (var studio in item.Studios)
{
await writer.WriteElementStringAsync(null, "Studio", null, studio).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
if (item.Tags.Length > 0)
{
await writer.WriteStartElementAsync(null, "Tags", null).ConfigureAwait(false);
foreach (var tag in item.Tags)
{
await writer.WriteElementStringAsync(null, "Tag", null, tag).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
var people = LibraryManager.GetPeople(item);
if (people.Count > 0)
{
await writer.WriteStartElementAsync(null, "Persons", null).ConfigureAwait(false);
foreach (var person in people)
{
await writer.WriteStartElementAsync(null, "Person", null).ConfigureAwait(false);
await writer.WriteElementStringAsync(null, "Name", null, person.Name).ConfigureAwait(false);
await writer.WriteElementStringAsync(null, "Type", null, person.Type).ConfigureAwait(false);
await writer.WriteElementStringAsync(null, "Role", null, person.Role).ConfigureAwait(false);
if (person.SortOrder.HasValue)
{
await writer.WriteElementStringAsync(null, "SortOrder", null, person.SortOrder.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
if (item is BoxSet boxset)
{
await AddLinkedChildren(boxset, writer, "CollectionItems", "CollectionItem").ConfigureAwait(false);
}
if (item is Playlist playlist && !Playlist.IsPlaylistFile(playlist.Path))
{
await writer.WriteElementStringAsync(null, "OwnerUserId", null, playlist.OwnerUserId.ToString("N")).ConfigureAwait(false);
await AddLinkedChildren(playlist, writer, "PlaylistItems", "PlaylistItem").ConfigureAwait(false);
}
if (item is IHasShares hasShares)
{
await AddSharesAsync(hasShares, writer).ConfigureAwait(false);
}
await AddMediaInfo(item, writer).ConfigureAwait(false);
}
/// <summary>
/// Add shares.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="writer">The xml writer.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
private static async Task AddSharesAsync(IHasShares item, XmlWriter writer)
{
await writer.WriteStartElementAsync(null, "Shares", null).ConfigureAwait(false);
foreach (var share in item.Shares)
{
if (share.UserId is not null)
{
await writer.WriteStartElementAsync(null, "Share", null).ConfigureAwait(false);
await writer.WriteElementStringAsync(null, "UserId", null, share.UserId).ConfigureAwait(false);
await writer.WriteElementStringAsync(
null,
"CanEdit",
null,
share.CanEdit.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()).ConfigureAwait(false);
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
/// <summary>
/// Appends the media info.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="writer">The xml writer.</param>
/// <typeparam name="T">Type of item.</typeparam>
/// <returns>The task object representing the asynchronous operation.</returns>
private static Task AddMediaInfo<T>(T item, XmlWriter writer)
where T : BaseItem
{
if (item is Video video && video.Video3DFormat.HasValue)
{
return video.Video3DFormat switch
{
Video3DFormat.FullSideBySide =>
writer.WriteElementStringAsync(null, "Format3D", null, "FSBS"),
Video3DFormat.FullTopAndBottom =>
writer.WriteElementStringAsync(null, "Format3D", null, "FTAB"),
Video3DFormat.HalfSideBySide =>
writer.WriteElementStringAsync(null, "Format3D", null, "HSBS"),
Video3DFormat.HalfTopAndBottom =>
writer.WriteElementStringAsync(null, "Format3D", null, "HTAB"),
Video3DFormat.MVC =>
writer.WriteElementStringAsync(null, "Format3D", null, "MVC"),
_ => Task.CompletedTask
};
}
return Task.CompletedTask;
}
/// <summary>
/// ADd linked children.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="writer">The xml writer.</param>
/// <param name="pluralNodeName">The plural node name.</param>
/// <param name="singularNodeName">The singular node name.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
private static async Task AddLinkedChildren(Folder item, XmlWriter writer, string pluralNodeName, string singularNodeName)
{
var items = item.LinkedChildren
.Where(i => i.Type == LinkedChildType.Manual)
.ToList();
if (items.Count == 0)
{
return;
}
await writer.WriteStartElementAsync(null, pluralNodeName, null).ConfigureAwait(false);
foreach (var link in items)
{
if (!string.IsNullOrWhiteSpace(link.Path) || !string.IsNullOrWhiteSpace(link.LibraryItemId))
{
await writer.WriteStartElementAsync(null, singularNodeName, null).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(link.Path))
{
await writer.WriteElementStringAsync(null, "Path", null, link.Path).ConfigureAwait(false);
}
if (!string.IsNullOrWhiteSpace(link.LibraryItemId))
{
await writer.WriteElementStringAsync(null, "ItemId", null, link.LibraryItemId).ConfigureAwait(false);
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
}
await writer.WriteEndElementAsync().ConfigureAwait(false);
}
}
}
|