Example #1
0
        public void ExportToFolder(string folder, int days)
        {
            if (!Directory.Exists(folder))
            {
                return;
            }

            FileSystemHelper.DeleteFiles(folder, "*.Mixes.txt", false);

            var sourceFiles = FileSystemHelper.SearchFiles(ShufflerFolder, "*.Mixes.txt", false);

            foreach (var source in sourceFiles)
            {
                var fileName = Path.GetFileName(source);
                if (fileName == null)
                {
                    continue;
                }

                var destinationFile = Path.Combine(folder, fileName);
                var dateModified    = File.GetLastWriteTime(source);
                var difference      = DateTime.Now - dateModified;
                if (days <= 0 || difference.Days < days)
                {
                    FileSystemHelper.Copy(source, destinationFile);
                }
            }
        }
Example #2
0
        public ActionResult Create(ImportProfileModel model)
        {
            if (!Services.Permissions.Authorize(StandardPermissionProvider.ManageImports))
            {
                return(AccessDeniedView());
            }

            var importFile = Path.Combine(FileSystemHelper.TempDir(), model.TempFileName.EmptyNull());

            if (System.IO.File.Exists(importFile))
            {
                var profile = _importProfileService.InsertImportProfile(model.TempFileName, model.Name, model.EntityType);

                if (profile != null && profile.Id != 0)
                {
                    var importFileDestination = Path.Combine(profile.GetImportFolder(true, true), model.TempFileName);

                    FileSystemHelper.Copy(importFile, importFileDestination, true, true);

                    return(RedirectToAction("Edit", new { id = profile.Id }));
                }
            }
            else
            {
                NotifyError(T("Admin.DataExchange.Import.MissingImportFile"));
            }

            return(RedirectToAction("List"));
        }
Example #3
0
        /// <summary>
        /// Copies a file.
        /// </summary>
        /// <param name="sourceFile">The source file.</param>
        /// <param name="destinationFile">The destination file.</param>
        private void CopyFile(string sourceFile, string destinationFile)
        {
            try
            {
                if (File.Exists(destinationFile))
                {
                    File.Delete(destinationFile);
                }

                FileSystemHelper.Copy(sourceFile, destinationFile);
                SyncFileDateTimes(sourceFile, destinationFile);

                AddLogEntry("Copied file '" + Path.GetFileName(sourceFile)
                            + "' to '"
                            + Path.GetDirectoryName(destinationFile)
                            + "'");
            }
            catch (Exception e)
            {
                AddLogEntry("** Could not copy file '"
                            + Path.GetFileName(sourceFile)
                            + "' to '"
                            + Path.GetDirectoryName(destinationFile)
                            + "'");
                AddLogEntry(e.ToString());
            }
        }
        private void mnuCopySample_Click(object sender, EventArgs e)
        {
            var samples = GetSelectedSamples();

            if (samples == null)
            {
                return;
            }

            var folder = FileDialogHelper.OpenFolder();

            if (folder == "")
            {
                return;
            }

            foreach (var sample in samples)
            {
                var source   = SampleLibrary.GetSampleFileName(sample);
                var filename = $"{sample.TrackArtist} - {sample.TrackTitle} - {sample.Description}";
                filename = FileSystemHelper.StripInvalidFileNameChars(filename) + Path.GetExtension(source);
                var destination = Path.Combine(folder, filename);
                FileSystemHelper.Copy(source, destination);
            }
        }
Example #5
0
        private string CopyExternalFileToLibraryFolder(string externalFile, string externalFolder)
        {
            var newFileName = externalFile.Replace(externalFolder, LibraryFolder);
            var newFilePath = Path.GetDirectoryName(newFileName) + "";

            Directory.CreateDirectory(newFilePath);
            FileSystemHelper.Copy(externalFile, newFileName);
            return(newFileName);
        }
Example #6
0
        public virtual void Publish(ExportDeploymentContext context, ExportDeployment deployment)
        {
            string folderDestination = null;

            if (deployment.IsPublic)
            {
                folderDestination = Path.Combine(HttpRuntime.AppDomainAppPath, DataExporter.PublicFolder);
            }
            else if (deployment.FileSystemPath.IsEmpty())
            {
                return;
            }
            else if (deployment.FileSystemPath.StartsWith("/") || deployment.FileSystemPath.StartsWith("\\") || !Path.IsPathRooted(deployment.FileSystemPath))
            {
                folderDestination = CommonHelper.MapPath(deployment.FileSystemPath);
            }
            else
            {
                folderDestination = deployment.FileSystemPath;
            }

            if (!System.IO.Directory.Exists(folderDestination))
            {
                System.IO.Directory.CreateDirectory(folderDestination);
            }

            if (deployment.CreateZip)
            {
                var path = Path.Combine(folderDestination, deployment.Profile.FolderName + ".zip");

                if (FileSystemHelper.Copy(context.ZipPath, path))
                {
                    context.Log.Information("Copied ZIP archive " + path);
                }
            }
            else
            {
                FileSystemHelper.CopyDirectory(new DirectoryInfo(context.FolderContent), new DirectoryInfo(folderDestination));

                context.Log.Information("Copied export data files to " + folderDestination);
            }
        }
        public void StartCreatingFeeds(Func <FeedFileCreationContext, bool> createFeed, string secondFileName = null)
        {
            try
            {
                using (var scope = new DbContextScope(autoDetectChanges: false, validateOnSave: false, forceNoTracking: true))
                {
                    _cachedPathes     = null;
                    _cachedCategories = null;

                    var storeService = _ctx.Resolve <IStoreService>();
                    var stores       = new List <Store>();

                    if (BaseSettings.StoreId != 0)
                    {
                        var storeById = storeService.GetStoreById(BaseSettings.StoreId);
                        if (storeById != null)
                        {
                            stores.Add(storeById);
                        }
                    }

                    if (stores.Count == 0)
                    {
                        stores.AddRange(storeService.GetAllStores());
                    }

                    var context = new FeedFileCreationContext()
                    {
                        StoreCount = stores.Count,
                        Progress   = new Progress <FeedFileCreationProgress>(x =>
                        {
                            AsyncState.Current.Set(x, SystemName);
                        })
                    };

                    foreach (var store in stores)
                    {
                        var feedFile = GetFeedFileByStore(store, secondFileName);
                        if (feedFile != null)
                        {
                            FileSystemHelper.Delete(feedFile.FileTempPath);

                            if (secondFileName.HasValue())
                            {
                                FileSystemHelper.Delete(feedFile.CustomProperties["SecondFileTempPath"] as string);
                            }

                            using (var stream = new FileStream(feedFile.FileTempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                                using (var logger = new TraceLogger(feedFile.LogPath))
                                {
                                    context.Stream      = stream;
                                    context.Logger      = logger;
                                    context.Store       = store;
                                    context.FeedFileUrl = feedFile.FileUrl;

                                    if (secondFileName.HasValue())
                                    {
                                        context.SecondFilePath = feedFile.CustomProperties["SecondFileTempPath"] as string;
                                    }

                                    if (!createFeed(context))
                                    {
                                        break;
                                    }
                                }

                            FileSystemHelper.Copy(feedFile.FileTempPath, feedFile.FilePath);

                            if (secondFileName.HasValue())
                            {
                                FileSystemHelper.Copy(context.SecondFilePath, feedFile.CustomProperties["SecondFilePath"] as string);
                            }
                        }
                    }
                }
            }
            finally
            {
                AsyncState.Current.Remove <FeedFileCreationProgress>(SystemName);
            }
        }
Example #8
0
        public async Task <IQueryable <UploadImportFile> > ImportFiles()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw this.ExceptionUnsupportedMediaType();
            }

            ImportProfile profile    = null;
            string        identifier = null;
            var           tempDir    = FileSystemHelper.TempDir(Guid.NewGuid().ToString());
            var           provider   = new MultipartFormDataStreamProvider(tempDir);

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);
            }
            catch (Exception exception)
            {
                FileSystemHelper.ClearDirectory(tempDir, true);
                throw this.ExceptionInternalServerError(exception);
            }

            // find import profile
            if (provider.FormData.AllKeys.Contains("Id"))
            {
                identifier = provider.FormData.GetValues("Id").FirstOrDefault();
                profile    = _importProfileService.Value.GetImportProfileById(identifier.ToInt());
            }
            else if (provider.FormData.AllKeys.Contains("Name"))
            {
                identifier = provider.FormData.GetValues("Name").FirstOrDefault();
                profile    = _importProfileService.Value.GetImportProfileByName(identifier);
            }

            if (profile == null)
            {
                FileSystemHelper.ClearDirectory(tempDir, true);
                throw this.ExceptionNotFound(WebApiGlobal.Error.EntityNotFound.FormatInvariant(identifier.NaIfEmpty()));
            }

            var deleteExisting = false;
            var result         = new List <UploadImportFile>();
            var unzippedFiles  = new List <MultipartFileData>();
            var importFolder   = profile.GetImportFolder(true, true);
            var csvTypes       = new string[] { ".csv", ".txt", ".tab" };

            if (provider.FormData.AllKeys.Contains("deleteExisting"))
            {
                var strDeleteExisting = provider.FormData.GetValues("deleteExisting").FirstOrDefault();
                deleteExisting = (strDeleteExisting.HasValue() && strDeleteExisting.ToBool());
            }

            // unzip files
            foreach (var file in provider.FileData)
            {
                var import = new UploadImportFile(file.Headers);

                if (import.FileExtension.IsCaseInsensitiveEqual(".zip"))
                {
                    var subDir = Path.Combine(tempDir, Guid.NewGuid().ToString());
                    ZipFile.ExtractToDirectory(file.LocalFileName, subDir);
                    FileSystemHelper.Delete(file.LocalFileName);

                    foreach (var unzippedFile in Directory.GetFiles(subDir, "*.*"))
                    {
                        var content = CloneHeaderContent(unzippedFile, file);
                        unzippedFiles.Add(new MultipartFileData(content.Headers, unzippedFile));
                    }
                }
                else
                {
                    unzippedFiles.Add(new MultipartFileData(file.Headers, file.LocalFileName));
                }
            }

            // copy files to import folder
            if (unzippedFiles.Any())
            {
                using (_rwLock.GetWriteLock())
                {
                    if (deleteExisting)
                    {
                        FileSystemHelper.ClearDirectory(importFolder, false);
                    }

                    foreach (var file in unzippedFiles)
                    {
                        var import   = new UploadImportFile(file.Headers);
                        var destPath = Path.Combine(importFolder, import.FileName);

                        import.Exists = File.Exists(destPath);

                        switch (profile.FileType)
                        {
                        case ImportFileType.XLSX:
                            import.IsSupportedByProfile = import.FileExtension.IsCaseInsensitiveEqual(".xlsx");
                            break;

                        case ImportFileType.CSV:
                            import.IsSupportedByProfile = csvTypes.Contains(import.FileExtension, StringComparer.OrdinalIgnoreCase);
                            break;
                        }

                        import.Inserted = FileSystemHelper.Copy(file.LocalFileName, destPath);

                        result.Add(import);
                    }
                }
            }

            FileSystemHelper.ClearDirectory(tempDir, true);
            return(result.AsQueryable());
        }
Example #9
0
        internal static async Task Run()
        {
            TimeTaken.Start();
            foreach (FileInfo inFile in SourceFiles)
            {
                FileInfo outFile = new FileInfo(inFile.FullName.Replace(inFile.DirectoryName, Program.Settings.DestinationDirectory.FullName)
                                                .Replace(inFile.Extension, "." + Program.Settings.ConvertToNonAlphaValue.ToString().ToLower()));

                if (!inFile.Extension.ContainsAny(".png", ".jpg", ".bmp", ".gif"))
                {
                    if (Program.Settings.CopySkippedFiles)
                    {
                        await FileSystemHelper.Copy(inFile, new FileInfo(outFile.FullName.Replace(outFile.Extension, inFile.Extension)), true);
                    }
                    IncompatibleFilesCopiedOver++;
                    if (!Program.CommandMode)
                    {
                        Program.Form.IncrementOverallProgress();
                    }
                    continue;
                }

                if (!Program.CommandMode)
                {
                    Program.Form.Invoke((MethodInvoker) delegate()
                    {
                        Program.Form.CurrentFileLabel.Text = "File: " + inFile.Name;
                    });
                }

                using (FileStream inStream = await FileIOHelper.OpenStream(inFile))
                {
                    byte[] imgData = new byte[inStream.Length];
                    await inStream.ReadAsync(imgData);

                    using MemoryStream memStr = new MemoryStream(imgData);
                    using Bitmap map          = new Bitmap(memStr);
                    bool isAlphaPresent = map.PixelFormat == PixelFormat.Format16bppArgb1555 || map.PixelFormat == PixelFormat.Format32bppArgb ||
                                          map.PixelFormat == PixelFormat.Format32bppPArgb || map.PixelFormat == PixelFormat.Format64bppArgb ||
                                          map.PixelFormat == PixelFormat.Format64bppPArgb;

                    if (Program.Settings.DownsizeLargerResolutionImages && (map.Width <= Program.Settings.TargetImageWidth || map.Height <= Program.Settings.TargetImageHeight))
                    {
                        if (Program.Settings.CopySkippedFiles)
                        {
                            await FileSystemHelper.Copy(inFile, new FileInfo(outFile.FullName.Replace(outFile.Extension, inFile.Extension)), true);
                        }
                        if (!Program.CommandMode)
                        {
                            Program.Form.IncrementOverallProgress();
                        }
                        continue;
                    }

                    if (map.Width != map.Height && Program.Settings.OnlyPassSquareImages)
                    {
                        if (!Program.CommandMode)
                        {
                            Program.Form.IncrementOverallProgress();
                        }
                        continue;
                    }

                    if (Program.Settings.UseAlphaFormatOnly || isAlphaPresent)
                    {
                        outFile = new FileInfo(inFile.FullName.Replace(inFile.DirectoryName, Program.Settings.DestinationDirectory.FullName)
                                               .Replace(inFile.Extension, "." + Program.Settings.ConvertToAlphaValue.ToString().ToLower()));
                    }

                    using FileStream outStream = outFile.Create();
                    using (Image image = Image.Load(imgData, out IImageFormat format))
                    {
                        string ConvertToAlphaString    = Program.Settings.ConvertToAlphaValue.ToString();
                        string ConvertToNonAlphaString = Program.Settings.ConvertToNonAlphaValue.ToString();

                        image.Mutate(c =>
                        {
                            c.Resize(Program.Settings.TargetImageWidth != 0 ? Program.Settings.TargetImageWidth : map.Width, Program.Settings.TargetImageHeight != 0 ? Program.Settings.TargetImageHeight : map.Height);
                        });

                        if (Program.Settings.UseAlphaFormatOnly || isAlphaPresent)
                        {
                            ConvertTransparentFormat();
                        }
                        else
                        {
                            ConvertNonTransparentFormat();
                        }
                        ProcessedImageCount++;

                        void ConvertNonTransparentFormat()
                        {
                            if (ConvertToNonAlphaString == "JPG")
                            {
                                image.SaveAsJpeg(outStream, new JpegEncoder
                                {
                                    Quality = 100 - Program.Settings.CompressionLevel
                                });
                                LogConversionState();
                            }
                            else if (ConvertToNonAlphaString == "BMP")
                            {
                                image.SaveAsBmp(outStream);
                                LogConversionState();
                            }
                        }

                        void ConvertTransparentFormat()
                        {
                            if (ConvertToAlphaString == "PNG")
                            {
                                image.SaveAsPng(outStream, new PngEncoder
                                {
                                    CompressionLevel = Program.Settings.CompressionLevel == 0 ? PngCompressionLevel.Level0 :
                                                       Program.Settings.CompressionLevel == 10 ? PngCompressionLevel.Level1 :
                                                       Program.Settings.CompressionLevel == 20 ? PngCompressionLevel.Level2 :
                                                       Program.Settings.CompressionLevel == 30 ? PngCompressionLevel.Level3 :
                                                       Program.Settings.CompressionLevel == 40 ? PngCompressionLevel.Level4 :
                                                       Program.Settings.CompressionLevel == 50 ? PngCompressionLevel.Level5 :
                                                       Program.Settings.CompressionLevel == 60 ? PngCompressionLevel.Level6 :
                                                       Program.Settings.CompressionLevel == 70 ? PngCompressionLevel.Level7 :
                                                       Program.Settings.CompressionLevel == 80 ? PngCompressionLevel.Level8 :
                                                       Program.Settings.CompressionLevel == 90 ? PngCompressionLevel.Level9 : PngCompressionLevel.Level9
                                });
                                LogConversionState();
                            }
                            else if (ConvertToAlphaString == "GIF")
                            {
                                image.SaveAsGif(outStream);
                                LogConversionState();
                            }
                        }

                        void LogConversionState()
                        {
                            if (Program.Settings.TargetImageWidth != 0 || Program.Settings.TargetImageHeight != 0 && outFile.Extension != inFile.Extension)
                            {
                                AddLog("Resized " + inFile.Name + " to " + Program.Settings.TargetImageWidth + "x" + Program.Settings.TargetImageHeight + " & converted to " + outFile.Extension.ToUpper()[1..] + " | Reduction " + GetPercentageReduction().ToString("0.00") + "%.");
                            }
        private void progressDialog_PerformProcessing(object sender, EventArgs e)
        {
            var albumArtist = "";

            Invoke((MethodInvoker) delegate { albumArtist = cmbAlbumArtist.Text; });

            var destinationFolder = txtOutputFolder.Text;

            if (chkCreateSubfolder.Checked)
            {
                destinationFolder = Path.Combine(destinationFolder,
                                                 FileSystemHelper.StripInvalidFileNameChars(txtAlbumName.Text));
                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);
                }
            }


            try
            {
                FileSystemHelper.DeleteFiles(destinationFolder, "*.mp3;*.jpg", false);
            }
            catch
            {
                // ignored
            }

            foreach (var track in Tracks.TakeWhile(track => !progressDialog.Cancelled))
            {
                progressDialog.Text     = "Exporting " + track.Description;
                progressDialog.Details += "Copying track " + track.Description + "...";

                var destination = Path.Combine(destinationFolder, Path.GetFileName(track.Filename));
                try
                {
                    FileSystemHelper.Copy(track.Filename, destination);
                    if (progressDialog.Cancelled)
                    {
                        break;
                    }


                    var destinationTrack = Library.LoadNonLibraryTrack(destination);

                    destinationTrack.AlbumArtist = albumArtist;
                    destinationTrack.Album       = txtAlbumName.Text;
                    if (chkTrackNumbers.Checked)
                    {
                        destinationTrack.TrackNumber = Tracks.IndexOf(track) + 1;
                    }
                    else
                    {
                        destinationTrack.TrackNumber = 0;
                    }

                    Library.SaveNonLibraryTrack(destinationTrack);

                    if (AlbumImage != null)
                    {
                        Library.SetTrackAlbumCover(destinationTrack, AlbumImage);
                    }


                    if (progressDialog.Cancelled)
                    {
                        break;
                    }

                    progressDialog.Details += "Done" + Environment.NewLine;
                }
                catch (Exception exception)
                {
                    var message = string.Format("{0}ERROR: Could not copy file '{1}' to '{2}'{0}{3}{0}",
                                                Environment.NewLine,
                                                track.Description,
                                                destinationFolder,
                                                exception.Message);

                    progressDialog.Details += message;

                    if (File.Exists(destination))
                    {
                        try
                        {
                            File.Delete(destination);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
                progressDialog.Value++;
            }

            if (AlbumImage != null)
            {
                ImageHelper.SaveJpg(Path.Combine(destinationFolder, "folder.jpg"), AlbumImage);
            }

            progressDialog.Text = "Export completed.";

            var settings = Settings.Default;

            settings.ExportPlaylistFolder = txtOutputFolder.Text;
            settings.Save();
        }
Example #11
0
        private void progressDialog_PerformProcessing(object sender, EventArgs e)
        {
            var destinationFolder = txtOutputFolder.Text;

            if (chkCreateSubfolder.Checked)
            {
                destinationFolder = Path.Combine(destinationFolder,
                                                 FileSystemHelper.StripInvalidFileNameChars("Library"));

                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);
                }
            }

            try
            {
                FileSystemHelper.DeleteFiles(destinationFolder, "*.mp3;*.jpg", true);
            }
            catch
            {
                // ignored
            }

            foreach (var track in _tracks.TakeWhile(track => !progressDialog.Cancelled))
            {
                progressDialog.Text     = "Exporting " + track.Description;
                progressDialog.Details += "Copying track " + track.Description + "...";

                var destinationFile      = track.Filename.Replace(Library.LibraryFolder, destinationFolder);
                var destinationSubFolder = Path.GetDirectoryName(destinationFile) + "";

                var albumArt            = Path.GetDirectoryName(track.Filename) + @"\folder.jpg";
                var destinationAlbumArt = Path.GetDirectoryName(track.Filename) + @"\folder.jpg";

                try
                {
                    if (!Directory.Exists(destinationSubFolder))
                    {
                        Directory.CreateDirectory(destinationSubFolder);
                    }

                    if (!File.Exists(destinationAlbumArt) && File.Exists(albumArt))
                    {
                        FileSystemHelper.Copy(albumArt, destinationAlbumArt);
                    }

                    FileSystemHelper.Copy(track.Filename, destinationFile);
                    if (progressDialog.Cancelled)
                    {
                        break;
                    }

                    progressDialog.Details += "Done" + Environment.NewLine;
                }
                catch (Exception exception)
                {
                    var message = string.Format("{0}ERROR: Could not copy file '{1}' to '{2}'{0}{3}{0}",
                                                Environment.NewLine,
                                                track.Description,
                                                destinationFolder,
                                                exception.Message);

                    progressDialog.Details += message;

                    if (File.Exists(destinationFile))
                    {
                        try
                        {
                            File.Delete(destinationFile);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
                progressDialog.Value++;
            }


            progressDialog.Text = "Export completed.";

            var settings = Settings.Default;

            settings.ExportPlaylistFolder = txtOutputFolder.Text;
            settings.Save();
        }