aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Controllers/ImageByNameController.cs
blob: 0e3c32d3cc1eea44ef00d04a6ef92c839f0814a2 (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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Jellyfin.Api.Controllers
{
    /// <summary>
    ///     Images By Name Controller.
    /// </summary>
    [Route("Images")]
    public class ImageByNameController : BaseJellyfinApiController
    {
        private readonly IServerApplicationPaths _applicationPaths;
        private readonly IFileSystem _fileSystem;

        /// <summary>
        ///     Initializes a new instance of the <see cref="ImageByNameController" /> class.
        /// </summary>
        /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager" /> interface.</param>
        /// <param name="fileSystem">Instance of the <see cref="IFileSystem" /> interface.</param>
        public ImageByNameController(
            IServerConfigurationManager serverConfigurationManager,
            IFileSystem fileSystem)
        {
            _applicationPaths = serverConfigurationManager.ApplicationPaths;
            _fileSystem = fileSystem;
        }

        /// <summary>
        ///     Get all general images.
        /// </summary>
        /// <response code="200">Retrieved list of images.</response>
        /// <returns>An <see cref="OkResult"/> containing the list of images.</returns>
        [HttpGet("General")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult<IEnumerable<ImageByNameInfo>> GetGeneralImages()
        {
            return GetImageList(_applicationPaths.GeneralPath, false);
        }

        /// <summary>
        ///     Get General Image.
        /// </summary>
        /// <param name="name">The name of the image.</param>
        /// <param name="type">Image Type (primary, backdrop, logo, etc).</param>
        /// <response code="200">Image stream retrieved.</response>
        /// <response code="404">Image not found.</response>
        /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
        [HttpGet("General/{name}/{type}")]
        [AllowAnonymous]
        [Produces(MediaTypeNames.Application.Octet)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult<FileStreamResult> GetGeneralImage([FromRoute] string name, [FromRoute] string type)
        {
            var filename = string.Equals(type, "primary", StringComparison.OrdinalIgnoreCase)
                ? "folder"
                : type;

            var path = BaseItem.SupportedImageExtensions
                .Select(i => Path.Combine(_applicationPaths.GeneralPath, name, filename + i))
                .FirstOrDefault(System.IO.File.Exists);

            if (path == null)
            {
                return NotFound();
            }

            var contentType = MimeTypes.GetMimeType(path);
            return File(System.IO.File.OpenRead(path), contentType);
        }

        /// <summary>
        ///     Get all general images.
        /// </summary>
        /// <response code="200">Retrieved list of images.</response>
        /// <returns>An <see cref="OkResult"/> containing the list of images.</returns>
        [HttpGet("Ratings")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult<IEnumerable<ImageByNameInfo>> GetRatingImages()
        {
            return GetImageList(_applicationPaths.RatingsPath, false);
        }

        /// <summary>
        ///     Get rating image.
        /// </summary>
        /// <param name="theme">The theme to get the image from.</param>
        /// <param name="name">The name of the image.</param>
        /// <response code="200">Image stream retrieved.</response>
        /// <response code="404">Image not found.</response>
        /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
        [HttpGet("Ratings/{theme}/{name}")]
        [AllowAnonymous]
        [Produces(MediaTypeNames.Application.Octet)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult<FileStreamResult> GetRatingImage(
            [FromRoute] string theme,
            [FromRoute] string name)
        {
            return GetImageFile(_applicationPaths.RatingsPath, theme, name);
        }

        /// <summary>
        ///     Get all media info images.
        /// </summary>
        /// <response code="200">Image list retrieved.</response>
        /// <returns>An <see cref="OkResult"/> containing the list of images.</returns>
        [HttpGet("MediaInfo")]
        [Authorize]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult<IEnumerable<ImageByNameInfo>> GetMediaInfoImages()
        {
            return GetImageList(_applicationPaths.MediaInfoImagesPath, false);
        }

        /// <summary>
        ///     Get media info image.
        /// </summary>
        /// <param name="theme">The theme to get the image from.</param>
        /// <param name="name">The name of the image.</param>
        /// <response code="200">Image stream retrieved.</response>
        /// <response code="404">Image not found.</response>
        /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
        [HttpGet("MediaInfo/{theme}/{name}")]
        [AllowAnonymous]
        [Produces(MediaTypeNames.Application.Octet)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult<FileStreamResult> GetMediaInfoImage(
            [FromRoute] string theme,
            [FromRoute] string name)
        {
            return GetImageFile(_applicationPaths.MediaInfoImagesPath, theme, name);
        }

        /// <summary>
        ///     Internal FileHelper.
        /// </summary>
        /// <param name="basePath">Path to begin search.</param>
        /// <param name="theme">Theme to search.</param>
        /// <param name="name">File name to search for.</param>
        /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns>
        private ActionResult<FileStreamResult> GetImageFile(string basePath, string theme, string name)
        {
            var themeFolder = Path.Combine(basePath, theme);
            if (Directory.Exists(themeFolder))
            {
                var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(themeFolder, name + i))
                    .FirstOrDefault(System.IO.File.Exists);

                if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
                {
                    var contentType = MimeTypes.GetMimeType(path);
                    return File(System.IO.File.OpenRead(path), contentType);
                }
            }

            var allFolder = Path.Combine(basePath, "all");
            if (Directory.Exists(allFolder))
            {
                var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(allFolder, name + i))
                    .FirstOrDefault(System.IO.File.Exists);

                if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
                {
                    var contentType = MimeTypes.GetMimeType(path);
                    return File(System.IO.File.OpenRead(path), contentType);
                }
            }

            return NotFound();
        }

        private List<ImageByNameInfo> GetImageList(string path, bool supportsThemes)
        {
            try
            {
                return _fileSystem.GetFiles(path, BaseItem.SupportedImageExtensions, false, true)
                    .Select(i => new ImageByNameInfo
                    {
                        Name = _fileSystem.GetFileNameWithoutExtension(i),
                        FileLength = i.Length,

                        // For themeable images, use the Theme property
                        // For general images, the same object structure is fine,
                        // but it's not owned by a theme, so call it Context
                        Theme = supportsThemes ? GetThemeName(i.FullName, path) : null,
                        Context = supportsThemes ? null : GetThemeName(i.FullName, path),
                        Format = i.Extension.ToLowerInvariant().TrimStart('.')
                    })
                    .OrderBy(i => i.Name)
                    .ToList();
            }
            catch (IOException)
            {
                return new List<ImageByNameInfo>();
            }
        }

        private string? GetThemeName(string path, string rootImagePath)
        {
            var parentName = Path.GetDirectoryName(path);

            if (string.Equals(parentName, rootImagePath, StringComparison.OrdinalIgnoreCase))
            {
                return null;
            }

            parentName = Path.GetFileName(parentName);

            return string.Equals(parentName, "all", StringComparison.OrdinalIgnoreCase) ? null : parentName;
        }
    }
}