Example #1
0
        /// <summary>
        /// Configures the specified autorun.
        /// </summary>
        /// <param name="autorun">if set to <c>true</c> [autorun].</param>
        /// <param name="fileSystem">The file system.</param>
        public static void Configure(bool autorun, IFileSystem fileSystem)
        {
            var shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "Media Browser 3", "Media Browser Server.lnk");

            if (!Directory.Exists(Path.GetDirectoryName(shortcutPath)))
            {
                shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "Emby", "Emby Server.lnk");
            }

            var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

            // Remove lnk from old name
            try
            {
                fileSystem.DeleteFile(Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Media Browser Server.lnk"));
            }
            catch
            {
                
            }

            if (autorun)
            {
                //Copy our shortut into the startup folder for this user
                File.Copy(shortcutPath, Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Emby Server.lnk"), true);
            }
            else
            {
                //Remove our shortcut from the startup folder for this user
                fileSystem.DeleteFile(Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Emby Server.lnk"));
            }
        }
Example #2
0
        public static void DeleteImages(GalleryImage image, IFileSystem fileSystem, string virtualRoot)
        {
            string imageVirtualPath = virtualRoot + "FullSizeImages/" + image.ImageFile;

            fileSystem.DeleteFile(imageVirtualPath);

            imageVirtualPath = virtualRoot + "WebImages/" + image.WebImageFile;

            fileSystem.DeleteFile(imageVirtualPath);

            imageVirtualPath = virtualRoot + "Thumbnails/" + image.ThumbnailFile;

            fileSystem.DeleteFile(imageVirtualPath);
        }
Example #3
0
        /// <summary>
        /// usage: local debugging
        /// </summary>
        private MongoDbRunner(IProcessWatcher processWatcher, IPortWatcher portWatcher, IFileSystem fileSystem, IMongoDbProcessStarter processStarter, IMongoBinaryLocator mongoBin, string dataDirectory)
        {
            _fileSystem = fileSystem;
            _port = MongoDbDefaults.DefaultPort;
            _mongoBin = mongoBin;

            MakeMongoBinarysExecutable();

            ConnectionString = "mongodb://*****:*****@"{0}{1}{2}".Formatted(dataDirectory, System.IO.Path.DirectorySeparatorChar.ToString(), MongoDbDefaults.Lockfile));
            _mongoDbProcess = processStarter.Start(_mongoBin.Directory, dataDirectory, _port, true);

            State = State.Running;
        }
Example #4
0
 public void StartUp()
 {
     if (FileSystem == null)
     {
         FileSystem = IsolatedStorageFileSystem.GetForApplication();
         if (FileSystem.FileExists(_LOG_FILE_PATH))
             FileSystem.DeleteFile(_LOG_FILE_PATH);
     }
 }
Example #5
0
        /// <summary>
        /// usage: integration tests
        /// </summary>
        private MongoDbRunner(IPortPool portPool, IFileSystem fileSystem, IMongoDbProcessStarter processStarter, string dataDirectory)
        {
            _fileSystem = fileSystem;
            _port = portPool.GetNextOpenPort();

            ConnectionString = "mongodb://*****:*****@"{0}\{1}".Formatted(_dataDirectoryWithPort, MongoDbDefaults.Lockfile));
            _mongoDbProcess = processStarter.Start(BinariesDirectory, _dataDirectoryWithPort, _port);

            State = State.Running;
        }
Example #6
0
        /// <summary>
        /// Deletes a shortcut from within a virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="mediaPath">The media path.</param>
        /// <param name="appPaths">The app paths.</param>
        /// <exception cref="System.IO.DirectoryNotFoundException">The media folder does not exist</exception>
        public static void RemoveMediaPath(IFileSystem fileSystem, string virtualFolderName, string mediaPath, IServerApplicationPaths appPaths)
        {
            var rootFolderPath = appPaths.DefaultUserViewsPath;
            var path = Path.Combine(rootFolderPath, virtualFolderName);

            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
            }

            var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));

            if (!string.IsNullOrEmpty(shortcut))
            {
                fileSystem.DeleteFile(shortcut);
            }
        }
Example #7
0
File: Autorun.cs Project: dgz/Emby
        /// <summary>
        /// Configures the specified autorun.
        /// </summary>
        /// <param name="autorun">if set to <c>true</c> [autorun].</param>
        /// <param name="fileSystem">The file system.</param>
        public static void Configure(bool autorun, IFileSystem fileSystem)
        {
            var shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "Emby", "Emby Server.lnk");

            var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

            if (autorun)
            {
                //Copy our shortut into the startup folder for this user
                File.Copy(shortcutPath, Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Emby Server.lnk"), true);
            }
            else
            {
                //Remove our shortcut from the startup folder for this user
                fileSystem.DeleteFile(Path.Combine(startupPath, Path.GetFileName(shortcutPath) ?? "Emby Server.lnk"));
            }
        }
Example #8
0
        /// <summary>
        /// usage: integration tests
        /// </summary>
        private MongoDbRunner(IPortPool portPool, IFileSystem fileSystem, IMongoDbProcessStarter processStarter, IMongoBinaryLocator mongoBin, string dataDirectory)
        {
            _fileSystem = fileSystem;
            _port = portPool.GetNextOpenPort();
            _mongoBin = mongoBin;

            MakeMongoBinarysExecutable();

            ConnectionString = "mongodb://*****:*****@"{0}{1}{2}".Formatted(_dataDirectoryWithPort, System.IO.Path.DirectorySeparatorChar.ToString(), MongoDbDefaults.Lockfile));

            _mongoDbProcess = processStarter.Start(_mongoBin.Directory, _dataDirectoryWithPort, _port);

            State = State.Running;
        }
Example #9
0
        /// <summary>
        /// usage: local debugging
        /// </summary>
        private MongoDbRunner(IProcessWatcher processWatcher, IPortWatcher portWatcher, IFileSystem fileSystem, IMongoDbProcessStarter processStarter)
        {
            _fileSystem = fileSystem;
            _port = MongoDbDefaults.DefaultPort;

            ConnectionString = "mongodb://*****:*****@"{0}\{1}".Formatted(MongoDbDefaults.DataDirectory, MongoDbDefaults.Lockfile));
            _mongoDbProcess = processStarter.Start(BinariesDirectory, MongoDbDefaults.DataDirectory, _port, true);

            State = State.Running;
        }
Example #10
0
        public Task DeleteSubtitles(BaseItem item, int index)
        {
            var stream = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery
            {
                Index  = index,
                ItemId = item.Id,
                Type   = MediaStreamType.Subtitle
            }).First();

            var path = stream.Path;

            _monitor.ReportFileSystemChangeBeginning(path);

            try
            {
                _fileSystem.DeleteFile(path);
            }
            finally
            {
                _monitor.ReportFileSystemChangeComplete(path, false);
            }

            return(item.RefreshMetadata(CancellationToken.None));
        }
Example #11
0
        public async Task UninstallRevision(int id, IProgress <int> progress)
        {
            var revision = Database.Revisions.Find(r => r.ID == id);

            if (revision == null)
            {
                return;
            }

            var totalCount = revision.Files.Count;
            var i          = 0;

            await Task.Factory.StartNew(() =>
            {
                Database.RemoveRevision(id);

                /* FIXME: totally guranteed to be sorted by directory! */
                foreach (var file in revision.Files)
                {
                    i++;

                    if (_fs.FileExists(file.Path))
                    {
                        _fs.DeleteFile(file.Path);
                    }
                    else if (_fs.DirectoryExists(file.Path))
                    {
                        _fs.DeleteDirectory(file.Path);
                    }

                    progress?.Report(i / totalCount * 100);
                }

                Database.WriteDbDisk();
            });
        }
        /// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:MethodInvocationRemoting.IRemoteSender.Send(System.String)"]/*'/>
        public void Send(string message)
        {
            metricsUtilities.Begin(new MessageSendTime());

            CheckNotDisposed();

            try
            {
                // Lock file is created before data is written to the message file
                //   The FileRemoteReceiver class checks for the absence of the lock file to prevent attempting to open the message file when it is partially written and causing an exception
                lockFile.WriteAll("");
                messageFile.WriteAll(message);
                fileSystem.DeleteFile(lockFilePath);
            }
            catch (Exception e)
            {
                metricsUtilities.CancelBegin(new MessageSendTime());
                throw new Exception("Error sending message.", e);
            }

            metricsUtilities.End(new MessageSendTime());
            metricsUtilities.Increment(new MessageSent());
            loggingUtilities.Log(this, LogLevel.Information, "Message sent.");
        }
Example #13
0
 protected virtual void DeleteFiles(EncodingJob job)
 {
     FileSystem.DeleteFile(job.OutputFilePath);
 }
Example #14
0
        private void HandleRequiresBody(DefaultCommandInput <ICoreParseResult> commandInput,
                                        IShellState shellState,
                                        HttpState programState,
                                        HttpRequestMessage request,
                                        Dictionary <string, string> requestHeaders)
        {
            string filePath    = null;
            string bodyContent = null;
            bool   deleteFile  = false;
            bool   noBody      = commandInput.Options[NoBodyOption].Count > 0;

            if (!requestHeaders.TryGetValue("content-type", out string contentType) && programState.Headers.TryGetValue("content-type", out IEnumerable <string> contentTypes))
            {
                contentType = contentTypes.FirstOrDefault();
            }

            if (!noBody)
            {
                if (string.IsNullOrEmpty(contentType))
                {
                    contentType = "application/json";
                }

                if (commandInput.Options[BodyFileOption].Count > 0)
                {
                    filePath = commandInput.Options[BodyFileOption][0].Text;

                    if (!_fileSystem.FileExists(filePath))
                    {
                        shellState.ConsoleManager.Error.WriteLine($"Content file {filePath} does not exist".SetColor(programState.ErrorColor));
                        return;
                    }
                }
                else if (commandInput.Options[BodyContentOption].Count > 0)
                {
                    bodyContent = commandInput.Options[BodyContentOption][0].Text;
                }
                else
                {
                    string defaultEditorCommand = _preferences.GetValue(WellKnownPreference.DefaultEditorCommand, null);
                    if (defaultEditorCommand == null)
                    {
                        shellState.ConsoleManager.Error.WriteLine($"The default editor must be configured using the command `pref set {WellKnownPreference.DefaultEditorCommand} \"{{commandline}}\"`".SetColor(programState.ErrorColor));
                        return;
                    }

                    deleteFile = true;
                    filePath   = _fileSystem.GetTempFileName();

                    string exampleBody = GetExampleBody(commandInput.Arguments.Count > 0 ? commandInput.Arguments[0].Text : string.Empty, ref contentType, Verb, programState);

                    if (!string.IsNullOrEmpty(exampleBody))
                    {
                        _fileSystem.WriteAllTextToFile(filePath, exampleBody);
                    }

                    string defaultEditorArguments = _preferences.GetValue(WellKnownPreference.DefaultEditorArguments, null) ?? "";
                    string original   = defaultEditorArguments;
                    string pathString = $"\"{filePath}\"";

                    defaultEditorArguments = defaultEditorArguments.Replace("{filename}", pathString);

                    if (string.Equals(defaultEditorArguments, original, StringComparison.Ordinal))
                    {
                        defaultEditorArguments = (defaultEditorArguments + " " + pathString).Trim();
                    }

                    ProcessStartInfo info = new ProcessStartInfo(defaultEditorCommand, defaultEditorArguments);

                    Process.Start(info)?.WaitForExit();
                }
            }

            if (string.IsNullOrEmpty(contentType))
            {
                contentType = "application/json";
            }

            byte[] data = noBody
                ? new byte[0]
                : string.IsNullOrEmpty(bodyContent)
                    ? _fileSystem.ReadAllBytesFromFile(filePath)
                    : Encoding.UTF8.GetBytes(bodyContent);

            HttpContent content = new ByteArrayContent(data);

            content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            request.Content             = content;

            if (deleteFile)
            {
                _fileSystem.DeleteFile(filePath);
            }

            AddHttpContentHeaders(content, programState, requestHeaders);
        }
Example #15
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            GalleryImage galleryImage;

            if (moduleId > -1)
            {
                if (itemId > -1)
                {
                    galleryImage = new GalleryImage(moduleId, itemId);
                }
                else
                {
                    galleryImage = new GalleryImage(moduleId);
                }

                if (galleryImage.ModuleId != moduleId)
                {
                    SiteUtils.RedirectToAccessDeniedPage(this);
                    return;
                }

                Module module = GetModule(moduleId, Gallery.FeatureGuid);
                galleryImage.ModuleGuid = module.ModuleGuid;

                galleryImage.ContentChanged += new ContentChangedEventHandler(galleryImage_ContentChanged);

                int displayOrder;
                if (!Int32.TryParse(txtDisplayOrder.Text, out displayOrder))
                {
                    displayOrder = -1;
                }

                if (displayOrder > -1)
                {
                    galleryImage.DisplayOrder = displayOrder;
                }

                galleryImage.WebImageHeight  = config.WebSizeHeight;
                galleryImage.WebImageWidth   = config.WebSizeWidth;
                galleryImage.ThumbNailHeight = config.ThumbnailHeight;
                galleryImage.ThumbNailWidth  = config.ThumbnailWidth;
                galleryImage.Description     = edDescription.Text;
                galleryImage.Caption         = txtCaption.Text;
                galleryImage.UploadUser      = Context.User.Identity.Name;
                SiteUser siteUser = SiteUtils.GetCurrentSiteUser();
                if (siteUser != null)
                {
                    galleryImage.UserGuid = siteUser.UserGuid;
                }

                // as long as javascript is available this code should never execute
                // because the standard file input ir replaced by javascript and the file upload happens
                // at the service url /ImageGallery/upload.ashx
                // this is fallback implementation

                if (uploader.HasFile)
                {
                    string ext = Path.GetExtension(uploader.FileName);
                    if (!SiteUtils.IsAllowedUploadBrowseFile(ext, ".jpg|.gif|.png|.jpeg"))
                    {
                        lblMessage.Text = GalleryResources.InvalidFile;

                        return;
                    }

                    string newFileName  = Path.GetFileName(uploader.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);
                    string newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName);
                    if (galleryImage.ImageFile == newFileName)
                    {
                        // an existing gallery image delete the old one
                        fileSystem.DeleteFile(newImagePath);
                    }
                    else
                    {
                        // this is a new galleryImage instance, make sure we don't use the same file name as any other instance
                        int i = 1;
                        while (fileSystem.FileExists(VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName)))
                        {
                            newFileName = i.ToInvariantString() + newFileName;
                            i          += 1;
                        }
                    }
                    newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName);

                    if (galleryImage.ItemId > -1)
                    {
                        //updating with a new image so delete the previous version
                        GalleryHelper.DeleteImages(galleryImage, fileSystem, imageFolderPath);
                    }


                    //using (Stream s = flImage.FileContent)
                    //{
                    //    fileSystem.SaveFile(newImagePath, s, flImage.ContentType, true);
                    //}
                    using (Stream s = uploader.FileContent)
                    {
                        fileSystem.SaveFile(newImagePath, s, IOHelper.GetMimeType(Path.GetExtension(ext).ToLower()), true);
                    }



                    galleryImage.ImageFile     = newFileName;
                    galleryImage.WebImageFile  = newFileName;
                    galleryImage.ThumbnailFile = newFileName;
                    galleryImage.Save();
                    GalleryHelper.ProcessImage(galleryImage, fileSystem, imageFolderPath, uploader.FileName, config.ResizeBackgroundColor);

                    CurrentPage.UpdateLastModifiedTime();
                    CacheHelper.ClearModuleCache(moduleId);

                    SiteUtils.QueueIndexing();
                    if (hdnReturnUrl.Value.Length > 0)
                    {
                        WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
                        return;
                    }
                }
                else // not hasfile
                {       //updating a previously uploaded image
                    if (itemId > -1)
                    {
                        if (galleryImage.Save())
                        {
                            CurrentPage.UpdateLastModifiedTime();
                            CacheHelper.ClearModuleCache(moduleId);
                            SiteUtils.QueueIndexing();
                            if (newItem)
                            {
                                string thisUrl = SiteRoot + "/ImageGallery/EditImage.aspx?pageid="
                                                 + pageId.ToInvariantString()
                                                 + "&mid=" + moduleId.ToInvariantString()
                                                 + "&ItemID=" + galleryImage.ItemId.ToInvariantString();

                                WebUtils.SetupRedirect(this, thisUrl);
                                return;
                            }
                            else
                            {
                                if (hdnReturnUrl.Value.Length > 0)
                                {
                                    WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
                                    return;
                                }

                                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                            }
                        }
                    }
                }
            }
        }
Example #16
0
        public async Task RemoveFromCollection(Guid collectionId, IEnumerable <Guid> itemIds)
        {
            var collection = _libraryManager.GetItemById(collectionId) as BoxSet;

            if (collection == null)
            {
                throw new ArgumentException("No collection exists with the supplied Id");
            }

            var list     = new List <LinkedChild>();
            var itemList = new List <BaseItem>();

            foreach (var itemId in itemIds)
            {
                var child = collection.LinkedChildren.FirstOrDefault(i => i.ItemId.HasValue && i.ItemId.Value == itemId);

                if (child == null)
                {
                    throw new ArgumentException("No collection title exists with the supplied Id");
                }

                list.Add(child);

                var childItem = _libraryManager.GetItemById(itemId);

                if (childItem != null)
                {
                    itemList.Add(childItem);
                }
            }

            var shortcutFiles = Directory
                                .EnumerateFiles(collection.Path, "*", SearchOption.TopDirectoryOnly)
                                .Where(i => _fileSystem.IsShortcut(i))
                                .ToList();

            var shortcutFilesToDelete = list.Where(child => !string.IsNullOrWhiteSpace(child.Path) && child.Type == LinkedChildType.Shortcut)
                                        .Select(child => shortcutFiles.FirstOrDefault(i => string.Equals(child.Path, _fileSystem.ResolveShortcut(i), StringComparison.OrdinalIgnoreCase)))
                                        .Where(i => !string.IsNullOrWhiteSpace(i))
                                        .ToList();

            foreach (var file in shortcutFilesToDelete)
            {
                _iLibraryMonitor.ReportFileSystemChangeBeginning(file);
            }

            try
            {
                foreach (var file in shortcutFilesToDelete)
                {
                    _fileSystem.DeleteFile(file);
                }

                foreach (var child in list)
                {
                    collection.LinkedChildren.Remove(child);
                }
            }
            finally
            {
                foreach (var file in shortcutFilesToDelete)
                {
                    _iLibraryMonitor.ReportFileSystemChangeComplete(file, false);
                }
            }

            collection.UpdateRatingToContent();

            await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);

            await collection.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);

            EventHelper.FireEventIfNotNull(ItemsRemovedFromCollection, this, new CollectionModifiedEventArgs
            {
                Collection   = collection,
                ItemsChanged = itemList
            }, _logger);
        }
Example #17
0
        /// <summary>
        ///     Copies a file between two filesystems.
        /// </summary>
        /// <param name="fs">The source filesystem</param>
        /// <param name="srcPath">The source path of the file to copy from the source filesystem</param>
        /// <param name="destFileSystem">The destination filesystem</param>
        /// <param name="destPath">The destination path of the file in the destination filesystem</param>
        /// <param name="overwrite"><c>true</c> to overwrite an existing destination file</param>
        public static void CopyFileCross(this IFileSystem fs, UPath srcPath, IFileSystem destFileSystem, UPath destPath, bool overwrite)
        {
            if (destFileSystem is null)
            {
                throw new ArgumentNullException(nameof(destFileSystem));
            }

            // If this is the same filesystem, use the file system directly to perform the action
            if (fs == destFileSystem)
            {
                fs.CopyFile(srcPath, destPath, overwrite);
                return;
            }

            srcPath.AssertAbsolute(nameof(srcPath));
            if (!fs.FileExists(srcPath))
            {
                throw NewFileNotFoundException(srcPath);
            }

            destPath.AssertAbsolute(nameof(destPath));
            var destDirectory = destPath.GetDirectory();

            if (!destFileSystem.DirectoryExists(destDirectory))
            {
                throw NewDirectoryNotFoundException(destDirectory);
            }

            if (destFileSystem.FileExists(destPath) && !overwrite)
            {
                throw new IOException($"The destination file path `{destPath}` already exist and overwrite is false");
            }

            using (var sourceStream = fs.OpenFile(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var copied = false;
                try
                {
                    using (var destStream = destFileSystem.OpenFile(destPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                    {
                        sourceStream.CopyTo(destStream);
                    }

                    // NOTE: For some reasons, we can sometimes get an Unauthorized access if we try to set the LastWriteTime after the SetAttributes
                    // So we setup it here.
                    destFileSystem.SetLastWriteTime(destPath, fs.GetLastWriteTime(srcPath));

                    // Preserve attributes and LastWriteTime as a regular File.Copy
                    destFileSystem.SetAttributes(destPath, fs.GetAttributes(srcPath));

                    copied = true;
                }
                finally
                {
                    if (!copied)
                    {
                        try
                        {
                            destFileSystem.DeleteFile(destPath);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
        }
Example #18
0
            private void RefreshCheckInfoStatus()
            {
                if (!m_UpdatableVersionListReady || !m_ReadOnlyVersionListReady || !m_ReadWriteVersionListReady)
                {
                    return;
                }

                int  movedCount                  = 0;
                int  removedCount                = 0;
                int  updateCount                 = 0;
                long updateTotalLength           = 0L;
                long updateTotalCompressedLength = 0L;

                foreach (KeyValuePair <ResourceName, CheckInfo> checkInfo in m_CheckInfos)
                {
                    CheckInfo ci = checkInfo.Value;
                    ci.RefreshStatus(m_CurrentVariant, m_IgnoreOtherVariant);
                    if (ci.Status == CheckInfo.CheckStatus.StorageInReadOnly)
                    {
                        m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, true, true));
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.StorageInReadWrite)
                    {
                        if (ci.NeedMoveToDisk || ci.NeedMoveToFileSystem)
                        {
                            movedCount++;
                            string resourceFullName = ci.ResourceName.FullName;
                            string resourcePath     = Utility.Path.GetRegularPath(Path.Combine(m_ResourceManager.m_ReadWritePath, resourceFullName));
                            if (ci.NeedMoveToDisk)
                            {
                                IFileSystem fileSystem = m_ResourceManager.GetFileSystem(ci.ReadWriteFileSystemName, false);
                                if (!fileSystem.SaveAsFile(resourceFullName, resourcePath))
                                {
                                    throw new GameFrameworkException(Utility.Text.Format("Save as file '{0}' to '{1}' from file system '{2}' error.", resourceFullName, resourcePath, fileSystem.FullPath));
                                }

                                fileSystem.DeleteFile(resourceFullName);
                            }

                            if (ci.NeedMoveToFileSystem)
                            {
                                IFileSystem fileSystem = m_ResourceManager.GetFileSystem(ci.FileSystemName, false);
                                if (!fileSystem.WriteFile(resourceFullName, resourcePath))
                                {
                                    throw new GameFrameworkException(Utility.Text.Format("Write resource '{0}' to file system '{1}' error.", resourceFullName, fileSystem.FullPath));
                                }

                                if (File.Exists(resourcePath))
                                {
                                    File.Delete(resourcePath);
                                }
                            }
                        }

                        m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, false, true));
                        m_ResourceManager.m_ReadWriteResourceInfos.Add(ci.ResourceName, new ReadWriteResourceInfo(ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode));
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.Update)
                    {
                        m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, false, false));
                        updateCount++;
                        updateTotalLength           += ci.Length;
                        updateTotalCompressedLength += ci.CompressedLength;
                        if (ResourceNeedUpdate != null)
                        {
                            ResourceNeedUpdate(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, ci.CompressedHashCode);
                        }
                    }
                    else if (ci.Status == CheckInfo.CheckStatus.Unavailable || ci.Status == CheckInfo.CheckStatus.Disuse)
                    {
                        // Do nothing.
                    }
                    else
                    {
                        throw new GameFrameworkException(Utility.Text.Format("Check resources '{0}' error with unknown status.", ci.ResourceName.FullName));
                    }

                    if (ci.NeedRemove)
                    {
                        removedCount++;
                        if (ci.ReadWriteUseFileSystem)
                        {
                            IFileSystem fileSystem = m_ResourceManager.GetFileSystem(ci.ReadWriteFileSystemName, false);
                            fileSystem.DeleteFile(ci.ResourceName.FullName);
                        }
                        else
                        {
                            string resourcePath = Utility.Path.GetRegularPath(Path.Combine(m_ResourceManager.m_ReadWritePath, ci.ResourceName.FullName));
                            if (File.Exists(resourcePath))
                            {
                                File.Delete(resourcePath);
                            }
                        }
                    }
                }

                if (movedCount > 0 || removedCount > 0)
                {
                    RemoveEmptyFileSystems();
                    Utility.Path.RemoveEmptyDirectory(m_ResourceManager.m_ReadWritePath);
                }

                if (ResourceCheckComplete != null)
                {
                    ResourceCheckComplete(movedCount, removedCount, updateCount, updateTotalLength, updateTotalCompressedLength);
                }
            }
        private void ArchiveLogFiles(string prefix, IFileInfo[] logFileInfos)
        {
            string zipPath = Path.Combine(_logDir, $"Archived_{prefix}.zip");

            var archivedLogFileInfos = new List <IFileInfo>();

            try
            {
                if (_fileSystem.FileExists(zipPath))
                {
                    Dictionary <string, ZipEntry> zipEntries = GetZipEntries(zipPath)
                                                               .ToDictionary(x => x.Name);

                    IFileInfo[] logFilesNotInZip = logFileInfos
                                                   .Where(fileInfo =>
                    {
                        string name = Path.GetFileName(fileInfo.FullName);
                        ZipEntry existingZipEntry;
                        if (!zipEntries.TryGetValue(name, out existingZipEntry))
                        {
                            return(true);
                        }

                        if (existingZipEntry.Size != fileInfo.Length)
                        {
                            return(true);
                        }

                        double secondsDiff = Math.Abs(existingZipEntry.DateTime.Subtract(fileInfo.LastWriteTimeUtc).TotalSeconds);
                        if (secondsDiff > 2)
                        {
                            return(true);
                        }

                        return(false);
                    })
                                                   .ToArray();

                    if (!logFilesNotInZip.Any())
                    {
                        archivedLogFileInfos.AddRange(logFileInfos);
                    }
                    else
                    {
                        using (Stream stream = _fileSystem.GetStream(zipPath, FileMode.Open, FileAccess.ReadWrite))
                        {
                            var zipEntryFactory = new ZipEntryFactory(ZipEntryFactory.TimeSetting.Fixed);

                            var zipFile = new ZipFile(stream)
                            {
                                EntryFactory = zipEntryFactory
                            };

                            zipFile.BeginUpdate();

                            foreach (IFileInfo fileInfo in logFilesNotInZip)
                            {
                                Func <Stream> getStreamFunc =
                                    () => _fileSystem.GetStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);

                                var staticDataSource = new FuncStreamStaticDataSource(getStreamFunc);

                                zipEntryFactory.FixedDateTime = fileInfo.LastWriteTimeUtc;
                                zipFile.Add(staticDataSource, Path.GetFileName(fileInfo.FullName));

                                archivedLogFileInfos.Add(fileInfo);
                            }

                            zipFile.CommitUpdate();
                        }
                    }
                }
                else
                {
                    using (Stream stream = _fileSystem.GetStream(zipPath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        using (var zipOutputStream = new ZipOutputStream(stream))
                        {
                            foreach (IFileInfo fileInfo in logFileInfos)
                            {
                                AddFileToZip(fileInfo, zipOutputStream);
                                archivedLogFileInfos.Add(fileInfo);
                            }
                        }
                    }
                }
            }
            catch
            {
                archivedLogFileInfos.Clear(); // Don't delete any file!

                if (_fileSystem.FileExists(zipPath))
                {
                    _fileSystem.DeleteFile(zipPath);
                }
            }

            DeleteFiles(archivedLogFileInfos);
        }
        void btnUploadAvatar_Click(object sender, EventArgs e)
        {
            if (selectedUser == null)
            {
                return;
            }

            if (uploader.HasFile)
            {
                if (!fileSystem.FolderExists(avatarBasePath))
                {
                    fileSystem.CreateFolder(avatarBasePath);
                }
                string newFileName = "user" + selectedUser.UserId.ToInvariantString() + "fullsize" + Path.GetExtension(uploader.FileName).ToLower();

                string destPath = avatarBasePath + newFileName;
                string ext      = Path.GetExtension(uploader.FileName);
                string mimeType = IOHelper.GetMimeType(ext).ToLower();

                if (!fileSystem.FolderExists(avatarBasePath))
                {
                    fileSystem.CreateFolder(avatarBasePath);
                }

                if (SiteUtils.IsAllowedUploadBrowseFile(ext, SiteUtils.ImageFileExtensions()))
                {
                    fileSystem.DeleteFile(destPath);
                    fileSystem.SaveFile(destPath, uploader.FileContent, mimeType, true);


                    // limit the size of the full size image to something reasonable
                    mojoPortal.Web.ImageHelper.ResizeImage(
                        destPath,
                        IOHelper.GetMimeType(ext),
                        WebConfigSettings.AvatarMaxOriginalWidth,
                        WebConfigSettings.AvatarMaxOriginalHeight,
                        WebConfigSettings.DefaultResizeBackgroundColor);

                    //create initial crop
                    string croppedFileName = GetBaseImageName() + Path.GetExtension(uploader.FileName).ToLower();
                    string destCropFile    = avatarBasePath + croppedFileName;
                    fileSystem.CopyFile(destPath, destCropFile, true);

                    if (WebConfigSettings.ForceSquareAvatars)
                    {
                        mojoPortal.Web.ImageHelper.ResizeAndSquareImage(
                            destCropFile,
                            IOHelper.GetMimeType(ext),
                            WebConfigSettings.AvatarMaxWidth,
                            WebConfigSettings.DefaultResizeBackgroundColor);
                    }
                    else
                    {
                        mojoPortal.Web.ImageHelper.ResizeImage(
                            destCropFile,
                            IOHelper.GetMimeType(ext),
                            WebConfigSettings.AvatarMaxWidth,
                            WebConfigSettings.AvatarMaxHeight,
                            WebConfigSettings.DefaultResizeBackgroundColor);
                    }

                    selectedUser.AvatarUrl = croppedFileName;
                    selectedUser.Save();
                }
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }
Example #21
0
        public static void DeleteAllFiles(SharedFileFolder folder, IFileSystem fileSystem, string fileVirtualBasePath, SharedFilesConfiguration config)
        {
            // method implemented by Jean-Michel 2008-07-31

            // TODO: implement check whether versioning is enabled before calling this method
            // if we are keeping versions we should not delete the files

            if (folder == null)
            {
                return;
            }
            if (fileSystem == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(fileVirtualBasePath))
            {
                return;
            }
            if (folder.FolderId == -1)
            {
                return;
            }

            ArrayList folders = new ArrayList();
            ArrayList files   = new ArrayList();

            using (IDataReader reader = SharedFile.GetSharedFiles(folder.ModuleId, folder.FolderId))
            {
                while (reader.Read())
                {
                    files.Add(Convert.ToInt32(reader["ItemID"]));
                }
            }

            using (IDataReader reader = SharedFileFolder.GetSharedFolders(folder.ModuleId, folder.FolderId))
            {
                while (reader.Read())
                {
                    folders.Add(Convert.ToInt32(reader["FolderID"]));
                }
            }

            foreach (int id in files)
            {
                SharedFile sharedFile = new SharedFile(folder.ModuleId, id);
                sharedFile.Delete();

                if (!config.EnableVersioning)
                {
                    fileSystem.DeleteFile(VirtualPathUtility.Combine(fileVirtualBasePath, sharedFile.ServerFileName));
                }
            }

            foreach (int id in folders)
            {
                SharedFileFolder subFolder = new SharedFileFolder(folder.ModuleId, id);

                DeleteAllFiles(subFolder, fileSystem, fileVirtualBasePath, config);

                SharedFileFolder.DeleteSharedFileFolder(id);
            }
        }
        public static void DeleteHistoryFile(int id, IFileSystem fileSystem, string virtualHistoryPath)
        {
            string historyServerName = string.Empty;

            using (IDataReader reader = SharedFile.GetHistoryFileAsIDataReader(id))
            {
                if (reader.Read())
                {

                    historyServerName = reader["ServerFileName"].ToString();

                }
            }

            if (historyServerName.Length > 0)
            {
                //File.Delete(Path.Combine(historyPath, Path.GetFileName(historyServerName)));
                string fullPath = VirtualPathUtility.Combine(virtualHistoryPath, historyServerName);
                fileSystem.DeleteFile(fullPath);

            }
        }
        public static bool RestoreHistoryFile(
            int historyId, 
            IFileSystem fileSystem,
            string virtualSourcePath, 
            string virtualHistoryPath)
        {
            bool historyRestored = false;

            if (string.IsNullOrEmpty(virtualSourcePath)) { return historyRestored; }
            if (string.IsNullOrEmpty(virtualHistoryPath)) { return historyRestored; }
            if (fileSystem == null) { return historyRestored; }

            int itemId = 0;
            int moduleId = 0;
            string historyFriendlyName = string.Empty;
            string historyOriginalName = string.Empty;
            string historyServerName = string.Empty;
            DateTime historyUploadDate = DateTime.Now;
            int historyUploadUserID = 0;
            int historyFileSize = 0;

            using (IDataReader reader = SharedFile.GetHistoryFileAsIDataReader(historyId))
            {
                if (reader.Read())
                {
                    itemId = Convert.ToInt32(reader["ItemID"]);
                    moduleId = Convert.ToInt32(reader["ModuleID"]);
                    historyFriendlyName = reader["FriendlyName"].ToString();
                    historyOriginalName = reader["OriginalFileName"].ToString();
                    historyServerName = reader["ServerFileName"].ToString();
                    historyFileSize = Convert.ToInt32(reader["SizeInKB"]);
                    historyUploadUserID = Convert.ToInt32(reader["UploadUserID"]);
                    historyUploadDate = DateTime.Parse(reader["UploadDate"].ToString());

                }
            }

            SharedFile sharedFile = new SharedFile(moduleId, itemId);
            CreateHistory(sharedFile, fileSystem, virtualSourcePath, virtualHistoryPath);

            //File.Move(Path.Combine(historyPath, Path.GetFileName(historyServerName)), Path.Combine(sourcePath, Path.GetFileName(historyServerName)));
            fileSystem.MoveFile(
                VirtualPathUtility.Combine(virtualHistoryPath, historyServerName),
                VirtualPathUtility.Combine(virtualSourcePath, historyServerName),
                true);

            sharedFile.ServerFileName = historyServerName;
            sharedFile.OriginalFileName = historyOriginalName;
            sharedFile.FriendlyName = historyFriendlyName;
            sharedFile.SizeInKB = historyFileSize;
            sharedFile.UploadDate = historyUploadDate;
            sharedFile.UploadUserId = historyUploadUserID;
            historyRestored = sharedFile.Save();
            SharedFile.DeleteHistory(historyId);

            fileSystem.DeleteFile(VirtualPathUtility.Combine(virtualHistoryPath, historyServerName));

            return historyRestored;
        }
        public static void DeleteAllFiles(SharedFileFolder folder, IFileSystem fileSystem, string fileVirtualBasePath, SharedFilesConfiguration config)
        {
            // method implemented by Jean-Michel 2008-07-31

            // TODO: implement check whether versioning is enabled before calling this method
            // if we are keeping versions we should not delete the files

            if (folder == null) { return; }
            if (fileSystem == null) { return; }
            if (string.IsNullOrEmpty(fileVirtualBasePath)) { return; }
            if (folder.FolderId == -1) { return; }

            ArrayList folders = new ArrayList();
            ArrayList files = new ArrayList();
            using (IDataReader reader = SharedFile.GetSharedFiles(folder.ModuleId, folder.FolderId))
            {
                while (reader.Read())
                {
                    files.Add(Convert.ToInt32(reader["ItemID"]));
                }
            }

            using (IDataReader reader = SharedFileFolder.GetSharedFolders(folder.ModuleId, folder.FolderId))
            {
                while (reader.Read())
                {
                    folders.Add(Convert.ToInt32(reader["FolderID"]));
                }
            }

            foreach (int id in files)
            {
                SharedFile sharedFile = new SharedFile(folder.ModuleId, id);
                sharedFile.Delete();

                if (!config.EnableVersioning)
                {
                    fileSystem.DeleteFile(VirtualPathUtility.Combine(fileVirtualBasePath, sharedFile.ServerFileName));

                }
            }

            foreach (int id in folders)
            {
                SharedFileFolder subFolder = new SharedFileFolder(folder.ModuleId, id);

                DeleteAllFiles(subFolder, fileSystem, fileVirtualBasePath, config);

                SharedFileFolder.DeleteSharedFileFolder(id);
            }
        }
        /// <summary>
        /// Deletes all but the most recent files.
        /// </summary>
        /// <param name="fileSystem">The abstract file system to search the root directory of.</param>
        /// <param name="maxFileAge">The maximum age of the files to keep, or <c>null</c>.</param>
        /// <param name="maxAppInstanceCount">The maximum number of app instances to keep, or <c>null</c>.</param>
        /// <param name="maxTotalFileSize">The maximum total file size to keep, or <c>null</c>.</param>
        public static void DeleteOldFiles( IFileSystem fileSystem, TimeSpan? maxFileAge, int? maxAppInstanceCount, long? maxTotalFileSize )
        {
            var allFiles = FindAllFiles(fileSystem);
            var filesToKeep = FindLatestFiles(fileSystem, maxFileAge, maxAppInstanceCount, maxTotalFileSize);

            foreach( var file in allFiles )
            {
                bool keepFile = false;
                foreach( var f in filesToKeep )
                {
                    if( DataStore.Comparer.Equals(file.DataStoreName, f.DataStoreName) )
                    {
                        keepFile = true;
                        break;
                    }
                }

                if( keepFile )
                    continue;
                else
                    fileSystem.DeleteFile(file.DataStoreName);
            }
        }
 void IFileSystem.DeleteFile(string filename) => filesystem.DeleteFile(filename);
Example #27
0
        public async Task <bool> RefreshChapterImages(Video video, IDirectoryService directoryService, List <ChapterInfo> chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken)
        {
            if (!IsEligibleForChapterImageExtraction(video))
            {
                extractImages = false;
            }

            var success     = true;
            var changesMade = false;

            var runtimeTicks = video.RunTimeTicks ?? 0;

            var currentImages = GetSavedChapterImages(video, directoryService);

            foreach (var chapter in chapters)
            {
                if (chapter.StartPositionTicks >= runtimeTicks)
                {
                    _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name);
                    break;
                }

                var path = GetChapterImagePath(video, chapter.StartPositionTicks);

                if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase))
                {
                    if (extractImages)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        try
                        {
                            // Add some time for the first chapter to make sure we don't end up with a black image
                            var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);

                            var protocol = MediaProtocol.File;

                            var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, Array.Empty <string>());

                            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));

                            var container = video.Container;

                            var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);

                            _fileSystem.CopyFile(tempFile, path, true);

                            try
                            {
                                _fileSystem.DeleteFile(tempFile);
                            }
                            catch
                            {
                            }

                            chapter.ImagePath         = path;
                            chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
                            changesMade = true;
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path));
                            success = false;
                            break;
                        }
                    }
                    else if (!string.IsNullOrEmpty(chapter.ImagePath))
                    {
                        chapter.ImagePath = null;
                        changesMade       = true;
                    }
                }
                else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
                {
                    chapter.ImagePath         = path;
                    chapter.ImageDateModified = _fileSystem.GetLastWriteTimeUtc(path);
                    changesMade = true;
                }
            }

            if (saveChapters && changesMade)
            {
                _chapterManager.SaveChapters(video.Id.ToString(), chapters);
            }

            DeleteDeadImages(currentImages, chapters);

            return(success);
        }
Example #28
0
        public async Task <object> Get(GetDashboardPackage request)
        {
            var path = Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath,
                                    "webclient-dump");

            try
            {
                _fileSystem.DeleteDirectory(path, true);
            }
            catch (IOException)
            {
            }

            var creator = GetPackageCreator();

            CopyDirectory(creator.DashboardUIPath, path);

            string culture = null;

            var appVersion = _appHost.ApplicationVersion.ToString();

            var mode = request.Mode;

            if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
            {
                _fileSystem.DeleteFile(Path.Combine(path, "scripts", "registrationservices.js"));
            }

            // Try to trim the output size a bit
            var bowerPath = Path.Combine(path, "bower_components");

            if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
            {
                var versionedBowerPath = Path.Combine(Path.GetDirectoryName(bowerPath), "bower_components" + _appHost.ApplicationVersion);
                Directory.Move(bowerPath, versionedBowerPath);
                bowerPath = versionedBowerPath;
            }

            DeleteFilesByExtension(bowerPath, ".log");
            DeleteFilesByExtension(bowerPath, ".txt");
            DeleteFilesByExtension(bowerPath, ".map");
            DeleteFilesByExtension(bowerPath, ".md");
            DeleteFilesByExtension(bowerPath, ".json");
            DeleteFilesByExtension(bowerPath, ".gz");
            DeleteFilesByExtension(bowerPath, ".bat");
            DeleteFilesByExtension(bowerPath, ".sh");
            DeleteFilesByName(bowerPath, "copying", true);
            DeleteFilesByName(bowerPath, "license", true);
            DeleteFilesByName(bowerPath, "license-mit", true);
            DeleteFilesByName(bowerPath, "gitignore");
            DeleteFilesByName(bowerPath, "npmignore");
            DeleteFilesByName(bowerPath, "jshintrc");
            DeleteFilesByName(bowerPath, "gruntfile");
            DeleteFilesByName(bowerPath, "bowerrc");
            DeleteFilesByName(bowerPath, "jscsrc");
            DeleteFilesByName(bowerPath, "hero.svg");
            DeleteFilesByName(bowerPath, "travis.yml");
            DeleteFilesByName(bowerPath, "build.js");
            DeleteFilesByName(bowerPath, "editorconfig");
            DeleteFilesByName(bowerPath, "gitattributes");
            DeleteFoldersByName(bowerPath, "demo");
            DeleteFoldersByName(bowerPath, "test");
            DeleteFoldersByName(bowerPath, "guides");
            DeleteFoldersByName(bowerPath, "grunt");
            DeleteFoldersByName(bowerPath, "rollups");

            DeleteCryptoFiles(Path.Combine(bowerPath, "cryptojslib", "components"));

            DeleteFoldersByName(Path.Combine(bowerPath, "jquery"), "src");
            DeleteFoldersByName(Path.Combine(bowerPath, "jstree"), "src");
            DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "meteor");
            DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "st");
            DeleteFoldersByName(Path.Combine(bowerPath, "swipebox"), "lib");
            DeleteFoldersByName(Path.Combine(bowerPath, "swipebox"), "scss");

            if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
            {
                // Delete things that are unneeded in an attempt to keep the output as trim as possible
                _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);

                _fileSystem.DeleteFile(Path.Combine(path, "thirdparty", "jquerymobile-1.4.5", "jquery.mobile-1.4.5.min.map"));
            }
            else
            {
                MinifyCssDirectory(path);
                MinifyJsDirectory(path);
            }

            await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);

            await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false);

            return("");
        }
Example #29
0
        public static void DeleteAttachmentFiles(IFileSystem fileSystem, List<FileAttachment> attachments, string basePath)
        {
            if (attachments == null) { return; }
            if (string.IsNullOrEmpty(basePath)) { return; }

            foreach (FileAttachment f in attachments)
            {
                if (fileSystem.FileExists(basePath + f.ServerFileName))
                {
                    fileSystem.DeleteFile(basePath + f.ServerFileName);
                }
            }
        }
 public void RemoveDependencyConfigurations(Project project)
 {
     _fileSystem.DeleteFile(Path.Combine(project.Directory, PackagesConfig));
 }
Example #31
0
 internal static void DeleteFileSafe(this IFileSystem fileSystem, string path)
 {
     DoSafeAction(() => fileSystem.DeleteFile(path), fileSystem.Logger);
 }
Example #32
0
 /// <summary>
 /// Deletes the specified file.
 /// This method can be called on a file that does not exist.
 /// </summary>
 /// <param name="filename">The file to delete.</param>
 public void DeleteFile(string filename)
 {
     WrappedFileSystem.DeleteFile(MakeLower(filename));
 }
Example #33
0
        /// <summary>
        ///     Moves a file between two filesystems.
        /// </summary>
        /// <param name="fs">The source filesystem</param>
        /// <param name="srcPath">The source path of the file to move from the source filesystem</param>
        /// <param name="destFileSystem">The destination filesystem</param>
        /// <param name="destPath">The destination path of the file in the destination filesystem</param>
        public static void MoveFileCross(this IFileSystem fs, UPath srcPath, IFileSystem destFileSystem, UPath destPath)
        {
            if (destFileSystem is null)
            {
                throw new ArgumentNullException(nameof(destFileSystem));
            }

            // If this is the same filesystem, use the file system directly to perform the action
            if (fs == destFileSystem)
            {
                fs.MoveFile(srcPath, destPath);
                return;
            }

            // Check source
            srcPath.AssertAbsolute(nameof(srcPath));
            if (!fs.FileExists(srcPath))
            {
                throw NewFileNotFoundException(srcPath);
            }

            // Check destination
            destPath.AssertAbsolute(nameof(destPath));
            var destDirectory = destPath.GetDirectory();

            if (!destFileSystem.DirectoryExists(destDirectory))
            {
                throw NewDirectoryNotFoundException(destPath);
            }

            if (destFileSystem.DirectoryExists(destPath))
            {
                throw NewDestinationDirectoryExistException(destPath);
            }

            if (destFileSystem.FileExists(destPath))
            {
                throw NewDestinationFileExistException(destPath);
            }

            using (var sourceStream = fs.OpenFile(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var copied = false;
                try
                {
                    using (var destStream = destFileSystem.OpenFile(destPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                    {
                        sourceStream.CopyTo(destStream);
                    }

                    // Preserve all attributes and times
                    destFileSystem.SetAttributes(destPath, fs.GetAttributes(srcPath));
                    destFileSystem.SetCreationTime(destPath, fs.GetCreationTime(srcPath));
                    destFileSystem.SetLastAccessTime(destPath, fs.GetLastAccessTime(srcPath));
                    destFileSystem.SetLastWriteTime(destPath, fs.GetLastWriteTime(srcPath));
                    copied = true;
                }
                finally
                {
                    if (!copied)
                    {
                        try
                        {
                            destFileSystem.DeleteFile(destPath);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }

            var deleted = false;

            try
            {
                fs.DeleteFile(srcPath);
                deleted = true;
            }
            finally
            {
                if (!deleted)
                {
                    try
                    {
                        destFileSystem.DeleteFile(destPath);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
        }
Example #34
0
        /// <summary>
        /// Performs a file deletion.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="file">The file to delete.</param>
        /// <param name="execute">if set to true, the operation gets executed.</param>
        private void PerformFileDeletionOperation(IFileSystem fileSystem, IFileInfo file, bool execute)
        {
            var eventArgs = new FileDeletionEventArgs(file.FullName, file.Length);

            this.OnDeletingFile(eventArgs);

            if (execute)
            {
                try
                {
                    fileSystem.DeleteFile(file);

                    this.OnDeletedFile(eventArgs);
                }

                catch (AccessException)
                {
                    this.OnFileDeletionError(new FileDeletionErrorEventArgs(file));
                }
            }
        }
Example #35
0
        public async Task SaveImage(IHasImages item, Stream source, string mimeType, ImageType type, int?imageIndex, string internalCacheKey, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.IsOwnedItem && !(item is Audio);

            if (item is User)
            {
                saveLocally = true;
            }
            if (item is IItemByName)
            {
                var hasDualAccess = item as IHasDualAccess;
                if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
                {
                    saveLocally = true;
                }
            }

            if (type != ImageType.Primary && item is Episode)
            {
                saveLocally = false;
            }

            var locationType = item.LocationType;

            if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
            {
                saveLocally = false;

                var season = item as Season;

                // If season is virtual under a physical series, save locally if using compatible convention
                if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
                {
                    var series = season.Series;

                    if (series != null && series.SupportsLocalMetadata && series.IsSaveLocalMetadataEnabled())
                    {
                        saveLocally = true;
                    }
                }
            }
            if (!string.IsNullOrEmpty(internalCacheKey))
            {
                saveLocally = false;
            }

            if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
            {
                imageIndex = item.GetImages(type).Count();
            }

            var index = imageIndex ?? 0;

            var paths = !string.IsNullOrEmpty(internalCacheKey) ?
                        new[] { GetCacheKeyPath(item, type, mimeType, internalCacheKey) } :
            GetSavePaths(item, type, imageIndex, mimeType, saveLocally);

            // If there are more than one output paths, the stream will need to be seekable
            if (paths.Length > 1 && !source.CanSeek)
            {
                var memoryStream = new MemoryStream();
                using (source)
                {
                    await source.CopyToAsync(memoryStream).ConfigureAwait(false);
                }
                memoryStream.Position = 0;
                source = memoryStream;
            }

            var currentPath = GetCurrentImagePath(item, type, index);

            using (source)
            {
                var isFirst = true;

                foreach (var path in paths)
                {
                    // Seek back to the beginning
                    if (!isFirst)
                    {
                        source.Position = 0;
                    }

                    await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);

                    isFirst = false;
                }
            }

            // Set the path into the item
            SetImagePath(item, type, imageIndex, paths[0]);

            // Delete the current path
            if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
            {
                _libraryMonitor.ReportFileSystemChangeBeginning(currentPath);

                try
                {
                    var currentFile = new FileInfo(currentPath);

                    // This will fail if the file is hidden
                    if (currentFile.Exists)
                    {
                        if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            currentFile.Attributes &= ~FileAttributes.Hidden;
                        }

                        _fileSystem.DeleteFile(currentFile.FullName);
                    }
                }
                finally
                {
                    _libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
                }
            }
        }
Example #36
0
 public void DeleteFile(string path)
 {
     Wrapped.DeleteFile(path);
 }
Example #37
0
        public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int?imageIndex, bool?saveLocallyWithMedia, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.ExtraType.HasValue && !(item is Audio);

            if (item is User)
            {
                saveLocally = true;
            }

            if (type != ImageType.Primary && item is Episode)
            {
                saveLocally = false;
            }

            if (!item.IsFileProtocol)
            {
                saveLocally = false;

                var season = item as Season;

                // If season is virtual under a physical series, save locally if using compatible convention
                if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
                {
                    var series = season.Series;

                    if (series != null && series.SupportsLocalMetadata && series.IsSaveLocalMetadataEnabled())
                    {
                        saveLocally = true;
                    }
                }
            }
            if (saveLocallyWithMedia.HasValue && !saveLocallyWithMedia.Value)
            {
                saveLocally = saveLocallyWithMedia.Value;
            }

            if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
            {
                imageIndex = item.GetImages(type).Count();
            }

            var index = imageIndex ?? 0;

            var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);

            var retryPaths = GetSavePaths(item, type, imageIndex, mimeType, false);

            // If there are more than one output paths, the stream will need to be seekable
            var memoryStream = new MemoryStream();

            using (source)
            {
                await source.CopyToAsync(memoryStream).ConfigureAwait(false);
            }

            source = memoryStream;

            var currentImage            = GetCurrentImage(item, type, index);
            var currentImageIsLocalFile = currentImage != null && currentImage.IsLocalFile;
            var currentImagePath        = currentImage == null ? null : currentImage.Path;

            var savedPaths = new List <string>();

            using (source)
            {
                var currentPathIndex = 0;

                foreach (var path in paths)
                {
                    source.Position = 0;
                    string retryPath = null;
                    if (paths.Length == retryPaths.Length)
                    {
                        retryPath = retryPaths[currentPathIndex];
                    }
                    var savedPath = await SaveImageToLocation(source, path, retryPath, cancellationToken).ConfigureAwait(false);

                    savedPaths.Add(savedPath);
                    currentPathIndex++;
                }
            }

            // Set the path into the item
            SetImagePath(item, type, imageIndex, savedPaths[0]);

            // Delete the current path
            if (currentImageIsLocalFile && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase))
            {
                var currentPath = currentImagePath;

                _logger.Info("Deleting previous image {0}", currentPath);

                _libraryMonitor.ReportFileSystemChangeBeginning(currentPath);

                try
                {
                    _fileSystem.DeleteFile(currentPath);
                }
                catch (FileNotFoundException)
                {
                }
                finally
                {
                    _libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
                }
            }
        }
Example #38
0
 void DeleteTempAppConfigFile()
 {
     fileSystem.DeleteFile(tempAppConfigFileName);
 }
Example #39
0
        private int Save()
        {
            checkpass();
            if (comfim)
            {
                try
                {
                    var    full = txtFullName.Text.Trim().Split(' ');
                    string Fist = "";
                    string Last = "";
                    for (int i = 0; i < full.Length; i++)
                    {
                        if ((i + 1) < full.Length)
                        {
                            Last += full[i];
                        }
                        else
                        {
                            Fist += full[i];
                        }
                    }
                    SiteUser user = new SiteUser(siteSettings)
                    {
                        Name      = txtFullName.Text.Trim(),
                        FirstName = Fist,
                        LastName  = Last,
                        Email     = txtEmail.Text.Trim(),
                        LoginName = txtFullName.Text.Trim().Replace(' ', '-'),
                        Password  = txtPass2.Text,
                    };
                    user.Save();
                    user = new SiteUser(siteSettings, txtFullName.Text.Replace(' ', '-'));
                    KLAuthor author = null;

                    imageFolderPath = AuthorHepper.MediaFolderPath(siteSettings.SiteId, user.UserId);
                    if (user.Save())
                    {
                        author = new KLAuthor()
                        {
                            ArticleCount = 0,
                            UserID       = user.UserId,
                            IsDel        = false,
                            LevelAuthor  = "Basic",
                            Name         = txtFullName.Text,
                            IsActive     = false,
                        };
                        if (fileImage.UploadedFiles.Count > 0)
                        {
                            imageFolderPath = AuthorHepper.MediaFolderPath(siteSettings.SiteId, user.UserId);


                            AuthorHepper.VerifyAuthorFolders(fileSystem, imageFolderPath);

                            foreach (UploadedFile file in fileImage.UploadedFiles)
                            {
                                string ext = file.GetExtension();
                                if (SiteUtils.IsAllowedUploadBrowseFile(ext, WebConfigSettings.ImageFileExtensions))
                                {
                                    ContentMedia media = new ContentMedia();
                                    media.SiteGuid = siteSettings.SiteGuid;
                                    //image.Title = txtImageTitle.Text;
                                    media.DisplayOrder = 0;

                                    string newFileName  = file.FileName.ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);
                                    string newImagePath = VirtualPathUtility.Combine(imageFolderPath, newFileName);

                                    if (media.MediaFile == newFileName)
                                    {
                                        // an existing image delete the old one
                                        fileSystem.DeleteFile(newImagePath);
                                    }
                                    else
                                    {
                                        // this is a new newsImage instance, make sure we don't use the same file name as any other instance
                                        int i = 1;
                                        while (fileSystem.FileExists(VirtualPathUtility.Combine(imageFolderPath, newFileName)))
                                        {
                                            newFileName = i.ToInvariantString() + newFileName;
                                            i          += 1;
                                        }
                                    }

                                    newImagePath = VirtualPathUtility.Combine(imageFolderPath, newFileName);

                                    file.SaveAs(Server.MapPath(newImagePath));

                                    media.MediaFile     = newFileName;
                                    media.ThumbnailFile = newFileName;

                                    author.Avatar = newFileName;
                                    media.Save();
                                    AuthorHepper.ProcessImage(media, fileSystem, imageFolderPath, file.FileName);
                                }
                            }
                        }
                    }
                    author.Save();

                    Role role = new Role(siteSettings.SiteId, "Author");
                    Role.AddUser(role.RoleId, author.UserID, role.RoleGuid, user.UserGuid);

                    if (!sendmail(user.Name, user.Email))
                    {
                        return(-1);
                    }

                    return(author.UserID);
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
            }
            return(-1);
        }
Example #40
0
        /// <summary>
        /// Converts the text subtitle to SRT internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="inputProtocol">The input protocol.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        /// <exception cref="ArgumentNullException">
        /// inputPath
        /// or
        /// outputPath
        /// </exception>
        private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }

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

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);

            // FFmpeg automatically convert character encoding when it is UTF-16
            // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
            if ((inputPath.EndsWith(".smi") || inputPath.EndsWith(".sami")) &&
                (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
                 encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
            {
                encodingParam = "";
            }
            else if (!string.IsNullOrEmpty(encodingParam))
            {
                encodingParam = " -sub_charenc " + encodingParam;
            }

            int exitCode;

            using (var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    FileName = _mediaEncoder.EncoderPath,
                    Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },
                EnableRaisingEvents = true
            })
            {
                _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

                try
                {
                    process.Start();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error starting ffmpeg");

                    throw;
                }

                var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);

                if (!ranToCompletion)
                {
                    try
                    {
                        _logger.LogInformation("Killing ffmpeg subtitle conversion process");

                        process.Kill();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error killing subtitle conversion process");
                    }
                }

                exitCode = ranToCompletion ? process.ExitCode : -1;
            }

            var failed = false;

            if (exitCode == -1)
            {
                failed = true;

                if (File.Exists(outputPath))
                {
                    try
                    {
                        _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
                        _fileSystem.DeleteFile(outputPath);
                    }
                    catch (IOException ex)
                    {
                        _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
                    }
                }
            }
            else if (!File.Exists(outputPath))
            {
                failed = true;
            }

            if (failed)
            {
                _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);

                throw new Exception(
                          string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
            }

            await SetAssFont(outputPath).ConfigureAwait(false);

            _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
        }
Example #41
0
        /// <summary>
        /// Converts the text subtitle to SRT internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="inputProtocol">The input protocol.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// inputPath
        /// or
        /// outputPath
        /// </exception>
        private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }

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

            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));

            var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(encodingParam))
            {
                encodingParam = " -sub_charenc " + encodingParam;
            }

            var process = _processFactory.Create(new ProcessOptions
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
                FileName        = _mediaEncoder.EncoderPath,
                Arguments       = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),

                IsHidden    = true,
                ErrorDialog = false
            });

            _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            try
            {
                process.Start();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error starting ffmpeg", ex);

                throw;
            }

            var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);

            if (!ranToCompletion)
            {
                try
                {
                    _logger.Info("Killing ffmpeg subtitle conversion process");

                    process.Kill();
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error killing subtitle conversion process", ex);
                }
            }

            var exitCode = ranToCompletion ? process.ExitCode : -1;

            process.Dispose();

            var failed = false;

            if (exitCode == -1)
            {
                failed = true;

                if (_fileSystem.FileExists(outputPath))
                {
                    try
                    {
                        _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
                        _fileSystem.DeleteFile(outputPath);
                    }
                    catch (IOException ex)
                    {
                        _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
                    }
                }
            }
            else if (!_fileSystem.FileExists(outputPath))
            {
                failed = true;
            }

            if (failed)
            {
                var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath);

                _logger.Error(msg);

                throw new Exception(msg);
            }
            await SetAssFont(outputPath).ConfigureAwait(false);

            _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath);
        }
Example #42
0
 internal static void RemoveOldFile(IFileSystem fileSystem)
 {
     string oldFile = typeof(Program).Assembly.Location + ".old";
     try
     {
         if (fileSystem.FileExists(oldFile))
         {
             fileSystem.DeleteFile(oldFile);
         }
     }
     catch
     {
         // We don't want to block the exe from usage if anything failed
     }
 }
Example #43
0
        private async Task PerformPackageInstallation(IProgress <double> progress, PackageVersionInfo package, CancellationToken cancellationToken)
        {
            // Target based on if it is an archive or single assembly
            //  zip archives are assumed to contain directory structures relative to our ProgramDataPath
            var extension = Path.GetExtension(package.targetFilename);
            var isArchive = string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase);
            var target    = Path.Combine(isArchive ? _appPaths.TempUpdatePath : _appPaths.PluginsPath, package.targetFilename);

            // Download to temporary file so that, if interrupted, it won't destroy the existing installation
            var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
            {
                Url = package.sourceUrl,
                CancellationToken = cancellationToken,
                Progress          = progress
            }).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            // Validate with a checksum
            var packageChecksum = string.IsNullOrWhiteSpace(package.checksum) ? Guid.Empty : new Guid(package.checksum);

            if (packageChecksum != Guid.Empty) // support for legacy uploads for now
            {
                using (var crypto = new MD5CryptoServiceProvider())
                    using (var stream = new BufferedStream(_fileSystem.OpenRead(tempFile), 100000))
                    {
                        var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty));
                        if (check != packageChecksum)
                        {
                            throw new ApplicationException(string.Format("Download validation failed for {0}.  Probably corrupted during transfer.", package.name));
                        }
                    }
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Success - move it to the real target
            try
            {
                _fileSystem.CreateDirectory(Path.GetDirectoryName(target));
                _fileSystem.CopyFile(tempFile, target, true);
                //If it is an archive - write out a version file so we know what it is
                if (isArchive)
                {
                    File.WriteAllText(target + ".ver", package.versionStr);
                }
            }
            catch (IOException e)
            {
                _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target);
                throw;
            }

            try
            {
                _fileSystem.DeleteFile(tempFile);
            }
            catch (IOException e)
            {
                // Don't fail because of this
                _logger.ErrorException("Error deleting temp file {0]", e, tempFile);
            }
        }
Example #44
0
        /// <summary>
        /// Converts the text subtitle to SRT internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="inputProtocol">The input protocol.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// inputPath
        /// or
        /// outputPath
        /// </exception>
        /// <exception cref="System.ApplicationException"></exception>
        private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }

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

            _fileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));

            var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(encodingParam))
            {
                encodingParam = " -sub_charenc " + encodingParam;
            }

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    RedirectStandardOutput = false,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,

                    CreateNoWindow  = true,
                    UseShellExecute = false,
                    FileName        = _mediaEncoder.EncoderPath,
                    Arguments       = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                }
            };

            _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");

            _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));

            var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
                                                          true);

            try
            {
                process.Start();
            }
            catch (Exception ex)
            {
                logFileStream.Dispose();

                _logger.ErrorException("Error starting ffmpeg", ex);

                throw;
            }

            var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);

            var ranToCompletion = process.WaitForExit(60000);

            if (!ranToCompletion)
            {
                try
                {
                    _logger.Info("Killing ffmpeg subtitle conversion process");

                    process.StandardInput.WriteLine("q");
                    process.WaitForExit(1000);

                    await logTask.ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error killing subtitle conversion process", ex);
                }
                finally
                {
                    logFileStream.Dispose();
                }
            }

            var exitCode = ranToCompletion ? process.ExitCode : -1;

            process.Dispose();

            var failed = false;

            if (exitCode == -1)
            {
                failed = true;

                if (_fileSystem.FileExists(outputPath))
                {
                    try
                    {
                        _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
                        _fileSystem.DeleteFile(outputPath);
                    }
                    catch (IOException ex)
                    {
                        _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
                    }
                }
            }
            else if (!_fileSystem.FileExists(outputPath))
            {
                failed = true;
            }

            if (failed)
            {
                var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);

                _logger.Error(msg);

                throw new ApplicationException(msg);
            }
            await SetAssFont(outputPath).ConfigureAwait(false);
        }
Example #45
0
        private async Task ExtractAttachmentInternal(
            string inputPath,
            int attachmentStreamIndex,
            string outputPath,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }

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

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            var processArgs = string.Format(
                CultureInfo.InvariantCulture,
                "-dump_attachment:{1} {2} -i {0} -t 0 -f null null",
                inputPath,
                attachmentStreamIndex,
                outputPath);

            int exitCode;

            using (var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    Arguments = processArgs,
                    FileName = _mediaEncoder.EncoderPath,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },
                EnableRaisingEvents = true
            })
            {
                _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);

                process.Start();

                var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);

                if (!ranToCompletion)
                {
                    try
                    {
                        _logger.LogWarning("Killing ffmpeg attachment extraction process");
                        process.Kill();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error killing attachment extraction process");
                    }
                }

                exitCode = ranToCompletion ? process.ExitCode : -1;
            }

            var failed = false;

            if (exitCode != 0)
            {
                failed = true;

                _logger.LogWarning("Deleting extracted attachment {Path} due to failure: {ExitCode}", outputPath, exitCode);
                try
                {
                    if (File.Exists(outputPath))
                    {
                        _fileSystem.DeleteFile(outputPath);
                    }
                }
                catch (IOException ex)
                {
                    _logger.LogError(ex, "Error deleting extracted attachment {Path}", outputPath);
                }
            }
            else if (!File.Exists(outputPath))
            {
                failed = true;
            }

            if (failed)
            {
                _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);

                throw new InvalidOperationException(
                          string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputPath));
            }
            else
            {
                _logger.LogInformation("ffmpeg attachment extraction completed for {Path} to {Path}", inputPath, outputPath);
            }
        }
Example #46
0
 /// <summary>
 /// Deletes a package from a FileSystem.
 /// </summary>
 /// <param name="fileSystem">The FileSystem where the specified package is deleted.</param>
 /// <param name="packageId">The package Id.</param>
 /// <param name="packageVersion">The package Id.</param>
 private static void DeletePackageFromFileSystem(IFileSystem fileSystem, string packageId, string packageVersion)
 {
     var pathResolver = new DefaultPackagePathResolver(fileSystem);
     var packageFileName = pathResolver.GetPackageFileName(packageId, new SemanticVersion(packageVersion));
     fileSystem.DeleteFile(packageFileName);
 }
Example #47
0
        void btnUpload_Click(object sender, EventArgs e)
        {
            // as long as javascript is available this code should never execute
            // because the standard file input ir replaced by javascript and the file upload happens
            // at the service url /ImageGallery/upload.ashx
            // this is fallback implementation

            Module module = GetModule(moduleId, Gallery.FeatureGuid);

            if (module == null)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            SiteUser siteUser = SiteUtils.GetCurrentSiteUser();

            try
            {
                if (uploader.HasFile)
                {
                    string ext = Path.GetExtension(uploader.FileName);
                    if (SiteUtils.IsAllowedUploadBrowseFile(ext, ".jpg|.gif|.png|.jpeg"))
                    {
                        GalleryImage galleryImage = new GalleryImage(this.moduleId);
                        galleryImage.ModuleGuid      = module.ModuleGuid;
                        galleryImage.WebImageHeight  = config.WebSizeHeight;
                        galleryImage.WebImageWidth   = config.WebSizeWidth;
                        galleryImage.ThumbNailHeight = config.ThumbnailHeight;
                        galleryImage.ThumbNailWidth  = config.ThumbnailWidth;
                        galleryImage.UploadUser      = Context.User.Identity.Name;

                        if (siteUser != null)
                        {
                            galleryImage.UserGuid = siteUser.UserGuid;
                        }

                        //string newFileName = Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);
                        string newFileName  = Path.GetFileName(uploader.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);
                        string newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName);

                        if (galleryImage.ImageFile == newFileName)
                        {
                            // an existing gallery image delete the old one
                            fileSystem.DeleteFile(newImagePath);
                        }
                        else
                        {
                            // this is a new galleryImage instance, make sure we don't use the same file name as any other instance
                            int i = 1;
                            while (fileSystem.FileExists(VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName)))
                            {
                                newFileName = i.ToInvariantString() + newFileName;
                                i          += 1;
                            }
                        }

                        newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName);


                        using (Stream s = uploader.FileContent)
                        {
                            //fileSystem.SaveFile(newImagePath, s, uploader.FileContentType, true);
                            fileSystem.SaveFile(newImagePath, s, IOHelper.GetMimeType(Path.GetExtension(ext).ToLower()), true);
                        }


                        galleryImage.ImageFile     = newFileName;
                        galleryImage.WebImageFile  = newFileName;
                        galleryImage.ThumbnailFile = newFileName;
                        galleryImage.Save();
                        GalleryHelper.ProcessImage(galleryImage, fileSystem, imageFolderPath, uploader.FileName, config.ResizeBackgroundColor);
                    }
                }

                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
            }
            catch (UnauthorizedAccessException ex)
            {
                lblError.Text = ex.Message;
            }
            catch (ArgumentException ex)
            {
                lblError.Text = ex.Message;
            }
        }
Example #48
0
        public static void DeleteAttachmentFile(IFileSystem fileSystem, FileAttachment attachment, string basePath)
        {
            if (attachment == null) { return; }
            if (string.IsNullOrEmpty(basePath)) { return; }

            if (fileSystem.FileExists(basePath + attachment.ServerFileName))
            {
                fileSystem.DeleteFile(basePath + attachment.ServerFileName);
            }
        }