コード例 #1
0
    /// <summary>
    /// Gets direct path for preview image of currently edited media file.
    /// </summary>
    private string GetPrevDirectPath()
    {
        string prevUrl = "";

        // Direct path
        string previewPath   = null;
        string previewFolder = null;

        if (Path.GetDirectoryName(FileInfo.FilePath).EndsWithCSafe(MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName)))
        {
            previewFolder = Path.GetDirectoryName(FileInfo.FilePath) + "\\" + MediaLibraryHelper.GetPreviewFileName(FileInfo.FileName, FileInfo.FileExtension, ".*", CMSContext.CurrentSiteName);
            previewPath   = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(FileInfo.FileLibraryID) + "\\" + previewFolder;
        }
        else
        {
            previewFolder = Path.GetDirectoryName(FileInfo.FilePath) + "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName) + "\\" + MediaLibraryHelper.GetPreviewFileName(FileInfo.FileName, FileInfo.FileExtension, ".*", CMSContext.CurrentSiteName);
            previewPath   = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(FileInfo.FileLibraryID) + "\\" + previewFolder;
        }
        if (Directory.Exists(Path.GetDirectoryName(previewPath)))
        {
            string[] files = Directory.GetFiles(Path.GetDirectoryName(previewPath), Path.GetFileName(previewPath));
            if (files.Length > 0)
            {
                previewFolder = Path.GetDirectoryName(previewFolder).Replace('\\', '/').TrimStart('/');
                string prevFileName = Path.GetFileName(files[0]);

                prevUrl = MediaFileInfoProvider.GetMediaFileUrl(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder, previewFolder + '/' + prevFileName);
                prevUrl = URLHelper.ResolveUrl(prevUrl);
            }
        }

        return(prevUrl);
    }
コード例 #2
0
    private void gridElem_OnAction(string actionName, object actionArgument)
    {
        switch (actionName.ToLowerCSafe())
        {
        case "edit":
            SelectedItemID = ValidationHelper.GetInteger(actionArgument, 0);
            RaiseOnEdit();
            break;

        case "delete":
            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(ValidationHelper.GetInteger(actionArgument, 0));
            // Check 'Manage' permission
            if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, PERMISSION_MANAGE))
            {
                ShowError(MediaLibraryHelper.GetAccessDeniedMessage(PERMISSION_MANAGE));
                return;
            }
            try
            {
                MediaLibraryInfoProvider.DeleteMediaLibraryInfo(ValidationHelper.GetInteger(actionArgument, 0));
            }
            catch (Exception ex)
            {
                EventLogProvider.LogException("Media library", "DELETEOBJ", ex, SiteContext.CurrentSiteID);

                ShowError(ex.Message, EventLogProvider.GetExceptionLogMessage(ex), null);
            }
            break;
        }

        RaiseOnAction(actionName, actionArgument);
    }
    /// <summary>
    /// Initializes controls
    /// </summary>
    private void InitializeControl()
    {
        RaiseOnCheckPermissions(PERMISSION_READ, this);

        if (!CheckPermissions())
        {
            ShowError(MediaLibraryHelper.GetAccessDeniedMessage("Manage"));
            return;
        }

        if (MediaLibraryGroupID > 0)
        {
            editElem.ObjectType = MediaLibraryInfo.OBJECT_TYPE_GROUP;
        }

        // Hide code name edit for simple mode
        if (DisplayMode == ControlDisplayModeEnum.Simple)
        {
            editElem.FieldsToHide.Add("LibraryName");
        }

        if (!Enable)
        {
            editElem.Enabled = false;
        }
    }
コード例 #4
0
        public void TestAudioItem()
        {
            IList <IDirectoryObject> objects = new List <IDirectoryObject>();

            Guid id = new Guid("11111111-aaaa-aaaa-aaaa-111111111111");
            IDictionary <Guid, IList <MediaItemAspect> > aspects = new Dictionary <Guid, IList <MediaItemAspect> >();

            SingleMediaItemAspect aspect1 = new SingleMediaItemAspect(MediaAspect.Metadata);

            aspect1.SetAttribute(MediaAspect.ATTR_TITLE, "The Track");
            MediaItemAspect.SetAspect(aspects, aspect1);

            MultipleMediaItemAspect aspect2 = new MultipleMediaItemAspect(ProviderResourceAspect.Metadata);

            aspect2.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, "c:\\file.mp3");
            MediaItemAspect.AddOrUpdateAspect(aspects, aspect2);

            SingleMediaItemAspect aspect3 = new SingleMediaItemAspect(AudioAspect.Metadata);

            MediaItemAspect.SetAspect(aspects, aspect3);

            MediaItem item = new MediaItem(id, aspects);

            objects.Add(MediaLibraryHelper.InstansiateMediaLibraryObject(item, null, null));

            GenericDidlMessageBuilder builder = new GenericDidlMessageBuilder();

            builder.BuildAll("*", objects);

            string xml = builder.ToString();

            Console.WriteLine("XML: {0}", xml);
        }
    /// <summary>
    /// Updates information displayed on import form.
    /// </summary>
    private void UpdateImportForm()
    {
        // Get info on next file name
        string nextFileName = GetNextFileName();

        if (!String.IsNullOrEmpty(nextFileName))
        {
            string ext = Path.GetExtension(nextFileName);

            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                plcMessError.AddError(string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                SetFormEnabled(false);
            }
            else
            {
                SetFormEnabled(true);
                txtImportFileDescription.Text = "";
                txtImportFileName.Text        = URLHelper.GetSafeFileName(Path.GetFileNameWithoutExtension(nextFileName), SiteName, false);
                txtImportFileTitle.Text       = Path.GetFileNameWithoutExtension(nextFileName);

                LoadPreview(nextFileName);
            }
        }
    }
コード例 #6
0
    /// <summary>
    /// Stores new media file info into the DB.
    /// </summary>
    /// <param name="fi">Info on file to be stored</param>
    /// <param name="description">Description of new media file</param>
    /// <param name="name">Name of new media file</param>
    public MediaFileInfo SaveNewFile(FileInfo fi, string title, string description, string name, string filePath)
    {
        string path     = MediaLibraryHelper.EnsurePath(filePath);
        string fileName = name;

        string fullPath  = fi.FullName;
        string extension = URLHelper.GetSafeFileName(fi.Extension, CMSContext.CurrentSiteName);

        // Check if filename is changed ad move file if necessary
        if (fileName + extension != fi.Name)
        {
            string oldPath = path;
            fullPath = MediaLibraryHelper.EnsureUniqueFileName(Path.GetDirectoryName(fullPath) + "\\" + fileName + extension);
            path     = MediaLibraryHelper.EnsurePath(Path.GetDirectoryName(path) + "/" + Path.GetFileName(fullPath)).TrimStart('/');
            MediaFileInfoProvider.MoveMediaFile(CMSContext.CurrentSiteName, MediaLibraryID, oldPath, path, true);
            fileName = Path.GetFileNameWithoutExtension(fullPath);
        }

        // Create media file info
        MediaFileInfo fileInfo = new MediaFileInfo(fullPath, LibraryInfo.LibraryID, MediaLibraryHelper.EnsurePath(Path.GetDirectoryName(path)), 0, 0, 0);

        fileInfo.FileTitle       = title;
        fileInfo.FileDescription = description;

        // Save media file info
        MediaFileInfoProvider.ImportMediaFileInfo(fileInfo);

        // Save FileID in ViewState
        FileID   = fileInfo.FileID;
        FilePath = fileInfo.FilePath;

        return(fileInfo);
    }
コード例 #7
0
    /// <summary>
    /// Updates information displayed on import form.
    /// </summary>
    private void UpdateImportForm()
    {
        // Get info on next file name
        string nextFileName = GetNextFileName();

        if (!String.IsNullOrEmpty(nextFileName))
        {
            string ext = Path.GetExtension(nextFileName);

            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                this.lblError.Text    = string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(CMSContext.CurrentSiteName).TrimEnd(';').Replace(";", ", "));
                this.lblError.Visible = true;
                SetFormEnabled(false);
            }
            else
            {
                SetFormEnabled(true);
                this.txtImportFileDescription.Text = "";
                this.txtImportFileName.Text        = URLHelper.GetSafeFileName(Path.GetFileNameWithoutExtension(nextFileName), CMSContext.CurrentSiteName, false);
                this.txtImportFileTitle.Text       = Path.GetFileNameWithoutExtension(nextFileName);

                LoadPreview(nextFileName);
            }

            InitializeImportBreadcrumbs(URLHelper.GetSafeFileName(nextFileName, CMSContext.CurrentSiteName));
        }
    }
コード例 #8
0
    /// <summary>
    /// Returns set of files in the file system.
    /// </summary>
    private DataSet GetFileSystemDataSource()
    {
        fileSystemDataSource.Path = LibraryPath + "/" + MediaLibraryHelper.EnsurePath(FolderPath) + "/";
        fileSystemDataSource.Path = fileSystemDataSource.Path.Replace("/", "\\").Replace("|", "\\");

        return((DataSet)fileSystemDataSource.DataSource);
    }
コード例 #9
0
        string GetDirectImageUrlFromMediaLibrary(Guid imageGuid)
        {
            //get filenale
            string fileName = null;
            var    libs     = MediaLibraryInfoProvider.GetMediaLibraries().ToList();

            foreach (var lib in libs)
            {
                var folder = lib.Children.FirstOrDefault();

                foreach (var image in folder)
                {
                    if (!string.IsNullOrEmpty(image.GetProperty("Guid").ToString()))
                    {
                        if (image.GetProperty("Guid").ToString() == imageGuid.ToString())
                        {
                            fileName = image.GetProperty("FileName").ToString();
                        }
                    }
                }
            }

            var siteName = SiteContext.CurrentSiteName;

            var urlMediaFileInfo = MediaFileInfoProvider.GetMediaFileInfo(imageGuid, siteName);

            string url = MediaLibraryHelper.GetDirectUrl(urlMediaFileInfo);

            return(url);
        }
 /// <summary>
 /// Handle all the necessary actions performed while file info is imported into the DB.
 /// </summary>
 /// <param name="importAll">Indicates whether the all files should be imported at once</param>
 private void HandleFileImport(bool importAll)
 {
     // Check 'File create' permission
     if (MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filecreate"))
     {
         // Get set of file paths
         if (!string.IsNullOrEmpty(ImportFilePaths))
         {
             // Import single file
             if (importAll)
             {
                 // Import all files
                 HandleMultipleMediaFiles();
             }
             else
             {
                 HandleSingleMediaFile();
             }
         }
         else
         {
             // Inform user on error
             RaiseOnAction("importnofiles", null);
         }
     }
     else
     {
         RaiseOnAction("importerror", MediaLibraryHelper.GetAccessDeniedMessage("filecreate"));
     }
 }
コード例 #11
0
        //TODO: Move to a service
        public override async void Execute(object parameter)
        {
            try
            {
                if (parameter is VLCStorageFile)
                {
                    // Copy the selected file.
                    var         file = parameter as VLCStorageFile;
                    StorageFile f    = await StorageFile.GetFileFromPathAsync(file.StorageItem.Path);

                    CopyMediaFileToLocalStorage(f);
                }
                else if (parameter is VLCStorageFolder)
                {
                    // Copy all media files in the selected folder.
                    var           folder = parameter as VLCStorageFolder;
                    StorageFolder d      = await StorageFolder.GetFolderFromPathAsync(folder.StorageItem.Path);

                    await MediaLibraryHelper.ForeachSupportedFile(d, (IReadOnlyList <StorageFile> files) =>
                    {
                        foreach (var f in files)
                        {
                            CopyMediaFileToLocalStorage(f);
                        }
                        return(Task.FromResult(true));
                    });
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e.Message);
            }
        }
コード例 #12
0
        private Task ExternalDeviceService_MustIndexExternalDevice(string deviceId)
        {
            return(Task.Run(async() =>
            {
                await DispatchHelper.InvokeAsync(CoreDispatcherPriority.Low, () => MediaLibraryIndexingState = LoadingState.Loading);
                StorageFolder folder;
                // Windows.Devices.Portable.StorageDevice.FromId blocks forever on Xbox... so work around
                if (Helpers.DeviceHelper.GetDeviceType() != DeviceTypeEnum.Xbox &&
                    Helpers.DeviceHelper.GetDeviceType() != DeviceTypeEnum.Phone)
                {
                    folder = Windows.Devices.Portable.StorageDevice.FromId(deviceId);
                }
                else
                {
                    var devices = KnownFolders.RemovableDevices;
                    var allFolders = await devices.GetFoldersAsync();
                    folder = allFolders.Last();
                }

                if (!StorageApplicationPermissions.FutureAccessList.CheckAccess(folder))
                {
                    StorageApplicationPermissions.FutureAccessList.Add(folder);
                }
                await MediaLibraryHelper.ForeachSupportedFile(folder, async(IReadOnlyList <StorageFile> files) => await DiscoverMediaItems(files));
                await DispatchHelper.InvokeAsync(CoreDispatcherPriority.Low, () => MediaLibraryIndexingState = LoadingState.Loaded);
            }));
        }
コード例 #13
0
        async Task PerformMediaLibraryIndexing()
        {
            await DispatchHelper.InvokeAsync(CoreDispatcherPriority.Low, () => MediaLibraryIndexingState = LoadingState.Loading);

            StorageFolder folder = await FileUtils.GetLocalStorageMediaFolder();

            await MediaLibraryHelper.ForeachSupportedFile(folder, async (IReadOnlyList <StorageFile> files) => await DiscoverMediaItems(files));

            await MediaLibraryHelper.ForeachSupportedFile(KnownFolders.VideosLibrary, async (IReadOnlyList <StorageFile> files) => await DiscoverMediaItems(files));

            await MediaLibraryHelper.ForeachSupportedFile(KnownFolders.MusicLibrary, async (IReadOnlyList <StorageFile> files) => await DiscoverMediaItems(files));

            await MediaLibraryHelper.ForeachSupportedFile(KnownFolders.CameraRoll, async (IReadOnlyList <StorageFile> files) => await DiscoverMediaItems(files, true));

            // Cortana gets all those artists, albums, songs names
            var artists = LoadArtists(null);

            if (artists != null)
            {
                await CortanaHelper.SetPhraseList("artistName", artists.Where(x => !string.IsNullOrEmpty(x.Name)).Select(x => x.Name).ToList());
            }

            var albums = LoadAlbums(null);

            if (albums != null)
            {
                await CortanaHelper.SetPhraseList("albumName", albums.Where(x => !string.IsNullOrEmpty(x.Name)).Select(x => x.Name).ToList());
            }

            await DispatchHelper.InvokeAsync(CoreDispatcherPriority.Low, () => MediaLibraryIndexingState = LoadingState.Loaded);
        }
コード例 #14
0
    /// <summary>
    /// Setup general values.
    /// </summary>
    private void SetupFile()
    {
        // Get file and library info
        if ((FileInfo != null) && (LibraryInfo != null))
        {
            formMediaFileCustomFields.IsLiveSite = IsLiveSite;

            if (MediaLibraryHelper.IsExternalLibrary(SiteContext.CurrentSiteName, LibraryInfo.LibraryFolder))
            {
                plcDirPath.Visible = false;
            }
            else
            {
                string url = MediaFileInfoProvider.GetMediaFileUrl(LibrarySiteInfo.SiteName, LibraryInfo.LibraryFolder, FileInfo.FilePath);
                ltrDirPathValue.Text = GetFileLinkHtml(ResolveUrl(url));
            }
            ltrPermaLinkValue.Text = GetFileLinkHtml(ResolveUrl(MediaFileInfoProvider.GetMediaFileUrl(FileInfo.FileGUID, FileInfo.FileName)));
            if (ImageHelper.IsImage(FileInfo.FileExtension))
            {
                // Ensure max side size 200
                int[] maxsize = ImageHelper.EnsureImageDimensions(0, 0, 200, FileInfo.FileImageWidth, FileInfo.FileImageHeight);
                imagePreview.Width  = maxsize[0];
                imagePreview.Height = maxsize[1];

                // If is Image show image properties
                imagePreview.URL        = URLHelper.AddParameterToUrl(MediaFileInfoProvider.GetMediaFileUrl(FileInfo.FileGUID, SiteContext.CurrentSiteName), "maxsidesize", "200");
                imagePreview.URL        = URLHelper.AddParameterToUrl(imagePreview.URL, "chset", Guid.NewGuid().ToString());
                plcImagePreview.Visible = true;
                plcMediaPreview.Visible = false;

                pnlPrew.Visible = true;
            }
            else if (MediaHelper.IsAudioVideo(FileInfo.FileExtension))
            {
                mediaPreview.Height = MediaHelper.IsAudio(FileInfo.FileExtension) ? 45 : 180;
                mediaPreview.Width  = 270;

                mediaPreview.AutoPlay   = false;
                mediaPreview.AVControls = true;
                mediaPreview.Loop       = false;
                mediaPreview.Type       = FileInfo.FileExtension;

                // If is Image show image properties
                mediaPreview.Url        = MediaFileInfoProvider.GetMediaFileUrl(FileInfo.FileGUID, FileInfo.FileName);
                plcMediaPreview.Visible = true;
                plcImagePreview.Visible = false;

                pnlPrew.Visible = true;
            }
            else
            {
                pnlPrew.Visible = false;
            }
        }
        else
        {
            pnlPrew.Visible = false;
        }
    }
コード例 #15
0
    /// <summary>
    /// Validates form entries.
    /// </summary>
    /// <param name="action">Action type</param>
    /// <param name="siteName">Site name</param>
    public string ValidateForm(string action, string siteName)
    {
        string newFolderName = txtFolderName.Text.Trim();

        string errMsg = new Validator().NotEmpty(newFolderName, GetString("media.error.FolderNameIsEmpty")).
                        IsFolderName(newFolderName, GetString("media.error.FolderNameIsNotValid")).Result;

        if (String.IsNullOrEmpty(errMsg))
        {
            // Check special folder names
            if ((newFolderName == ".") || (newFolderName == ".."))
            {
                errMsg = GetString("media.error.FolderNameIsRelative");
            }

            if (String.IsNullOrEmpty(errMsg))
            {
                // Make a note that we are renaming existing folder
                bool mustExist = String.IsNullOrEmpty(Action) || (Action.ToLowerCSafe().Trim() != "new");

                // Check if folder with specified name exists already if required
                if (mustExist)
                {
                    // Existing folder is being renamed
                    if (!Directory.Exists(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(siteName, DirectoryHelper.CombinePath(LibraryFolder, FolderPath))))
                    {
                        errMsg = GetString("media.error.FolderDoesNotExist");
                    }
                }

                if (String.IsNullOrEmpty(errMsg))
                {
                    string hiddenFolderName = MediaLibraryHelper.GetMediaFileHiddenFolder(siteName);
                    // Check if folder name is not reserved
                    if (string.Equals(hiddenFolderName, newFolderName, StringComparison.InvariantCultureIgnoreCase) || ValidationHelper.IsSpecialFolderName(newFolderName))
                    {
                        errMsg = String.Format(GetString("media.error.FolderNameIsReserved"), newFolderName);
                    }

                    if (String.IsNullOrEmpty(errMsg))
                    {
                        // Get new folder path
                        GetNewFolderPath(mustExist);

                        if (Path.EnsureForwardSlashes(FolderPath) != Path.EnsureForwardSlashes(mNewFolderPath))
                        {
                            // Check if new folder doesn't exist yet
                            if (Directory.Exists(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(siteName, DirectoryHelper.CombinePath(LibraryFolder, mNewFolderPath))))
                            {
                                errMsg = GetString("media.error.FolderExists");
                            }
                        }
                    }
                }
            }
        }

        return(errMsg);
    }
コード例 #16
0
    /// <summary>
    /// UniGrid action buttons event handler.
    /// </summary>
    protected void GridOnAction(string actionName, object actionArgument)
    {
        // Process proper action
        switch (actionName.ToLower())
        {
        case "delete":
            if (this.IsMediaThumbnail)
            {
                // Delete thumbnail file
                if (this.LibraryInfo != null)
                {
                    // Check 'File delete' permission
                    if (MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(this.LibraryInfo, "filemodify"))
                    {
                        MediaFileInfoProvider.DeleteMediaFilePreview(CMSContext.CurrentSiteName, this.LibraryID, this.FileInfo.FilePath, false);

                        if (this.FileInfo != null)
                        {
                            SiteInfo si = SiteInfoProvider.GetSiteInfo(FileInfo.FileSiteID);
                            if (si != null)
                            {
                                // Log synchronization task
                                SynchronizationHelper.LogObjectChange(FileInfo, TaskTypeEnum.UpdateObject);
                            }

                            // Drop the cache dependencies
                            CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(this.FileInfo, true));
                        }
                    }
                    else
                    {
                        lblError.Text = MediaLibraryHelper.GetAccessDeniedMessage("filemodify");
                    }
                }

                // Ensure recent action is forgotten
                this.gridAttachments.ClearActions();
            }
            else
            {
                if (this.LibraryInfo != null)
                {
                    // Check 'File delete' permission
                    if (MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(this.LibraryInfo, "filedelete"))
                    {
                        // Delete Media File
                        if (this.FileInfo != null)
                        {
                            MediaFileInfoProvider.DeleteMediaFileInfo(this.FileInfo);
                        }
                    }
                }
            }

            // Force reload data
            ReloadData();
            break;
        }
    }
コード例 #17
0
 public MediaLibraryFileProfile()
 {
     CreateMap <MediaFileInfo, MediaLibraryFileDto>()
     .ForMember(dst => dst.Title, opt => opt.MapFrom(src => src.FileTitle))
     .ForMember(dst => dst.Extension, opt => opt.MapFrom(src => src.FileExtension))
     .ForMember(dst => dst.DirectUrl, opt => opt.MapFrom(src => MediaLibraryHelper.GetDirectUrl(src)))
     .ForMember(dst => dst.PermanentUrl, opt => opt.MapFrom(src => MediaLibraryHelper.GetPermanentUrl(src)));
 }
コード例 #18
0
    /// <summary>
    /// Ensures the physical file.
    /// </summary>
    /// <param name="file">Output file</param>
    public bool EnsurePhysicalFile(CMSOutputMediaFile file)
    {
        if (file == null)
        {
            return(false);
        }

        // Try to link to file system
        if (String.IsNullOrEmpty(file.Watermark) && (file.MediaFile != null) && (file.MediaFile.FileID > 0))
        {
            SiteInfo si = SiteInfoProvider.GetSiteInfo(file.MediaFile.FileSiteID);
            if (si != null)
            {
                bool   generateThumbnails = ValidationHelper.GetBoolean(SettingsKeyInfoProvider.GetStringValue(si.SiteName + ".CMSGenerateThumbnails"), true);
                string filePath           = null;
                string libraryFolder      = Path.EnsureEndBackslash(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(file.MediaFile.FileLibraryID));

                if (file.Resized && generateThumbnails)
                {
                    filePath = libraryFolder + MediaFileInfoProvider.EnsureThumbnailFile(file.MediaFile, file.SiteName, Width, Height, MaxSideSize, file.UsePreview);
                }
                else
                {
                    if (file.UsePreview)
                    {
                        // Get file path
                        string path             = MediaFileInfoProvider.GetMediaFilePath(file.MediaFile.FileLibraryID, file.MediaFile.FilePath);
                        string pathDirectory    = Path.GetDirectoryName(path);
                        string hiddenFolderPath = MediaLibraryHelper.GetMediaFileHiddenFolder(CurrentSiteName);
                        string folderPath       = String.Format("{0}\\{1}", pathDirectory, hiddenFolderPath);

                        // Ensure hidden folder exists
                        DirectoryHelper.EnsureDiskPath(folderPath, pathDirectory);
                        // Get preview file
                        string[] files = Directory.GetFiles(folderPath, MediaLibraryHelper.GetPreviewFileName(file.MediaFile.FileName, file.MediaFile.FileExtension, ".*", CurrentSiteName));
                        if (files.Length > 0)
                        {
                            filePath = files[0];
                        }
                    }
                    else
                    {
                        filePath = libraryFolder + file.MediaFile.FilePath;
                    }
                }

                if (filePath != null)
                {
                    // Link to the physical file
                    file.PhysicalFile = filePath;
                    return(true);
                }
            }
        }

        file.PhysicalFile = "";
        return(false);
    }
コード例 #19
0
        public ActionResult Index()
        {
            var properties = GetProperties();
            IEnumerable <Picture> pictures = new List <Picture>();

            switch (properties.Type)
            {
            case Type.Attachments:
                pictures = this.GetPage().Attachments.ToList().Where(a => a.AttachmentImageWidth > 0).Select(a => new Picture
                {
                    Url       = CMS.DocumentEngine.AttachmentURLProvider.GetAttachmentUrl(a.AttachmentName, this.GetPage().NodeAliasPath),
                    AltText   = a.AttachmentTitle,
                    Thumbnail = $"{AttachmentURLProvider.GetAttachmentUrl(a.AttachmentName, this.GetPage().NodeAliasPath)}?maxsidesize=128"
                });
                break;

            case Type.MediaLibraryFolder:
                /*var library = MediaLibraryInfoProvider.GetMediaLibraryInfo(properties.MediaLibraryFolder, this.GetPage().NodeSiteName);
                 * if (string.IsNullOrEmpty(properties.MediaLibraryFolder))
                 * {
                 *  properties.MediaLibraryFolder = "%";
                 * }
                 * var files = MediaFileInfoProvider.GetMediaFiles($"{nameof(MediaFileInfo.FileLibraryID)}={library.LibraryID} AND {nameof(MediaFileInfo.FilePath)} LIKE '{properties.MediaLibrarySubfolder}%'");
                 * pictures = files.ToList().Select(f => new Picture
                 * {
                 *  Url = MediaLibraryHelper.GetMediaFileUrl(f.FileGUID, this.GetPage().NodeSiteName),
                 *  AltText = f.FileTitle,
                 *  Thumbnail = $"{MediaFileURLProvider.GetMediaFileAbsoluteUrl(this.GetPage().NodeSiteName, f.FileGUID, f.FileName)}?maxsidesize=120"
                 * });*/
                if (properties.MediaFiles != null)
                {
                    pictures = properties.MediaFiles.Select(m => new Picture
                    {
                        Url       = MediaLibraryHelper.GetMediaFileUrl(m.FileGuid, this.GetPage().NodeSiteName),
                        AltText   = MediaFileInfoProvider.GetMediaFileInfo(m.FileGuid, this.GetPage().NodeSiteName).FileTitle,
                        Thumbnail = $"{MediaFileURLProvider.GetMediaFileAbsoluteUrl(this.GetPage().NodeSiteName, m.FileGuid, MediaFileInfoProvider.GetMediaFileInfo(m.FileGuid, this.GetPage().NodeSiteName).FileName)}?maxsidesize=128"
                    });
                }
                break;

            case Type.External:
                pictures = properties.External.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Select(f => new Picture
                {
                    Url       = f,
                    AltText   = f,
                    Thumbnail = f
                });
                break;
            }

            var viewModel = new ViewModel
            {
                Pictures = pictures
            };

            return(PartialView("Widgets/_LightboxGallery", viewModel));
        }
コード例 #20
0
    /// <summary>
    /// Edit file event handler.
    /// </summary>
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        // Check 'File modify' permission
        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filemodify"))
        {
            ShowError(MediaLibraryHelper.GetAccessDeniedMessage("filemodify"));

            SetupFile();
            return;
        }

        FileInfo fi = CMS.IO.FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder, FilePath));

        if ((fi != null) && (LibraryInfo != null))
        {
            if (FileInfo != null)
            {
                FileInfo.FileModifiedWhen = DateTime.Now;
                // Set media file info
                FileInfo.FileSize = fi.Length;
                if (ImageHelper.IsImage(FileInfo.FileExtension))
                {
                    ImageHelper ih = new ImageHelper();
                    ih.LoadImage(File.ReadAllBytes(fi.FullName));
                    FileInfo.FileImageWidth  = ih.ImageWidth;
                    FileInfo.FileImageHeight = ih.ImageHeight;
                }
                FileInfo.FileTitle       = txtEditTitle.Text.Trim();
                FileInfo.FileDescription = txtEditDescription.Text.Trim();

                // Save
                MediaFileInfoProvider.SetMediaFileInfo(FileInfo);

                // Remove old thumbnails
                MediaFileInfoProvider.DeleteMediaFileThumbnails(FileInfo);

                // Inform user on success
                ShowConfirmation(GetString("media.refresh.success"));

                SetupTexts();

                SetupFile();
                pnlUpdateGeneral.Update();

                SetupPreview();
                pnlUpdatePreviewDetails.Update();

                SetupEdit();
                pnlUpdateFileInfo.Update();

                SetupVersions(false);
                pnlUpdateVersions.Update();

                RaiseOnAction("rehighlightitem", Path.GetFileName(FileInfo.FilePath));
            }
        }
    }
コード例 #21
0
 /// <summary>
 /// Ensures that the path is ready to be used as an node ID.
 /// </summary>
 /// <param name="path">Path to use</param>
 private string EnsurePath(string path)
 {
     if (!string.IsNullOrEmpty(path))
     {
         path = MediaLibraryHelper.EnsurePath(path);
         path = EnsureFolderId(path);
         path = ScriptHelper.EscapeJQueryCharacters(path);
     }
     return(path);
 }
コード例 #22
0
 public static MediaFileViewModel GetViewModel(MediaFileInfo mediaFileInfo)
 {
     return(new MediaFileViewModel
     {
         Guid = mediaFileInfo.FileGUID,
         Title = mediaFileInfo.FileTitle,
         Name = mediaFileInfo.FileName,
         Url = MediaLibraryHelper.GetDirectUrl(mediaFileInfo)
     });
 }
コード例 #23
0
        private async Task <bool> SaveToMusicAsync(IEnumerable <Memo> items)
        {
            var tasks = items.Select(m => Task.Run <bool>(() =>
            {
                return(MediaLibraryHelper.SaveToMediaLibrary(m.AudioFile, m.Title, m.Duration));
            }));

            var result = await Task.WhenAll <bool>(tasks);

            return(result.Contains(false) ? false : true);
        }
コード例 #24
0
 private void uploader_OnNotAllowed(string permissionType, CMSAdminControl sender)
 {
     if (sender != null)
     {
         sender.StopProcessing = true;
     }
     uploader.StopProcessing    = true;
     uploader.Visible           = false;
     messageElem.ErrorMessage   = MediaLibraryHelper.GetAccessDeniedMessage("filecreate");
     messageElem.DisplayMessage = true;
 }
コード例 #25
0
    /// <summary>
    /// Processes the specified file.
    /// </summary>
    /// <param name="fileGuid">File guid</param>
    /// <param name="preview">Use preview</param>
    protected void ProcessFile(Guid fileGuid, bool preview)
    {
        // Get the file info if doesn't retrieved yet
        fileInfo = (fileInfo ?? MediaFileInfoProvider.GetMediaFileInfo(fileGuid, CurrentSiteName));
        if (fileInfo != null)
        {
            if (preview)
            {
                // Get file path
                string path             = MediaFileInfoProvider.GetMediaFilePath(fileInfo.FileLibraryID, fileInfo.FilePath);
                string pathDirectory    = Path.GetDirectoryName(path);
                string hiddenFolderPath = MediaLibraryHelper.GetMediaFileHiddenFolder(CurrentSiteName);
                string folderPath       = DirectoryHelper.CombinePath(pathDirectory, hiddenFolderPath);


                // Ensure hidden folder exists
                DirectoryHelper.EnsureDiskPath(folderPath, pathDirectory);
                // Get preview file
                string[] files = Directory.GetFiles(folderPath, MediaLibraryHelper.GetPreviewFileName(fileInfo.FileName, fileInfo.FileExtension, ".*", CurrentSiteName));
                if (files.Length > 0)
                {
                    bool resizeImage = (ImageHelper.IsImage(Path.GetExtension(files[0])) && MediaFileInfoProvider.CanResizeImage(files[0], Width, Height, MaxSideSize));

                    // Get the data
                    if ((outputFile == null) || (outputFile.MediaFile == null))
                    {
                        outputFile               = NewOutputFile(fileInfo, null);
                        outputFile.UsePreview    = true;
                        outputFile.Width         = Width;
                        outputFile.Height        = Height;
                        outputFile.MaxSideSize   = MaxSideSize;
                        outputFile.Resized       = resizeImage;
                        outputFile.FileExtension = Path.GetExtension(files[0]);
                        outputFile.MimeType      = MimeTypeHelper.GetMimetype(outputFile.FileExtension);
                    }
                }
            }
            else
            {
                bool resizeImage = (ImageHelper.IsImage(fileInfo.FileExtension) && MediaFileInfoProvider.CanResizeImage(fileInfo, Width, Height, MaxSideSize));

                // Get the data
                if ((outputFile == null) || (outputFile.MediaFile == null))
                {
                    outputFile             = NewOutputFile(fileInfo, null);
                    outputFile.Width       = Width;
                    outputFile.Height      = Height;
                    outputFile.MaxSideSize = MaxSideSize;
                    outputFile.Resized     = resizeImage;
                }
            }
        }
    }
コード例 #26
0
 public async Task <string> GetMediaFileUrlAsync(Guid FileGuid)
 {
     try
     {
         return(MediaLibraryHelper.GetDirectUrl(_mediaFileInfoProvider.Get(FileGuid, _SiteRepo.CurrentSite.SiteID)));
     }
     catch (Exception ex)
     {
         _eventLogService.LogException("KenticoMediaRepository", "MediaFileMissing", ex, additionalMessage: "For media file with Guid " + FileGuid.ToString());
         return("");
     }
 }
コード例 #27
0
    private void gallery_OnNotAllowed(string permissionType, CMSAdminControl sender)
    {
        if (sender != null)
        {
            sender.StopProcessing = true;
        }

        gallery.StopProcessing       = true;
        gallery.Visible              = false;
        gallery.UniPager.PageControl = null;
        messageElem.ErrorMessage     = MediaLibraryHelper.GetAccessDeniedMessage(permissionType);
        messageElem.DisplayMessage   = true;
    }
コード例 #28
0
        public DlnaProtocolInfo GetProtocolInfo(MediaItem item)
        {
            var info = new DlnaProtocolInfo
            {
                Protocol       = "http-get",
                Network        = "*",
                MediaType      = MediaLibraryHelper.GetOrGuessMimeType(item),
                AdditionalInfo = new DlnaForthField()
            };

            ConfigureProfile(info.AdditionalInfo, item, info.MediaType);
            return(info);
        }
コード例 #29
0
    private void formMediaFileCustomFields_OnBeforeSave(object sender, EventArgs e)
    {
        // Check 'File modify' permission
        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filemodify"))
        {
            ShowError(MediaLibraryHelper.GetAccessDeniedMessage("filemodify"));

            DisplayCustomFields(true);
            formMediaFileCustomFields.StopProcessing = true;

            // Update form
            SetupEdit();
        }
    }
コード例 #30
0
        /// <summary>
        /// Navigates to the Video Player screen with the requested file a parameter.
        /// </summary>
        /// <param name="file">The file to be played.</param>
        /// <param name="token">Token is for files that are NOT in the sandbox, such as files taken from the filepicker from a sd card but not in the Video/Music folder.</param>
        public async Task PlayVideoFile(StorageFile file, string token = null)
        {
            var video = await MediaLibraryHelper.GetVideoItem(file);

            video.Id = -1;
            if (token != null)
            {
                video.Token = token;
            }

            await Locator.MediaPlaybackViewModel.PlaybackService.SetPlaylist(new List <IMediaItem> {
                video
            }, true, true, video);
        }