aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Api/HttpHandlers/UpdateMediaLibraryHandler.cs
blob: e5c42008e12c09ef4b233a17de606e70a2584a68 (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
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net.Handlers;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MediaBrowser.Api.HttpHandlers
{
    /// <summary>
    /// Makes changes to the user's media library
    /// </summary>
    [Export(typeof(IHttpServerHandler))]
    public class UpdateMediaLibraryHandler : BaseActionHandler<Kernel>
    {
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <returns>Task.</returns>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override Task ExecuteAction()
        {
            return Task.Run(() =>
            {
                var action = QueryString["action"];

                if (string.IsNullOrEmpty(action))
                {
                    throw new ArgumentNullException();
                }

                User user = null;

                if (!string.IsNullOrEmpty(QueryString["userId"]))
                {
                    user = ApiService.GetUserById(QueryString["userId"]);
                }

                if (action.Equals("AddVirtualFolder", StringComparison.OrdinalIgnoreCase))
                {
                    AddVirtualFolder(Uri.UnescapeDataString(QueryString["name"]), user);
                }

                if (action.Equals("RemoveVirtualFolder", StringComparison.OrdinalIgnoreCase))
                {
                    RemoveVirtualFolder(QueryString["name"], user);
                }

                if (action.Equals("RenameVirtualFolder", StringComparison.OrdinalIgnoreCase))
                {
                    RenameVirtualFolder(QueryString["name"], QueryString["newName"], user);
                }

                if (action.Equals("RemoveMediaPath", StringComparison.OrdinalIgnoreCase))
                {
                    RemoveMediaPath(QueryString["virtualFolderName"], QueryString["mediaPath"], user);
                }

                if (action.Equals("AddMediaPath", StringComparison.OrdinalIgnoreCase))
                {
                    AddMediaPath(QueryString["virtualFolderName"], QueryString["mediaPath"], user);
                }

                throw new ArgumentOutOfRangeException();
            });
        }

        /// <summary>
        /// Adds a virtual folder to either the default view or a user view
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="user">The user.</param>
        private void AddVirtualFolder(string name, User user)
        {
            name = FileSystem.GetValidFilename(name);

            var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, name);

            if (Directory.Exists(virtualFolderPath))
            {
                throw new ArgumentException("There is already a media collection with the name " + name + ".");
            }

            Directory.CreateDirectory(virtualFolderPath);
        }

        /// <summary>
        /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="user">The user.</param>
        private void AddMediaPath(string virtualFolderName, string path, User user)
        {
            if (!Path.IsPathRooted(path))
            {
                throw new ArgumentException("The path is not valid.");
            }

            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException("The path does not exist.");
            }

            // Strip off trailing slash, but not on drives
            path = path.TrimEnd(Path.DirectorySeparatorChar);
            if (path.EndsWith(":", StringComparison.OrdinalIgnoreCase))
            {
                path += Path.DirectorySeparatorChar;
            }

            var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);

            ValidateNewMediaPath(rootFolderPath, path);

            var shortcutFilename = Path.GetFileNameWithoutExtension(path);

            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ".lnk");

            while (File.Exists(lnk))
            {
                shortcutFilename += "1";
                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ".lnk");
            }

            FileSystem.CreateShortcut(lnk, path);
        }

        /// <summary>
        /// Validates that a new media path can be added
        /// </summary>
        /// <param name="currentViewRootFolderPath">The current view root folder path.</param>
        /// <param name="mediaPath">The media path.</param>
        private void ValidateNewMediaPath(string currentViewRootFolderPath, string mediaPath)
        {
            var duplicate = Directory.EnumerateFiles(Kernel.ApplicationPaths.RootFolderPath, "*.lnk", SearchOption.AllDirectories)
                .Select(FileSystem.ResolveShortcut)
                .FirstOrDefault(p => !IsNewPathValid(mediaPath, p));

            if (!string.IsNullOrEmpty(duplicate))
            {
                throw new ArgumentException(string.Format("The path cannot be added to the library because {0} already exists.", duplicate));
            }

            // Make sure the current root folder doesn't already have a shortcut to the same path
            duplicate = Directory.EnumerateFiles(currentViewRootFolderPath, "*.lnk", SearchOption.AllDirectories)
                .Select(FileSystem.ResolveShortcut)
                .FirstOrDefault(p => mediaPath.Equals(p, StringComparison.OrdinalIgnoreCase));

            if (!string.IsNullOrEmpty(duplicate))
            {
                throw new ArgumentException(string.Format("The path {0} already exists in the library", mediaPath));
            }
        }

        /// <summary>
        /// Validates that a new path can be added based on an existing path
        /// </summary>
        /// <param name="newPath">The new path.</param>
        /// <param name="existingPath">The existing path.</param>
        /// <returns><c>true</c> if [is new path valid] [the specified new path]; otherwise, <c>false</c>.</returns>
        private bool IsNewPathValid(string newPath, string existingPath)
        {
            // Example: D:\Movies is the existing path
            // D:\ cannot be added
            // Neither can D:\Movies\Kids
            // A D:\Movies duplicate is ok here since that will be caught later

            if (newPath.Equals(existingPath, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            // Validate the D:\Movies\Kids scenario
            if (newPath.StartsWith(existingPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            // Validate the D:\ scenario
            if (existingPath.StartsWith(newPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Renames a virtual folder within either the default view or a user view
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="newName">The new name.</param>
        /// <param name="user">The user.</param>
        private void RenameVirtualFolder(string name, string newName, User user)
        {
            var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;

            var currentPath = Path.Combine(rootFolderPath, name);
            var newPath = Path.Combine(rootFolderPath, newName);

            if (!Directory.Exists(currentPath))
            {
                throw new DirectoryNotFoundException("The media collection does not exist");
            }

            if (Directory.Exists(newPath))
            {
                throw new ArgumentException("There is already a media collection with the name " + newPath + ".");
            }

            Directory.Move(currentPath, newPath);
        }

        /// <summary>
        /// Deletes a virtual folder from either the default view or a user view
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="user">The user.</param>
        private void RemoveVirtualFolder(string name, User user)
        {
            var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
            var path = Path.Combine(rootFolderPath, name);

            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException("The media folder does not exist");
            }

            Directory.Delete(path, true);
        }

        /// <summary>
        /// Deletes a shortcut from within a virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="mediaPath">The media path.</param>
        /// <param name="user">The user.</param>
        private void RemoveMediaPath(string virtualFolderName, string mediaPath, User user)
        {
            var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
            var path = Path.Combine(rootFolderPath, virtualFolderName);

            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException("The media folder does not exist");
            }

            var shortcut = Directory.EnumerateFiles(path, "*.lnk", SearchOption.AllDirectories).FirstOrDefault(f => FileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(shortcut))
            {
                throw new DirectoryNotFoundException("The media folder does not exist");
            }
            File.Delete(shortcut);
        }
    }
}