/// <summary> /// Extension method which is added on <see cref="IEnumerable{Share}"/> to find that share in the given enumeration /// which best matches the given <paramref name="path"/>. /// </summary> /// <remarks> /// If there are shares where one share path contains the path of another share in the given <paramref name="shares"/> enumeration, /// the algorithm will always find the share whose path is as close to the given <paramref name="path"/>. If more than one share match best, /// the first best matching share is returned. /// </remarks> /// <param name="shares">Enumeration of shares to search through.</param> /// <param name="path">Path to find a share for.</param> /// <returns>Share which best matches the given <paramref name="path"/>, if one exists. Else, <c>null</c> will be returned.</returns> public static Share BestContainingPath(this IEnumerable <Share> shares, ResourcePath path) { if (path == null) { return(null); } int bestMatchPathLength = int.MaxValue; Share bestMatchShare = null; foreach (Share share in shares) { ResourcePath currentSharePath = share.BaseResourcePath; if (!currentSharePath.IsSameOrParentOf(path)) { // The path is not located in the current share continue; } if (bestMatchShare == null) { bestMatchShare = share; bestMatchPathLength = currentSharePath.Serialize().Length; continue; } // We want to find a share which is as close as possible to the given path int currentSharePathLength = currentSharePath.Serialize().Length; if (bestMatchPathLength >= currentSharePathLength) { continue; } bestMatchShare = share; bestMatchPathLength = currentSharePathLength; } return(bestMatchShare); }
public void ImportLocation(ResourcePath path, IEnumerable <string> mediaCategories, ImportJobType importJobType) { CpAction action = GetAction("ImportLocation"); string importJobTypeStr; switch (importJobType) { case ImportJobType.Import: importJobTypeStr = "Import"; break; case ImportJobType.Refresh: importJobTypeStr = "Refresh"; break; default: throw new NotImplementedException(string.Format("Import job type '{0}' is not implemented", importJobType)); } IList <object> inParameters = new List <object> { path.Serialize(), StringUtils.Join(", ", mediaCategories), importJobTypeStr }; action.InvokeAction(inParameters); }
public int UpdateShare(Guid shareId, ResourcePath baseResourcePath, string shareName, IEnumerable <string> mediaCategories, RelocationMode relocationMode) { CpAction action = GetAction("UpdateShare"); IList <object> inParameters = new List <object> { MarshallingHelper.SerializeGuid(shareId), baseResourcePath.Serialize(), shareName, StringUtils.Join(",", mediaCategories) }; string relocationModeStr; switch (relocationMode) { case RelocationMode.Relocate: relocationModeStr = "Relocate"; break; case RelocationMode.ClearAndReImport: relocationModeStr = "ClearAndReImport"; break; case RelocationMode.None: relocationModeStr = "None"; break; default: throw new NotImplementedException(string.Format("RelocationMode '{0}' is not implemented", relocationMode)); } inParameters.Add(relocationModeStr); IList <object> outParameters = action.InvokeAction(inParameters); return((int)outParameters[0]); }
public string GetResourceDisplayName(ResourcePath path) { CpAction action = GetAction("GetResourceDisplayName"); IList<object> inParameters = new List<object> {path.Serialize()}; IList<object> outParameters = action.InvokeAction(inParameters); return (string) outParameters[0]; }
protected IFileSystemResourceAccessor GetResourceAccessor(ResourcePath resourcePath) { lock (_syncObj) { CachedResource resource; string resourcePathStr = resourcePath.Serialize(); if (_resourceAccessorCache.TryGetValue(resourcePathStr, out resource)) { return(resource.ResourceAccessor); } // TODO: Security check. Only deliver resources which are located inside local shares. ServiceRegistration.Get <ILogger>().Debug("ResourceAccessModule: Access of resource '{0}'", resourcePathStr); IResourceAccessor ra; if (!resourcePath.TryCreateLocalResourceAccessor(out ra)) { throw new ArgumentException("Unable to access resource path '{0}'", resourcePathStr); } IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor; if (fsra == null) { ra.Dispose(); throw new ArgumentException("The given resource path '{0}' doesn't denote a file system resource", resourcePathStr); } _resourceAccessorCache[resourcePathStr] = new CachedResource(fsra); return(fsra); } }
public async Task DeleteMediaItemOrPathAsync(string systemId, ResourcePath path, bool inclusive) { CpAction action = GetAction("X_MediaPortal_DeleteMediaItemOrPath"); IList <object> inParameters = new List <object> { systemId, path.Serialize(), inclusive }; await action.InvokeAsync(inParameters); }
public void DeleteMediaItemOrPath(string systemId, ResourcePath path, bool inclusive) { CpAction action = GetAction("DeleteMediaItemOrPath"); IList <object> inParameters = new List <object> { systemId, path.Serialize(), inclusive }; action.InvokeAction(inParameters); }
public bool DoesResourceExist(ResourcePath path) { CpAction action = GetAction("DoesResourceExist"); IList <object> inParameters = new List <object> { path.Serialize() }; IList <object> outParameters = action.InvokeAction(inParameters); return((bool)outParameters[0]); }
public string GetResourceDisplayName(ResourcePath path) { CpAction action = GetAction("GetResourceDisplayName"); IList <object> inParameters = new List <object> { path.Serialize() }; IList <object> outParameters = action.InvokeAction(inParameters); return((string)outParameters[0]); }
public ICollection <ResourcePathMetadata> GetChildDirectoriesData(ResourcePath path) { CpAction action = GetAction("GetChildDirectoriesData"); IList <object> inParameters = new List <object> { path.Serialize() }; IList <object> outParameters = action.InvokeAction(inParameters); return((ICollection <ResourcePathMetadata>)outParameters[0]); }
public ResourcePath ConcatenatePaths(ResourcePath basePath, string relativePath) { CpAction action = GetAction("ConcatenatePaths"); IList <object> inParameters = new List <object> { basePath.Serialize(), relativePath }; IList <object> outParameters = action.InvokeAction(inParameters); return(ResourcePath.Deserialize((string)outParameters[0])); }
public async Task<MediaItem> LoadItemAsync(string systemId, ResourcePath path, IEnumerable<Guid> necessaryMIATypes, IEnumerable<Guid> optionalMIATypes, Guid? userProfile) { CpAction action = GetAction("X_MediaPortal_LoadItem"); IList<object> inParameters = new List<object> {systemId, path.Serialize(), MarshallingHelper.SerializeGuidEnumerationToCsv(necessaryMIATypes), MarshallingHelper.SerializeGuidEnumerationToCsv(optionalMIATypes), userProfile.HasValue ? MarshallingHelper.SerializeGuid(userProfile.Value) : null }; IList<object> outParameters = await action.InvokeAsync(inParameters); return (MediaItem) outParameters[0]; }
public MediaItem LoadItem(string systemId, ResourcePath path, IEnumerable <Guid> necessaryMIATypes, IEnumerable <Guid> optionalMIATypes) { CpAction action = GetAction("LoadItem"); IList <object> inParameters = new List <object> { systemId, path.Serialize(), MarshallingHelper.SerializeGuidEnumerationToCsv(necessaryMIATypes), MarshallingHelper.SerializeGuidEnumerationToCsv(optionalMIATypes) }; IList <object> outParameters = action.InvokeAction(inParameters); return((MediaItem)outParameters[0]); }
public string CreateRootDirectory(string rootDirectoryName) { lock (_syncObj) { ResourcePath rootPath = RootPath; if (rootPath == null) { return(null); } _dokanExecutor.RootDirectory.AddResource(rootDirectoryName, new VirtualRootDirectory(rootDirectoryName)); return(ResourcePathHelper.Combine(rootPath.Serialize(), rootDirectoryName)); } }
public async Task<Guid> AddOrUpdateMediaItemAsync(Guid parentDirectoryId, string systemId, ResourcePath path, IEnumerable<MediaItemAspect> mediaItemAspects) { CpAction action = GetAction("X_MediaPortal_AddOrUpdateMediaItem"); IList<object> inParameters = new List<object> { MarshallingHelper.SerializeGuid(parentDirectoryId), systemId, path.Serialize(), mediaItemAspects }; IList<object> outParameters = await action.InvokeAsync(inParameters); return MarshallingHelper.DeserializeGuid((string) outParameters[0]); }
public static IDbCommand SelectShareIdCommand(ITransaction transaction, string systemId, ResourcePath baseResourcePath, out int shareIdIndex) { IDbCommand result = transaction.CreateCommand(); result.CommandText = "SELECT SHARE_ID FROM SHARES WHERE SYSTEM_ID=@SYSTEM_ID AND BASE_RESOURCE_PATH=@BASE_RESOURCE_PATH"; ISQLDatabase database = transaction.Database; database.AddParameter(result, "SYSTEM_ID", systemId, typeof(string)); database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string)); shareIdIndex = 0; return(result); }
public static IDbCommand InsertShareCommand(ITransaction transaction, Guid shareId, string systemId, ResourcePath baseResourcePath, string shareName) { IDbCommand result = transaction.CreateCommand(); result.CommandText = "INSERT INTO SHARES (SHARE_ID, NAME, SYSTEM_ID, BASE_RESOURCE_PATH) VALUES (@SHARE_ID, @NAME, @SYSTEM_ID, @BASE_RESOURCE_PATH)"; ISQLDatabase database = transaction.Database; database.AddParameter(result, "SHARE_ID", shareId, typeof(Guid)); database.AddParameter(result, "NAME", shareName, typeof(string)); database.AddParameter(result, "SYSTEM_ID", systemId, typeof(string)); database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string)); return(result); }
public static IDbCommand UpdateShareCommand(ITransaction transaction, Guid shareId, ResourcePath baseResourcePath, string shareName) { IDbCommand result = transaction.CreateCommand(); result.CommandText = "UPDATE SHARES set NAME=@NAME, BASE_RESOURCE_PATH=@BASE_RESOURCE_PATH WHERE SHARE_ID=@SHARE_ID"; ISQLDatabase database = transaction.Database; database.AddParameter(result, "NAME", shareName, typeof(string)); database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string)); database.AddParameter(result, "SHARE_ID", shareId, typeof(Guid)); return(result); }
private DateTime _dateOfLastImport; // only valid for refresh imports #endregion #region Constructor public PendingImportResourceNewGen(ResourcePath parentDirectory, IFileSystemResourceAccessor resourceAccessor, String currentBlock, ImportJobController parentImportJobController, Guid?parentDirectoryId = null, Guid?mediaItemId = null) { _parentDirectoryId = parentDirectoryId; _mediaItemId = mediaItemId; _parentDirectoryResourcePathString = (parentDirectory == null) ? "" : parentDirectory.Serialize(); _resourceAccessor = resourceAccessor; _currentBlock = currentBlock; _parentImportJobController = parentImportJobController; _pendingImportResourceNumber = _parentImportJobController.GetNumberOfNextPendingImportResource(); _isValid = (_resourceAccessor != null); _parentImportJobController.RegisterPendingImportResource(this); }
static UPnPError OnExpandResourcePathFromString(DvAction action, IList <object> inParams, out IList <object> outParams, CallContext context) { Guid resourceProviderId = MarshallingHelper.DeserializeGuid((string)inParams[0]); string pathStr = (string)inParams[1]; IMediaAccessor mediaAccessor = ServiceRegistration.Get <IMediaAccessor>(); ResourcePath result = null; IResourceProvider rp; if (mediaAccessor.LocalResourceProviders.TryGetValue(resourceProviderId, out rp) && rp is IBaseResourceProvider) { result = ((IBaseResourceProvider)rp).ExpandResourcePathFromString(pathStr); } outParams = new List <object> { result == null ? null : result.Serialize() }; return(null); }
public bool GetResourceInformation(ResourcePath path, out bool isFileSystemResource, out bool isFile, out string resourcePathName, out string resourceName, out DateTime lastChanged, out long size) { CpAction action = GetAction("GetResourceInformation"); IList <object> inParameters = new List <object> { path.Serialize() }; IList <object> outParameters = action.InvokeAction(inParameters); isFileSystemResource = (bool)outParameters[0]; isFile = (bool)outParameters[1]; resourcePathName = (string)outParameters[2]; resourceName = (string)outParameters[3]; lastChanged = (DateTime)outParameters[4]; size = (Int64)outParameters[5]; return((bool)outParameters[6]); }
protected IResourceAccessor GetResourceAccessor(ResourcePath resourcePath) { lock (_syncObj) { CachedResource resource; string resourcePathStr = resourcePath.Serialize(); if (_resourceAccessorCache.TryGetValue(resourcePathStr, out resource)) { return(resource.ResourceAccessor); } // TODO: Security check. Only deliver resources which are located inside local shares. ServiceRegistration.Get <ILogger>().Debug("ResourceAccessModule: Access of resource '{0}'", resourcePathStr); IResourceAccessor result; if (!resourcePath.TryCreateLocalResourceAccessor(out result)) { throw new ArgumentException("Unable to access resource path '{0}'", resourcePathStr); } _resourceAccessorCache[resourcePathStr] = new CachedResource(result); return(result); } }
public void ImportLocation(ResourcePath path, IEnumerable<string> mediaCategories, ImportJobType importJobType) { CpAction action = GetAction("ImportLocation"); string importJobTypeStr; switch (importJobType) { case ImportJobType.Import: importJobTypeStr = "Import"; break; case ImportJobType.Refresh: importJobTypeStr = "Refresh"; break; default: throw new NotImplementedException(string.Format("Import job type '{0}' is not implemented", importJobType)); } IList<object> inParameters = new List<object> { path.Serialize(), StringUtils.Join(", ", mediaCategories), importJobTypeStr }; action.InvokeAction(inParameters); }
protected IResourceAccessor GetResourceAccessor(ResourcePath resourcePath) { lock (_syncObj) { CachedResource resource; string resourcePathStr = resourcePath.Serialize(); if (_resourceAccessorCache.TryGetValue(resourcePathStr, out resource)) return resource.ResourceAccessor; // TODO: Security check. Only deliver resources which are located inside local shares. ServiceRegistration.Get<ILogger>().Debug("ResourceAccessModule: Access of resource '{0}'", resourcePathStr); IResourceAccessor result; if(!resourcePath.TryCreateLocalResourceAccessor(out result)) ServiceRegistration.Get<ILogger>().Debug("ResourceAccessModule: Unable to access resource path '{0}'", resourcePathStr); _resourceAccessorCache[resourcePathStr] = new CachedResource(result); return result; } }
public Guid AddOrUpdateMediaItem(Guid parentDirectoryId, string systemId, ResourcePath path, IEnumerable<MediaItemAspect> mediaItemAspects) { CpAction action = GetAction("AddOrUpdateMediaItem"); IList<object> inParameters = new List<object> { MarshallingHelper.SerializeGuid(parentDirectoryId), systemId, path.Serialize(), mediaItemAspects }; IList<object> outParameters = action.InvokeAction(inParameters); return MarshallingHelper.DeserializeGuid((string) outParameters[0]); }
internal static string BuildProviderPath(string nativeSystemId, ResourcePath nativeResourcePath) { return(nativeSystemId + ":" + nativeResourcePath.Serialize()); }
protected Guid? GetMediaItemId(ITransaction transaction, string systemId, ResourcePath resourcePath) { string providerAspectTable = _miaManagement.GetMIATableName(ProviderResourceAspect.Metadata); string systemIdAttribute = _miaManagement.GetMIAAttributeColumnName(ProviderResourceAspect.ATTR_SYSTEM_ID); string pathAttribute = _miaManagement.GetMIAAttributeColumnName(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH); ISQLDatabase database = transaction.Database; using (IDbCommand command = transaction.CreateCommand()) { command.CommandText = "SELECT " + MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME + " FROM " + providerAspectTable + " WHERE " + systemIdAttribute + " = @SYSTEM_ID AND " + pathAttribute + " = @PATH"; database.AddParameter(command, "SYSTEM_ID", systemId, typeof(string)); database.AddParameter(command, "PATH", resourcePath.Serialize(), typeof(string)); using (IDataReader reader = command.ExecuteReader()) { if (!reader.Read()) return null; return database.ReadDBValue<Guid>(reader, 0); } } }
public ICollection<ResourcePathMetadata> GetFilesData(ResourcePath path) { CpAction action = GetAction("GetFilesData"); IList<object> inParameters = new List<object> {path.Serialize()}; IList<object> outParameters = action.InvokeAction(inParameters); return (ICollection<ResourcePathMetadata>) outParameters[0]; }
/// <summary> /// Imports or refreshes the directory with the specified <paramref name="directoryAccessor"/>. Sub directories will not /// be processed in this method. /// </summary> /// <param name="importJob">The import job being processed.</param> /// <param name="parentDirectoryId">Media item id of the parent directory, if present, else <see cref="Guid.Empty"/>.</param> /// <param name="directoryAccessor">Resource accessor for the directory to import.</param> /// <param name="metadataExtractors">Metadata extractors to apply on the resources.</param> /// <param name="mediaBrowsing">Callback interface to the media library for the refresh import type.</param> /// <param name="resultHandler">Callback to notify the import result.</param> /// <param name="mediaAccessor">Convenience reference to the media accessor.</param> /// <returns>Id of the directory's media item or <c>null</c>, if the given <paramref name="directoryAccessor"/> /// was imported as a media item or if an error occured. If <c>null</c> is returned, the directory import should be /// considered to be finished.</returns> protected Guid?ImportDirectory(ImportJob importJob, Guid parentDirectoryId, IFileSystemResourceAccessor directoryAccessor, ICollection <IMetadataExtractor> metadataExtractors, IMediaBrowsing mediaBrowsing, IImportResultHandler resultHandler, IMediaAccessor mediaAccessor) { ResourcePath currentDirectoryPath = directoryAccessor.CanonicalLocalResourcePath; try { ImporterWorkerMessaging.SendImportMessage(ImporterWorkerMessaging.MessageType.ImportStatus, currentDirectoryPath); if (ImportResource(importJob, directoryAccessor, parentDirectoryId, metadataExtractors, resultHandler, mediaAccessor)) { // The directory could be imported as a media item. // If the directory itself was identified as a normal media item, don't import its children. // Necessary for DVD directories, for example. return(null); } Guid directoryId = GetOrAddDirectory(importJob, directoryAccessor, parentDirectoryId, mediaBrowsing, resultHandler); IDictionary <string, MediaItem> path2Item = new Dictionary <string, MediaItem>(); if (importJob.JobType == ImportJobType.Refresh) { foreach (MediaItem mediaItem in mediaBrowsing.BrowseAsync(directoryId, IMPORTER_PROVIDER_MIA_ID_ENUMERATION, EMPTY_MIA_ID_ENUMERATION, null, false).Result) { IList <MultipleMediaItemAspect> providerResourceAspects; if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, ProviderResourceAspect.Metadata, out providerResourceAspects)) { path2Item[providerResourceAspects[0].GetAttributeValue <string>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH)] = mediaItem; } } } CheckImportStillRunning(importJob.State); ICollection <IFileSystemResourceAccessor> files = FileSystemResourceNavigator.GetFiles(directoryAccessor, false); if (files != null) { foreach (IFileSystemResourceAccessor fileAccessor in files) { using (fileAccessor) { // Add & update files ResourcePath currentFilePath = fileAccessor.CanonicalLocalResourcePath; string serializedFilePath = currentFilePath.Serialize(); try { SingleMediaItemAspect importerAspect; MediaItem mediaItem; if (importJob.JobType == ImportJobType.Refresh && path2Item.TryGetValue(serializedFilePath, out mediaItem) && MediaItemAspect.TryGetAspect(mediaItem.Aspects, ImporterAspect.Metadata, out importerAspect) && importerAspect.GetAttributeValue <DateTime>(ImporterAspect.ATTR_LAST_IMPORT_DATE) > fileAccessor.LastChanged) { // We can skip this file; it was imported after the last change time of the item path2Item.Remove(serializedFilePath); continue; } if (ImportResource(importJob, fileAccessor, directoryId, metadataExtractors, resultHandler, mediaAccessor)) { path2Item.Remove(serializedFilePath); } } catch (Exception e) { CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous ServiceRegistration.Get <ILogger>().Warn("ImporterWorker: Problem while importing resource '{0}'", e, serializedFilePath); importJob.State = ImportJobState.Erroneous; } CheckImportStillRunning(importJob.State); } } } if (importJob.JobType == ImportJobType.Refresh) { // Remove remaining (= non-present) files foreach (string pathStr in path2Item.Keys) { ResourcePath path = ResourcePath.Deserialize(pathStr); try { IResourceAccessor ra; if (!path.TryCreateLocalResourceAccessor(out ra)) { throw new IllegalCallException("Unable to access resource path '{0}'", importJob.BasePath); } using (ra) { IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor; if (fsra == null || !fsra.IsFile) { // Don't touch directories because they will be imported in a different call of ImportDirectory continue; } } } catch (IllegalCallException) { // This happens if the resource doesn't exist any more - we also catch missing directories here } // Delete all remaining items resultHandler.DeleteMediaItemAsync(path); CheckImportStillRunning(importJob.State); } } return(directoryId); } catch (ImportSuspendedException) { throw; } catch (ImportAbortException) { throw; } catch (UnauthorizedAccessException e) { // If the access to the file or folder was denied, simply continue with the others ServiceRegistration.Get <ILogger>().Warn("ImporterWorker: Problem accessing resource '{0}', continueing with one", e, currentDirectoryPath); } catch (Exception e) { CheckSuspended(e); // Throw ImportAbortException if suspended - will skip warning and tagging job as erroneous ServiceRegistration.Get <ILogger>().Warn("ImporterWorker: Problem while importing directory '{0}'", e, currentDirectoryPath); importJob.State = ImportJobState.Erroneous; } return(null); }
public int UpdateShare(Guid shareId, ResourcePath baseResourcePath, string shareName, IEnumerable<string> mediaCategories, RelocationMode relocationMode) { CpAction action = GetAction("UpdateShare"); IList<object> inParameters = new List<object> { MarshallingHelper.SerializeGuid(shareId), baseResourcePath.Serialize(), shareName, StringUtils.Join(",", mediaCategories) }; string relocationModeStr; switch (relocationMode) { case RelocationMode.Relocate: relocationModeStr = "Relocate"; break; case RelocationMode.ClearAndReImport: relocationModeStr = "ClearAndReImport"; break; case RelocationMode.None: relocationModeStr = "None"; break; default: throw new NotImplementedException(string.Format("RelocationMode '{0}' is not implemented", relocationMode)); } inParameters.Add(relocationModeStr); IList<object> outParameters = action.InvokeAction(inParameters); return (int) outParameters[0]; }
public ResourcePath ConcatenatePaths(ResourcePath basePath, string relativePath) { CpAction action = GetAction("ConcatenatePaths"); IList<object> inParameters = new List<object> {basePath.Serialize(), relativePath}; IList<object> outParameters = action.InvokeAction(inParameters); return ResourcePath.Deserialize((string) outParameters[0]); }
public static string GetResourceURL(string baseURL, ResourcePath nativeResourcePath) { // Use UrlEncode to encode also # sign, UrlPathEncode doesn't do this. return(string.Format("{0}?{1}={2}", baseURL, RESOURCE_PATH_ARGUMENT_NAME, HttpUtility.UrlEncode(nativeResourcePath.Serialize()))); }
public MediaItem LoadItem(string systemId, ResourcePath path, IEnumerable<Guid> necessaryMIATypes, IEnumerable<Guid> optionalMIATypes) { CpAction action = GetAction("LoadItem"); IList<object> inParameters = new List<object> {systemId, path.Serialize(), MarshallingHelper.SerializeGuidEnumerationToCsv(necessaryMIATypes), MarshallingHelper.SerializeGuidEnumerationToCsv(optionalMIATypes)}; IList<object> outParameters = action.InvokeAction(inParameters); return (MediaItem) outParameters[0]; }
public static ResourcePath Combine(ResourcePath rootPath, string path) { return ResourcePath.Deserialize(Combine(rootPath.Serialize(), path)); }
private DateTime _dateOfLastImport; // only valid for refresh imports #endregion #region Constructor public PendingImportResourceNewGen(ResourcePath parentDirectory, IFileSystemResourceAccessor resourceAccessor, String currentBlock, ImportJobController parentImportJobController, Guid? parentDirectoryId = null, Guid? mediaItemId = null) { _parentDirectoryId = parentDirectoryId; _mediaItemId = mediaItemId; _parentDirectoryResourcePathString = (parentDirectory == null) ? "" : parentDirectory.Serialize(); _resourceAccessor = resourceAccessor; _currentBlock = currentBlock; _parentImportJobController = parentImportJobController; _pendingImportResourceNumber = _parentImportJobController.GetNumberOfNextPendingImportResource(); _isValid = (_resourceAccessor != null); _parentImportJobController.RegisterPendingImportResource(this); }
public static string GetResourceURL(string baseURL, ResourcePath nativeResourcePath) { // Use UrlEncode to encode also # sign, UrlPathEncode doesn't do this. return string.Format("{0}?{1}={2}", baseURL, RESOURCE_PATH_ARGUMENT_NAME, HttpUtility.UrlEncode(nativeResourcePath.Serialize())); }
public override async Task <IEnumerable <MediaItem> > GetAllMediaItems() { IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory; if (cd == null) { return(new List <MediaItem>()); } UserProfile userProfile = null; IUserManagement userProfileDataManagement = ServiceRegistration.Get <IUserManagement>(); if (userProfileDataManagement != null && userProfileDataManagement.IsValidUser) { userProfile = userProfileDataManagement.CurrentUser; } MediaItemQuery query = new MediaItemQuery( _necessaryMIATypeIds, _optionalMIATypeIds, UserHelper.GetUserRestrictionFilter(_necessaryMIATypeIds, userProfile, new BooleanCombinationFilter(BooleanOperator.And, new IFilter[] { new RelationalFilter(ProviderResourceAspect.ATTR_SYSTEM_ID, RelationalOperator.EQ, _systemId), new LikeFilter(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, SqlUtils.LikeEscape(_basePath.Serialize(), '\\') + "%", '\\', true) }))); bool showVirtual = VirtualMediaHelper.ShowVirtualMedia(_necessaryMIATypeIds); return(await cd.SearchAsync(query, false, userProfile?.ProfileId, showVirtual)); }
public void DeleteMediaItemOrPath(string systemId, ResourcePath path, bool inclusive) { ISQLDatabase database = ServiceRegistration.Get<ISQLDatabase>(); ITransaction transaction = database.BeginTransaction(); try { DeleteAllMediaItemsUnderPath(transaction, systemId, path, inclusive); transaction.Commit(); } catch (Exception e) { ServiceRegistration.Get<ILogger>().Error("MediaLibrary: Error deleting media item(s) of system '{0}' in path '{1}'", e, systemId, path.Serialize()); transaction.Rollback(); throw; } }
public bool GetResourceInformation(ResourcePath path, out bool isFileSystemResource, out bool isFile, out string resourcePathName, out string resourceName, out DateTime lastChanged, out long size) { CpAction action = GetAction("GetResourceInformation"); IList<object> inParameters = new List<object> {path.Serialize()}; IList<object> outParameters = action.InvokeAction(inParameters); isFileSystemResource = (bool) outParameters[0]; isFile = (bool) outParameters[1]; resourcePathName = (string) outParameters[2]; resourceName = (string) outParameters[3]; lastChanged = (DateTime) outParameters[4]; size = (long) (UInt64) outParameters[5]; return (bool) outParameters[6]; }
public static IDbCommand SelectShareIdCommand(ITransaction transaction, string systemId, ResourcePath baseResourcePath, out int shareIdIndex) { IDbCommand result = transaction.CreateCommand(); result.CommandText = "SELECT SHARE_ID FROM SHARES WHERE SYSTEM_ID=@SYSTEM_ID AND BASE_RESOURCE_PATH=@BASE_RESOURCE_PATH"; ISQLDatabase database = transaction.Database; database.AddParameter(result, "SYSTEM_ID", systemId, typeof(string)); database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string)); shareIdIndex = 0; return result; }
protected int DeleteAllMediaItemsUnderPath(ITransaction transaction, string systemId, ResourcePath basePath, bool inclusive) { MediaItemAspectMetadata providerAspectMetadata = ProviderResourceAspect.Metadata; string providerAspectTable = _miaManagement.GetMIATableName(providerAspectMetadata); string systemIdAttribute = _miaManagement.GetMIAAttributeColumnName(ProviderResourceAspect.ATTR_SYSTEM_ID); string pathAttribute = _miaManagement.GetMIAAttributeColumnName(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH); string commandStr = "DELETE FROM " + MediaLibrary_SubSchema.MEDIA_ITEMS_TABLE_NAME + " WHERE " + MediaLibrary_SubSchema.MEDIA_ITEMS_ITEM_ID_COL_NAME + " IN (" + // TODO: Replace this inner select statement by a select statement generated from an appropriate item query "SELECT " + MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME + " FROM " + providerAspectTable + " WHERE " + systemIdAttribute + " = @SYSTEM_ID"; ISQLDatabase database = transaction.Database; using (IDbCommand command = transaction.CreateCommand()) { database.AddParameter(command, "SYSTEM_ID", systemId, typeof(string)); if (basePath != null) { commandStr += " AND ("; if (inclusive) commandStr += pathAttribute + " = @EXACT_PATH OR "; commandStr += pathAttribute + " LIKE @LIKE_PATH1 ESCAPE @LIKE_ESCAPE1 OR " + pathAttribute + " LIKE @LIKE_PATH2 ESCAPE @LIKE_ESCAPE2" + ")"; string path = StringUtils.RemoveSuffixIfPresent(basePath.Serialize(), "/"); string escapedPath = SqlUtils.LikeEscape(path, ESCAPE_CHAR); if (inclusive) { // The path itself database.AddParameter(command, "EXACT_PATH", path, typeof(string)); // Normal children and, if escapedPath ends with "/", the directory itself database.AddParameter(command, "LIKE_PATH1", escapedPath + "/%", typeof(string)); database.AddParameter(command, "LIKE_ESCAPE1", ESCAPE_CHAR, typeof(char)); } else { // Normal children, in any case excluding the escaped path, even if it is a directory which ends with "/" database.AddParameter(command, "LIKE_PATH1", escapedPath + "/_%", typeof(string)); database.AddParameter(command, "LIKE_ESCAPE1", ESCAPE_CHAR, typeof(char)); } // Chained children database.AddParameter(command, "LIKE_PATH2", escapedPath + ">_%", typeof(string)); database.AddParameter(command, "LIKE_ESCAPE2", ESCAPE_CHAR, typeof(char)); } commandStr = commandStr + ")"; command.CommandText = commandStr; return command.ExecuteNonQuery(); } }
public static IDbCommand InsertShareCommand(ITransaction transaction, Guid shareId, string systemId, ResourcePath baseResourcePath, string shareName) { IDbCommand result = transaction.CreateCommand(); result.CommandText = "INSERT INTO SHARES (SHARE_ID, NAME, SYSTEM_ID, BASE_RESOURCE_PATH) VALUES (@SHARE_ID, @NAME, @SYSTEM_ID, @BASE_RESOURCE_PATH)"; ISQLDatabase database = transaction.Database; database.AddParameter(result, "SHARE_ID", shareId, typeof(Guid)); database.AddParameter(result, "NAME", shareName, typeof(string)); database.AddParameter(result, "SYSTEM_ID", systemId, typeof(string)); database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string)); return result; }
public bool DoesResourceExist(ResourcePath path) { CpAction action = GetAction("DoesResourceExist"); IList<object> inParameters = new List<object> {path.Serialize()}; IList<object> outParameters = action.InvokeAction(inParameters); return (bool) outParameters[0]; }
public static IDbCommand UpdateShareCommand(ITransaction transaction, Guid shareId, ResourcePath baseResourcePath, string shareName) { IDbCommand result = transaction.CreateCommand(); result.CommandText = "UPDATE SHARES set NAME=@NAME, BASE_RESOURCE_PATH=@BASE_RESOURCE_PATH WHERE SHARE_ID=@SHARE_ID"; ISQLDatabase database = transaction.Database; database.AddParameter(result, "NAME", shareName, typeof(string)); database.AddParameter(result, "BASE_RESOURCE_PATH", baseResourcePath.Serialize(), typeof(string)); database.AddParameter(result, "SHARE_ID", shareId, typeof(Guid)); return result; }
internal static string BuildProviderPath(string nativeSystemId, ResourcePath nativeResourcePath) { return nativeSystemId + ":" + nativeResourcePath.Serialize(); }
public override string ToString() { return(string.Format("ImportJob '{0}'", _basePath.Serialize())); }
protected int RelocateMediaItems(ITransaction transaction, string systemId, ResourcePath originalBasePath, ResourcePath newBasePath) { string originalBasePathStr = StringUtils.CheckSuffix(originalBasePath.Serialize(), "/"); string newBasePathStr = StringUtils.CheckSuffix(newBasePath.Serialize(), "/"); if (originalBasePathStr == newBasePathStr) return 0; string providerAspectTable = _miaManagement.GetMIATableName(ProviderResourceAspect.Metadata); string systemIdAttribute = _miaManagement.GetMIAAttributeColumnName(ProviderResourceAspect.ATTR_SYSTEM_ID); string pathAttribute = _miaManagement.GetMIAAttributeColumnName(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH); ISQLDatabase database = transaction.Database; using (IDbCommand command = transaction.CreateCommand()) { command.CommandText = "UPDATE " + providerAspectTable + " SET " + pathAttribute + " = " + database.CreateStringConcatenationExpression("@PATH", database.CreateSubstringExpression(pathAttribute, (originalBasePathStr.Length + 1).ToString())) + " WHERE " + systemIdAttribute + " = @SYSTEM_ID AND " + database.CreateSubstringExpression(pathAttribute, "1", originalBasePathStr.Length.ToString()) + " = @ORIGBASEPATH"; database.AddParameter(command, "PATH", newBasePathStr, typeof(string)); database.AddParameter(command, "SYSTEM_ID", systemId, typeof(string)); database.AddParameter(command, "ORIGBASEPATH", originalBasePathStr, typeof(string)); return command.ExecuteNonQuery(); } }
public override IEnumerable <MediaItem> GetAllMediaItems() { IContentDirectory cd = ServiceRegistration.Get <IServerConnectionManager>().ContentDirectory; if (cd == null) { return(new List <MediaItem>()); } MediaItemQuery query = new MediaItemQuery( _necessaryMIATypeIds, _optionalMIATypeIds, new BooleanCombinationFilter(BooleanOperator.And, new IFilter[] { new RelationalFilter(ProviderResourceAspect.ATTR_SYSTEM_ID, RelationalOperator.EQ, _systemId), new LikeFilter(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, SqlUtils.LikeEscape(_basePath.Serialize(), '\\') + "%", '\\', true) })); return(cd.Search(query, false)); }
protected MediaItemQuery BuildLoadItemQuery(string systemId, ResourcePath path) { return new MediaItemQuery(new List<Guid>(), new List<Guid>(), new BooleanCombinationFilter(BooleanOperator.And, new IFilter[] { new RelationalFilter(ProviderResourceAspect.ATTR_SYSTEM_ID, RelationalOperator.EQ, systemId), new RelationalFilter(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, RelationalOperator.EQ, path.Serialize()) })); }
public Guid AddOrUpdateMediaItem(Guid parentDirectoryId, string systemId, ResourcePath path, IEnumerable<MediaItemAspect> mediaItemAspects) { // TODO: Avoid multiple write operations to the same media item ISQLDatabase database = ServiceRegistration.Get<ISQLDatabase>(); ITransaction transaction = database.BeginTransaction(); try { Guid? mediaItemId = GetMediaItemId(transaction, systemId, path); DateTime now = DateTime.Now; MediaItemAspect importerAspect; bool wasCreated = !mediaItemId.HasValue; if (wasCreated) { mediaItemId = AddMediaItem(database, transaction); MediaItemAspect pra = new MediaItemAspect(ProviderResourceAspect.Metadata); pra.SetAttribute(ProviderResourceAspect.ATTR_SYSTEM_ID, systemId); pra.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, path.Serialize()); pra.SetAttribute(ProviderResourceAspect.ATTR_PARENT_DIRECTORY_ID, parentDirectoryId); _miaManagement.AddOrUpdateMIA(transaction, mediaItemId.Value, pra, true); importerAspect = new MediaItemAspect(ImporterAspect.Metadata); importerAspect.SetAttribute(ImporterAspect.ATTR_DATEADDED, now); } else importerAspect = _miaManagement.GetMediaItemAspect(transaction, mediaItemId.Value, ImporterAspect.ASPECT_ID); importerAspect.SetAttribute(ImporterAspect.ATTR_DIRTY, false); importerAspect.SetAttribute(ImporterAspect.ATTR_LAST_IMPORT_DATE, now); _miaManagement.AddOrUpdateMIA(transaction, mediaItemId.Value, importerAspect, wasCreated); // Update foreach (MediaItemAspect mia in mediaItemAspects) { if (!_miaManagement.ManagedMediaItemAspectTypes.ContainsKey(mia.Metadata.AspectId)) // Simply skip unknown MIA types. All types should have been added before import. continue; if (mia.Metadata.AspectId == ImporterAspect.ASPECT_ID || mia.Metadata.AspectId == ProviderResourceAspect.ASPECT_ID) { // Those aspects are managed by the MediaLibrary ServiceRegistration.Get<ILogger>().Warn("MediaLibrary.AddOrUpdateMediaItem: Client tried to update either ImporterAspect or ProviderResourceAspect"); continue; } if (wasCreated) _miaManagement.AddOrUpdateMIA(transaction, mediaItemId.Value, mia, true); else _miaManagement.AddOrUpdateMIA(transaction, mediaItemId.Value, mia); } transaction.Commit(); return mediaItemId.Value; } catch (Exception e) { ServiceRegistration.Get<ILogger>().Error("MediaLibrary: Error adding or updating media item(s) in path '{0}'", e, path.Serialize()); transaction.Rollback(); throw; } }
protected IFileSystemResourceAccessor GetResourceAccessor(ResourcePath resourcePath) { lock (_syncObj) { CachedResource resource; string resourcePathStr = resourcePath.Serialize(); if (_resourceAccessorCache.TryGetValue(resourcePathStr, out resource)) return resource.ResourceAccessor; // TODO: Security check. Only deliver resources which are located inside local shares. ServiceRegistration.Get<ILogger>().Debug("ResourceAccessModule: Access of resource '{0}'", resourcePathStr); IResourceAccessor ra; if (!resourcePath.TryCreateLocalResourceAccessor(out ra)) throw new ArgumentException("Unable to access resource path '{0}'", resourcePathStr); IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor; if (fsra == null) { ra.Dispose(); throw new ArgumentException("The given resource path '{0}' doesn't denote a file system resource", resourcePathStr); } _resourceAccessorCache[resourcePathStr] = new CachedResource(fsra); return fsra; } }
public void DeleteMediaItemOrPath(string systemId, ResourcePath path, bool inclusive) { CpAction action = GetAction("DeleteMediaItemOrPath"); IList<object> inParameters = new List<object> {systemId, path.Serialize(), inclusive}; action.InvokeAction(inParameters); }