aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Server.Implementations/Providers/ImageSaver.cs
blob: 3bdef9226e76a5acf844071352cca645058238f9 (plain)
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
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Server.Implementations.Providers
{
    /// <summary>
    /// Class ImageSaver
    /// </summary>
    public class ImageSaver
    {
        private static readonly CultureInfo UsCulture = new CultureInfo("en-US");

        /// <summary>
        /// The _config
        /// </summary>
        private readonly IServerConfigurationManager _config;

        /// <summary>
        /// The remote image cache
        /// </summary>
        private readonly FileSystemRepository _remoteImageCache;
        /// <summary>
        /// The _directory watchers
        /// </summary>
        private readonly IDirectoryWatchers _directoryWatchers;

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageSaver"/> class.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="directoryWatchers">The directory watchers.</param>
        public ImageSaver(IServerConfigurationManager config, IDirectoryWatchers directoryWatchers)
        {
            _config = config;
            _directoryWatchers = directoryWatchers;
            _remoteImageCache = new FileSystemRepository(config.ApplicationPaths.DownloadedImagesDataPath);
        }

        /// <summary>
        /// Saves the image.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="source">The source.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="sourceUrl">The source URL.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException">mimeType</exception>
        public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, string sourceUrl, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            var saveLocally = _config.Configuration.SaveLocalMeta || item is IItemByName || item is User;

            if (item is Audio || item.Parent == null)
            {
                saveLocally = false;
            }

            if (type != ImageType.Primary && item is Episode)
            {
                saveLocally = false;
            }

            var locationType = item.LocationType;
            if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
            {
                saveLocally = false;
            }

            var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);

            // If there are more than one output paths, the stream will need to be seekable
            if (paths.Length > 1 && !source.CanSeek)
            {
                var memoryStream = new MemoryStream();
                using (source)
                {
                    await source.CopyToAsync(memoryStream).ConfigureAwait(false);
                }
                memoryStream.Position = 0;
                source = memoryStream;
            }

            var currentPath = GetCurrentImagePath(item, type, imageIndex);

            using (source)
            {
                var isFirst = true;

                foreach (var path in paths)
                {
                    // Seek back to the beginning
                    if (!isFirst)
                    {
                        source.Position = 0;
                    }

                    await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);

                    isFirst = false;
                }
            }

            // Set the path into the BaseItem
            SetImagePath(item, type, imageIndex, paths[0], sourceUrl);

            // Delete the current path
            if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
            {
                _directoryWatchers.TemporarilyIgnore(currentPath);

                try
                {
                    var currentFile = new FileInfo(currentPath);

                    // This will fail if the file is hidden
                    if (currentFile.Exists)
                    {
                        if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            currentFile.Attributes &= ~FileAttributes.Hidden;
                        }

                        currentFile.Delete();
                    }
                }
                finally
                {
                    _directoryWatchers.RemoveTempIgnore(currentPath);
                }
            }
        }

        /// <summary>
        /// Saves the image to location.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="path">The path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
        {
            _directoryWatchers.TemporarilyIgnore(path);

            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));

                // If the file is currently hidden we'll have to remove that or the save will fail
                var file = new FileInfo(path);

                // This will fail if the file is hidden
                if (file.Exists)
                {
                    if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        file.Attributes &= ~FileAttributes.Hidden;
                    }
                }

                using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
                {
                    await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
                }
            }
            finally
            {
                _directoryWatchers.RemoveTempIgnore(path);
            }
        }

        /// <summary>
        /// Gets the save paths.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
        /// <returns>IEnumerable{System.String}.</returns>
        private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
        {
            if (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy || !saveLocally)
            {
                return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
            }

            return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
        }

        /// <summary>
        /// Gets the current image path.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// imageIndex
        /// or
        /// imageIndex
        /// </exception>
        private string GetCurrentImagePath(BaseItem item, ImageType type, int? imageIndex)
        {
            switch (type)
            {
                case ImageType.Screenshot:

                    if (!imageIndex.HasValue)
                    {
                        throw new ArgumentNullException("imageIndex");
                    }
                    return item.ScreenshotImagePaths.Count > imageIndex.Value ? item.ScreenshotImagePaths[imageIndex.Value] : null;
                case ImageType.Backdrop:
                    if (!imageIndex.HasValue)
                    {
                        throw new ArgumentNullException("imageIndex");
                    }
                    return item.BackdropImagePaths.Count > imageIndex.Value ? item.BackdropImagePaths[imageIndex.Value] : null;
                default:
                    return item.GetImage(type);
            }
        }

        /// <summary>
        /// Sets the image path.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="path">The path.</param>
        /// <param name="sourceUrl">The source URL.</param>
        /// <exception cref="System.ArgumentNullException">imageIndex
        /// or
        /// imageIndex</exception>
        private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path, string sourceUrl)
        {
            switch (type)
            {
                case ImageType.Screenshot:

                    if (!imageIndex.HasValue)
                    {
                        throw new ArgumentNullException("imageIndex");
                    }

                    if (item.ScreenshotImagePaths.Count > imageIndex.Value)
                    {
                        item.ScreenshotImagePaths[imageIndex.Value] = path;
                    }
                    else
                    {
                        item.ScreenshotImagePaths.Add(path);
                    }
                    break;
                case ImageType.Backdrop:
                    if (!imageIndex.HasValue)
                    {
                        throw new ArgumentNullException("imageIndex");
                    }
                    if (item.BackdropImagePaths.Count > imageIndex.Value)
                    {
                        item.BackdropImagePaths[imageIndex.Value] = path;
                    }
                    else
                    {
                        item.BackdropImagePaths.Add(path);
                    }

                    if (string.IsNullOrEmpty(sourceUrl))
                    {
                        item.RemoveImageSourceForPath(path);
                    }
                    else
                    {
                        item.AddImageSource(path, sourceUrl);
                    }
                    break;
                default:
                    item.SetImage(type, path);
                    break;
            }
        }

        /// <summary>
        /// Gets the save path.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// imageIndex
        /// or
        /// imageIndex
        /// </exception>
        private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
        {
            string filename;

            switch (type)
            {
                case ImageType.Art:
                    filename = "clearart";
                    break;
                case ImageType.Primary:
                    filename = item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : "folder";
                    break;
                case ImageType.Backdrop:
                    if (!imageIndex.HasValue)
                    {
                        throw new ArgumentNullException("imageIndex");
                    }
                    filename = imageIndex.Value == 0 ? "backdrop" : "backdrop" + imageIndex.Value.ToString(UsCulture);
                    break;
                case ImageType.Screenshot:
                    if (!imageIndex.HasValue)
                    {
                        throw new ArgumentNullException("imageIndex");
                    }
                    filename = imageIndex.Value == 0 ? "screenshot" : "screenshot" + imageIndex.Value.ToString(UsCulture);
                    break;
                default:
                    filename = type.ToString().ToLower();
                    break;
            }

            var extension = mimeType.Split('/').Last();

            if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
            {
                extension = "jpg";
            }

            extension = "." + extension.ToLower();

            string path = null;

            if (saveLocally)
            {
                if (item.IsInMixedFolder && !(item is Episode))
                {
                    path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
                }

                if (string.IsNullOrEmpty(path))
                {
                    path = Path.Combine(item.MetaLocation, filename + extension);
                }
            }

            // None of the save local conditions passed, so store it in our internal folders
            if (string.IsNullOrEmpty(path))
            {
                path = _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id, filename + extension);
            }

            return path;
        }

        /// <summary>
        /// Gets the compatible save paths.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <returns>IEnumerable{System.String}.</returns>
        /// <exception cref="System.ArgumentNullException">imageIndex</exception>
        private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
        {
            var extension = mimeType.Split('/').Last();

            if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
            {
                extension = "jpg";
            }
            extension = "." + extension.ToLower();

            // Backdrop paths
            if (type == ImageType.Backdrop)
            {
                if (!imageIndex.HasValue)
                {
                    throw new ArgumentNullException("imageIndex");
                }

                if (imageIndex.Value == 0)
                {
                    if (item is Season && item.IndexNumber.HasValue)
                    {
                        var seriesFolder = Path.GetDirectoryName(item.Path);

                        var seasonMarker = item.IndexNumber.Value == 0
                                               ? "-specials"
                                               : item.IndexNumber.Value.ToString("00", UsCulture);

                        var imageFilename = "season" + seasonMarker + "-fanart" + extension;

                        return new[] { Path.Combine(seriesFolder, imageFilename) };
                    }

                    return new[]
                        {
                            Path.Combine(item.MetaLocation, "fanart" + extension)
                        };
                }

                var outputIndex = imageIndex.Value;

                return new[]
                    {
                        Path.Combine(item.MetaLocation, "extrafanart", "fanart" + outputIndex.ToString(UsCulture) + extension),
                        Path.Combine(item.MetaLocation, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension)
                    };
            }

            if (type == ImageType.Primary)
            {
                if (item is Season && item.IndexNumber.HasValue)
                {
                    var seriesFolder = Path.GetDirectoryName(item.Path);

                    var seasonMarker = item.IndexNumber.Value == 0
                                           ? "-specials"
                                           : item.IndexNumber.Value.ToString("00", UsCulture);

                    var imageFilename = "season" + seasonMarker + "-poster" + extension;

                    return new[] { Path.Combine(seriesFolder, imageFilename) };
                }

                if (item is Episode)
                {
                    var seasonFolder = Path.GetDirectoryName(item.Path);

                    var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;

                    return new[] { Path.Combine(seasonFolder, imageFilename) };
                }

                if (item.IsInMixedFolder)
                {
                    return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
                }

                var filename = "poster" + extension;
                return new[] { Path.Combine(item.MetaLocation, filename) };
            }

            if (type == ImageType.Banner)
            {
                if (item is Season && item.IndexNumber.HasValue)
                {
                    var seriesFolder = Path.GetDirectoryName(item.Path);

                    var seasonMarker = item.IndexNumber.Value == 0
                                           ? "-specials"
                                           : item.IndexNumber.Value.ToString("00", UsCulture);

                    var imageFilename = "season" + seasonMarker + "-banner" + extension;

                    return new[] { Path.Combine(seriesFolder, imageFilename) };
                }
            }

            if (type == ImageType.Thumb)
            {
                if (item is Season && item.IndexNumber.HasValue)
                {
                    var seriesFolder = Path.GetDirectoryName(item.Path);

                    var seasonMarker = item.IndexNumber.Value == 0
                                           ? "-specials"
                                           : item.IndexNumber.Value.ToString("00", UsCulture);

                    var imageFilename = "season" + seasonMarker + "-landscape" + extension;

                    return new[] { Path.Combine(seriesFolder, imageFilename) };
                }
            }

            // All other paths are the same
            return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
        }

        /// <summary>
        /// Gets the save path for item in mixed folder.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageFilename">The image filename.</param>
        /// <param name="extension">The extension.</param>
        /// <returns>System.String.</returns>
        private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
        {
            if (type == ImageType.Primary)
            {
                imageFilename = "poster";
            }
            var folder = Path.GetDirectoryName(item.Path);

            return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
        }
    }
}