2
0

UpdateMediaLibraryHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net.Handlers;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Entities;
  5. using System;
  6. using System.ComponentModel.Composition;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Api.HttpHandlers
  11. {
  12. /// <summary>
  13. /// Makes changes to the user's media library
  14. /// </summary>
  15. [Export(typeof(IHttpServerHandler))]
  16. public class UpdateMediaLibraryHandler : BaseActionHandler<Kernel>
  17. {
  18. /// <summary>
  19. /// Executes the action.
  20. /// </summary>
  21. /// <returns>Task.</returns>
  22. /// <exception cref="System.NotImplementedException"></exception>
  23. protected override Task ExecuteAction()
  24. {
  25. return Task.Run(() =>
  26. {
  27. var action = QueryString["action"];
  28. if (string.IsNullOrEmpty(action))
  29. {
  30. throw new ArgumentNullException();
  31. }
  32. User user = null;
  33. if (!string.IsNullOrEmpty(QueryString["userId"]))
  34. {
  35. user = ApiService.GetUserById(QueryString["userId"]);
  36. }
  37. if (action.Equals("AddVirtualFolder", StringComparison.OrdinalIgnoreCase))
  38. {
  39. AddVirtualFolder(Uri.UnescapeDataString(QueryString["name"]), user);
  40. }
  41. if (action.Equals("RemoveVirtualFolder", StringComparison.OrdinalIgnoreCase))
  42. {
  43. RemoveVirtualFolder(QueryString["name"], user);
  44. }
  45. if (action.Equals("RenameVirtualFolder", StringComparison.OrdinalIgnoreCase))
  46. {
  47. RenameVirtualFolder(QueryString["name"], QueryString["newName"], user);
  48. }
  49. if (action.Equals("RemoveMediaPath", StringComparison.OrdinalIgnoreCase))
  50. {
  51. RemoveMediaPath(QueryString["virtualFolderName"], QueryString["mediaPath"], user);
  52. }
  53. if (action.Equals("AddMediaPath", StringComparison.OrdinalIgnoreCase))
  54. {
  55. AddMediaPath(QueryString["virtualFolderName"], QueryString["mediaPath"], user);
  56. }
  57. throw new ArgumentOutOfRangeException();
  58. });
  59. }
  60. /// <summary>
  61. /// Adds a virtual folder to either the default view or a user view
  62. /// </summary>
  63. /// <param name="name">The name.</param>
  64. /// <param name="user">The user.</param>
  65. private void AddVirtualFolder(string name, User user)
  66. {
  67. name = FileSystem.GetValidFilename(name);
  68. var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
  69. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  70. if (Directory.Exists(virtualFolderPath))
  71. {
  72. throw new ArgumentException("There is already a media collection with the name " + name + ".");
  73. }
  74. Directory.CreateDirectory(virtualFolderPath);
  75. }
  76. /// <summary>
  77. /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
  78. /// </summary>
  79. /// <param name="virtualFolderName">Name of the virtual folder.</param>
  80. /// <param name="path">The path.</param>
  81. /// <param name="user">The user.</param>
  82. private void AddMediaPath(string virtualFolderName, string path, User user)
  83. {
  84. if (!Path.IsPathRooted(path))
  85. {
  86. throw new ArgumentException("The path is not valid.");
  87. }
  88. if (!Directory.Exists(path))
  89. {
  90. throw new DirectoryNotFoundException("The path does not exist.");
  91. }
  92. // Strip off trailing slash, but not on drives
  93. path = path.TrimEnd(Path.DirectorySeparatorChar);
  94. if (path.EndsWith(":", StringComparison.OrdinalIgnoreCase))
  95. {
  96. path += Path.DirectorySeparatorChar;
  97. }
  98. var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
  99. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  100. ValidateNewMediaPath(rootFolderPath, path);
  101. var shortcutFilename = Path.GetFileNameWithoutExtension(path);
  102. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ".lnk");
  103. while (File.Exists(lnk))
  104. {
  105. shortcutFilename += "1";
  106. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ".lnk");
  107. }
  108. FileSystem.CreateShortcut(lnk, path);
  109. }
  110. /// <summary>
  111. /// Validates that a new media path can be added
  112. /// </summary>
  113. /// <param name="currentViewRootFolderPath">The current view root folder path.</param>
  114. /// <param name="mediaPath">The media path.</param>
  115. private void ValidateNewMediaPath(string currentViewRootFolderPath, string mediaPath)
  116. {
  117. var duplicate = Directory.EnumerateFiles(Kernel.ApplicationPaths.RootFolderPath, "*.lnk", SearchOption.AllDirectories)
  118. .Select(FileSystem.ResolveShortcut)
  119. .FirstOrDefault(p => !IsNewPathValid(mediaPath, p));
  120. if (!string.IsNullOrEmpty(duplicate))
  121. {
  122. throw new ArgumentException(string.Format("The path cannot be added to the library because {0} already exists.", duplicate));
  123. }
  124. // Make sure the current root folder doesn't already have a shortcut to the same path
  125. duplicate = Directory.EnumerateFiles(currentViewRootFolderPath, "*.lnk", SearchOption.AllDirectories)
  126. .Select(FileSystem.ResolveShortcut)
  127. .FirstOrDefault(p => mediaPath.Equals(p, StringComparison.OrdinalIgnoreCase));
  128. if (!string.IsNullOrEmpty(duplicate))
  129. {
  130. throw new ArgumentException(string.Format("The path {0} already exists in the library", mediaPath));
  131. }
  132. }
  133. /// <summary>
  134. /// Validates that a new path can be added based on an existing path
  135. /// </summary>
  136. /// <param name="newPath">The new path.</param>
  137. /// <param name="existingPath">The existing path.</param>
  138. /// <returns><c>true</c> if [is new path valid] [the specified new path]; otherwise, <c>false</c>.</returns>
  139. private bool IsNewPathValid(string newPath, string existingPath)
  140. {
  141. // Example: D:\Movies is the existing path
  142. // D:\ cannot be added
  143. // Neither can D:\Movies\Kids
  144. // A D:\Movies duplicate is ok here since that will be caught later
  145. if (newPath.Equals(existingPath, StringComparison.OrdinalIgnoreCase))
  146. {
  147. return true;
  148. }
  149. // Validate the D:\Movies\Kids scenario
  150. if (newPath.StartsWith(existingPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
  151. {
  152. return false;
  153. }
  154. // Validate the D:\ scenario
  155. if (existingPath.StartsWith(newPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
  156. {
  157. return false;
  158. }
  159. return true;
  160. }
  161. /// <summary>
  162. /// Renames a virtual folder within either the default view or a user view
  163. /// </summary>
  164. /// <param name="name">The name.</param>
  165. /// <param name="newName">The new name.</param>
  166. /// <param name="user">The user.</param>
  167. private void RenameVirtualFolder(string name, string newName, User user)
  168. {
  169. var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
  170. var currentPath = Path.Combine(rootFolderPath, name);
  171. var newPath = Path.Combine(rootFolderPath, newName);
  172. if (!Directory.Exists(currentPath))
  173. {
  174. throw new DirectoryNotFoundException("The media collection does not exist");
  175. }
  176. if (Directory.Exists(newPath))
  177. {
  178. throw new ArgumentException("There is already a media collection with the name " + newPath + ".");
  179. }
  180. Directory.Move(currentPath, newPath);
  181. }
  182. /// <summary>
  183. /// Deletes a virtual folder from either the default view or a user view
  184. /// </summary>
  185. /// <param name="name">The name.</param>
  186. /// <param name="user">The user.</param>
  187. private void RemoveVirtualFolder(string name, User user)
  188. {
  189. var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
  190. var path = Path.Combine(rootFolderPath, name);
  191. if (!Directory.Exists(path))
  192. {
  193. throw new DirectoryNotFoundException("The media folder does not exist");
  194. }
  195. Directory.Delete(path, true);
  196. }
  197. /// <summary>
  198. /// Deletes a shortcut from within a virtual folder, within either the default view or a user view
  199. /// </summary>
  200. /// <param name="virtualFolderName">Name of the virtual folder.</param>
  201. /// <param name="mediaPath">The media path.</param>
  202. /// <param name="user">The user.</param>
  203. private void RemoveMediaPath(string virtualFolderName, string mediaPath, User user)
  204. {
  205. var rootFolderPath = user != null ? user.RootFolderPath : Kernel.ApplicationPaths.DefaultUserViewsPath;
  206. var path = Path.Combine(rootFolderPath, virtualFolderName);
  207. if (!Directory.Exists(path))
  208. {
  209. throw new DirectoryNotFoundException("The media folder does not exist");
  210. }
  211. var shortcut = Directory.EnumerateFiles(path, "*.lnk", SearchOption.AllDirectories).FirstOrDefault(f => FileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  212. if (string.IsNullOrEmpty(shortcut))
  213. {
  214. throw new DirectoryNotFoundException("The media folder does not exist");
  215. }
  216. File.Delete(shortcut);
  217. }
  218. }
  219. }