aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Controllers/EnvironmentController.cs
blob: e0713cf05456d36ea927e8ffc1b6a1fc8cc9530b (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
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Models.EnvironmentDtos;
using MediaBrowser.Common.Api;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.IO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Api.Controllers;

/// <summary>
/// Environment Controller.
/// </summary>
[Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
public class EnvironmentController : BaseJellyfinApiController
{
    private const char UncSeparator = '\\';
    private const string UncStartPrefix = @"\\";

    private readonly IFileSystem _fileSystem;
    private readonly ILogger<EnvironmentController> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="EnvironmentController"/> class.
    /// </summary>
    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
    /// <param name="logger">Instance of the <see cref="ILogger{EnvironmentController}"/> interface.</param>
    public EnvironmentController(IFileSystem fileSystem, ILogger<EnvironmentController> logger)
    {
        _fileSystem = fileSystem;
        _logger = logger;
    }

    /// <summary>
    /// Gets the contents of a given directory in the file system.
    /// </summary>
    /// <param name="path">The path.</param>
    /// <param name="includeFiles">An optional filter to include or exclude files from the results. true/false.</param>
    /// <param name="includeDirectories">An optional filter to include or exclude folders from the results. true/false.</param>
    /// <response code="200">Directory contents returned.</response>
    /// <returns>Directory contents.</returns>
    [HttpGet("DirectoryContents")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IEnumerable<FileSystemEntryInfo> GetDirectoryContents(
        [FromQuery, Required] string path,
        [FromQuery] bool includeFiles = false,
        [FromQuery] bool includeDirectories = false)
    {
        if (path.StartsWith(UncStartPrefix, StringComparison.OrdinalIgnoreCase)
            && path.LastIndexOf(UncSeparator) == 1)
        {
            return Array.Empty<FileSystemEntryInfo>();
        }

        var entries =
            _fileSystem.GetFileSystemEntries(path)
                .Where(i => (i.IsDirectory && includeDirectories) || (!i.IsDirectory && includeFiles))
                .OrderBy(i => i.FullName);

        return entries.Select(f => new FileSystemEntryInfo(f.Name, f.FullName, f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File));
    }

    /// <summary>
    /// Validates path.
    /// </summary>
    /// <param name="validatePathDto">Validate request object.</param>
    /// <response code="204">Path validated.</response>
    /// <response code="404">Path not found.</response>
    /// <returns>Validation status.</returns>
    [HttpPost("ValidatePath")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult ValidatePath([FromBody, Required] ValidatePathDto validatePathDto)
    {
        if (validatePathDto.IsFile.HasValue)
        {
            if (validatePathDto.IsFile.Value)
            {
                if (!System.IO.File.Exists(validatePathDto.Path))
                {
                    return NotFound();
                }
            }
            else
            {
                if (!Directory.Exists(validatePathDto.Path))
                {
                    return NotFound();
                }
            }
        }
        else
        {
            if (!System.IO.File.Exists(validatePathDto.Path) && !Directory.Exists(validatePathDto.Path))
            {
                return NotFound();
            }

            if (validatePathDto.ValidateWritable)
            {
                if (validatePathDto.Path is null)
                {
                    throw new ResourceNotFoundException(nameof(validatePathDto.Path));
                }

                var file = Path.Combine(validatePathDto.Path, Guid.NewGuid().ToString());
                try
                {
                    System.IO.File.WriteAllText(file, string.Empty);
                }
                finally
                {
                    if (System.IO.File.Exists(file))
                    {
                        System.IO.File.Delete(file);
                    }
                }
            }
        }

        return NoContent();
    }

    /// <summary>
    /// Gets network paths.
    /// </summary>
    /// <response code="200">Empty array returned.</response>
    /// <returns>List of entries.</returns>
    [Obsolete("This endpoint is obsolete.")]
    [HttpGet("NetworkShares")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult<IEnumerable<FileSystemEntryInfo>> GetNetworkShares()
    {
        _logger.LogWarning("Obsolete endpoint accessed: /Environment/NetworkShares");
        return Array.Empty<FileSystemEntryInfo>();
    }

    /// <summary>
    /// Gets available drives from the server's file system.
    /// </summary>
    /// <response code="200">List of entries returned.</response>
    /// <returns>List of entries.</returns>
    [HttpGet("Drives")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IEnumerable<FileSystemEntryInfo> GetDrives()
    {
        return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo(d.Name, d.FullName, FileSystemEntryType.Directory));
    }

    /// <summary>
    /// Gets the parent path of a given path.
    /// </summary>
    /// <param name="path">The path.</param>
    /// <returns>Parent path.</returns>
    [HttpGet("ParentPath")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult<string?> GetParentPath([FromQuery, Required] string path)
    {
        string? parent = Path.GetDirectoryName(path);
        if (string.IsNullOrEmpty(parent))
        {
            // Check if unc share
            var index = path.LastIndexOf(UncSeparator);

            if (index != -1 && path.IndexOf(UncSeparator, StringComparison.OrdinalIgnoreCase) == 0)
            {
                parent = path.Substring(0, index);

                if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
                {
                    parent = null;
                }
            }
        }

        return parent;
    }

    /// <summary>
    /// Get Default directory browser.
    /// </summary>
    /// <response code="200">Default directory browser returned.</response>
    /// <returns>Default directory browser.</returns>
    [HttpGet("DefaultDirectoryBrowser")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult<DefaultDirectoryBrowserInfoDto> GetDefaultDirectoryBrowser()
    {
        return new DefaultDirectoryBrowserInfoDto();
    }
}