public LastSaveDirectoryHelper(ICurrentSettingsProvider currentSettingsProvider, ISettingsManager settingsManager, ITempFolderProvider tempFolderProvider, IPathUtil pathUtil) { _currentSettingsProvider = currentSettingsProvider; _settingsManager = settingsManager; _tempFolderProvider = tempFolderProvider; _pathUtil = pathUtil; }
public void SetUp() { _job = new Job(new JobInfo(), new ConversionProfile(), new JobTranslations(), new Accounts()); _job.OutputFilenameTemplate = "MayNotStartWithTempfolder.pdf"; _job.OutputFiles.Add("NotEmpty.pdf"); _storedHistory = new List <HistoricJob>(); _jobHistoryStorage = Substitute.For <IJobHistoryStorage>(); for (var i = 0; i < _capacity; i++) { _storedHistory.Add(new HistoricJob(_job)); } _jobHistoryStorage.Load().Returns(_storedHistory); var settingsProvider = Substitute.For <ISettingsProvider>(); _settings = new PdfCreatorSettings(null); _settings.ApplicationSettings.JobHistory.Enabled = true; _settings.ApplicationSettings.JobHistory.Capacity = _capacity; settingsProvider.Settings.Returns(_settings); _tempFolderProvider = Substitute.For <ITempFolderProvider>(); _tempFolderProvider.TempFolder.Returns(TempFolder); _file = Substitute.For <IFile>(); _file.Exists(Arg.Any <string>()).Returns(true); _jobHistoryManager = new JobHistoryManager(settingsProvider, _jobHistoryStorage, _tempFolderProvider, _file); }
/// <summary> /// Create a new GhostscriptJob instance /// </summary> /// <param name="jobInfo">JobInfo of the job to convert</param> /// <param name="profile">Profile that determines the conversion process</param> /// <param name="tempFolder"> /// TempFolderProvider that gives the full Temp path, i.e. C:\Users\Admin\Local /// Settings\Temp\clawPDF /// </param> /// <param name="jobTranslations">Translations needed for the job</param> /// <param name="fileWrap">Only for testing</param> /// <param name="directoryWrap">Only for testing</param> public GhostscriptJob(IJobInfo jobInfo, ConversionProfile profile, JobTranslations jobTranslations, ITempFolderProvider tempFolder, IFile fileWrap, IDirectory directoryWrap) : base(jobInfo, profile, jobTranslations, fileWrap, directoryWrap) { var gsVersion = new GhostscriptDiscovery().GetBestGhostscriptInstance(); if (gsVersion == null) { Logger.Error("No valid Ghostscript version found."); throw new InvalidOperationException("No valid Ghostscript version found."); } Logger.Debug("Ghostscript Version: " + gsVersion.Version + " loaded from " + gsVersion.DllPath); _ghostScript = new GhostScript(gsVersion); JobTempFolder = PathSafe.Combine(tempFolder.TempFolder, "Job_" + PathSafe.GetFileNameWithoutExtension(PathSafe.GetRandomFileName())); JobTempOutputFolder = PathSafe.Combine(JobTempFolder, "tempoutput"); DirectoryWrap.CreateDirectory(JobTempFolder); DirectoryWrap.CreateDirectory(JobTempOutputFolder); // Shorten the temp folder for GS compatibility //缩短临时文件夹以实现GS兼容性 JobTempFolder = JobTempFolder; }
public UpdateHelper(IDirectory directory, IFile systemFile, ITempFolderProvider tempFolderProvider, IHashUtil hashUtil) { _directory = directory; _systemFile = systemFile; _tempFolderProvider = tempFolderProvider; _hashUtil = hashUtil; OnlineVersion = new ApplicationVersion(new Version(0, 0, 0, 0), "", "", new List <Release>()); }
public UpdateDownloader(IDirectory directory, IFile systemFile, ITempFolderProvider tempFolderProvider, IHashUtil hashUtil, ICancellationTokenSourceFactory cancellationSourceFactory) { _directory = directory; _systemFile = systemFile; _tempFolderProvider = tempFolderProvider; _hashUtil = hashUtil; _cancellationSourceFactory = cancellationSourceFactory; }
public UpdateDownloadWindowViewModel(IDirectory directory, IFile file, ITempFolderProvider tempFolderProvider) { _directory = directory; _file = file; _tempFolderProvider = tempFolderProvider; _dispatcher = Dispatcher.CurrentDispatcher; CancelCommand = new DelegateCommand(ExecuteCancel); }
public PrintJobViewModel( ISettingsProvider settingsProvider, ITranslationUpdater translationUpdater, IJobInfoQueue jobInfoQueue, IFileNameQuery saveFileQuery, IInteractionRequest interactionRequest, IProfileChecker profileChecker, ErrorCodeInterpreter errorCodeInterpreter, ICommandLocator commandsLocator, IEventAggregator eventAggregator, ISelectedProfileProvider selectedProfileProvider, ITempFolderProvider tempFolderProvider, IPathUtil pathUtil, IFile file, IGpoSettings gpoSettings) : base(translationUpdater) { GpoSettings = gpoSettings; _settingsProvider = settingsProvider; _saveFileQuery = saveFileQuery; _profileChecker = profileChecker; _interactionRequest = interactionRequest; _errorCodeInterpreter = errorCodeInterpreter; _selectedProfileProvider = selectedProfileProvider; _file = file; _tempFolderProvider = tempFolderProvider; _pathUtil = pathUtil; SaveCommand = new DelegateCommand(SaveExecute); SendByEmailCommand = new DelegateCommand(EmailExecute); MergeCommand = new DelegateCommand(MergeExecute); CancelCommand = new DelegateCommand(CancelExecute); SetOutputFormatCommand = new DelegateCommand <OutputFormat>(SetOutputFormatExecute); BrowseFileCommand = new DelegateCommand(BrowseFileExecute); SetupEditProfileCommand(commandsLocator, eventAggregator); var settings = settingsProvider.Settings?.CopyAndPreserveApplicationSettings(); Profiles = settings?.ConversionProfiles; jobInfoQueue.OnNewJobInfo += (sender, args) => UpdateNumberOfPrintJobsHint(jobInfoQueue.Count); UpdateNumberOfPrintJobsHint(jobInfoQueue.Count); var profileListView = CollectionViewSource.GetDefaultView(Profiles); if (profileListView != null) { profileListView.CurrentChanged += (sender, args) => { if (Job != null) { OutputFormat = ((ConversionProfile)profileListView.CurrentItem).OutputFormat; } }; } }
public InteractiveTargetFileNameComposer(IFileNameQuery fileNameQuery, IInteractionInvoker interactionInvoker, IPathUtil pathUtil, ITempFolderProvider tempFolderProvider, IJobDataUpdater jobDataUpdater, IOutputFilenameComposer outputFilenameComposer) { _fileNameQuery = fileNameQuery; _interactionInvoker = interactionInvoker; _pathUtil = pathUtil; _tempFolderProvider = tempFolderProvider; _jobDataUpdater = jobDataUpdater; _outputFilenameComposer = outputFilenameComposer; }
public static IJob CreateJob(IJobInfo jobInfo, ConversionProfile conversionProfile, ITempFolderProvider tempFolder, JobTranslations jobTranslations) { if (jobInfo.JobType == JobType.XpsJob) { return(new XpsJob(jobInfo, conversionProfile, jobTranslations)); } return(new GhostscriptJob(jobInfo, conversionProfile, tempFolder, jobTranslations)); }
public JobHistoryManager(ISettingsProvider settingsProvider, IJobHistoryStorage jobHistroryStorage, ITempFolderProvider tempFolderProvider, IFile file, IHashUtil hashUtil) { History = new List <HistoricJob>(); _settingsProvider = settingsProvider; _jobHistoryStorage = jobHistroryStorage; _tempFolderProvider = tempFolderProvider; _file = file; _hashUtil = hashUtil; _settingsProvider.SettingsChanged += (sender, args) => UpdateCapacity(); }
public JobHistoryActiveRecord(ISettingsProvider settingsProvider, IJobHistoryStorage jobHistoryStorage, ITempFolderProvider tempFolderProvider, IFile file, IHashUtil hashUtil, IGpoSettings gpoSettings) { History = new List <HistoricJob>(); _settingsProvider = settingsProvider; _jobHistoryStorage = jobHistoryStorage; _tempFolderProvider = tempFolderProvider; _file = file; _hashUtil = hashUtil; _gpoSettings = gpoSettings; _settingsProvider.SettingsChanged += (sender, args) => UpdateCapacity(); }
public UpdateDownloadWindowViewModel(IDirectory directory, IFile file, ITempFolderProvider tempFolderProvider, ITranslationUpdater translationUpdater, IReadableFileSizeFormatter readableFileSizeFormatter, ApplicationNameProvider applicationNameProvider) : base(translationUpdater) { _directory = directory; _file = file; _tempFolderProvider = tempFolderProvider; _readableFileSizeFormatter = readableFileSizeFormatter; _applicationNameProvider = applicationNameProvider; _dispatcher = Dispatcher.CurrentDispatcher; CancelCommand = new DelegateCommand(ExecuteCancel); }
public JobRunner(ITokenReplacerFactory tokenReplacerFactory, IPdfProcessor processor, IConverterFactory converterFactory, IActionManager actionManager, IJobCleanUp jobClean, ITempFolderProvider tempFolderProvider, IDirectory directory, IDirectoryHelper directoryHelper) { _tokenReplacerFactory = tokenReplacerFactory; _processor = processor; _converterFactory = converterFactory; _actionManager = actionManager; _jobClean = jobClean; _tempFolderProvider = tempFolderProvider; _directory = directory; _directoryHelper = directoryHelper; }
public JobRunner(IOutputFileMover outputFileMover, ITokenReplacerFactory tokenReplacerFactory, IPdfProcessor processor, IConverterFactory converterFactory, IActionManager actionManager, IJobCleanUp jobClean, ITempFolderProvider tempFolderProvider, IDirectory directory, IConversionProgress conversionProgress) { _outputFileMover = outputFileMover; _tokenReplacerFactory = tokenReplacerFactory; _processor = processor; _converterFactory = converterFactory; _actionManager = actionManager; _jobClean = jobClean; _tempFolderProvider = tempFolderProvider; _directory = directory; _conversionProgress = conversionProgress; }
public OnlineVersionHelper(UpdateInformationProvider updateInformationProvider, ITempFolderProvider tempFolderProvider, IVersionHelper versionHelper, IUpdateChangeParser changeParser, IFileCacheFactory fileCacheFactory, IDownloader downloader, ICurrentSettings <ApplicationSettings> applicationSettingsProvider) { _updateInformationProvider = updateInformationProvider; _tempFolderProvider = tempFolderProvider; _versionHelper = versionHelper; _changeParser = changeParser; _fileCacheFactory = fileCacheFactory; _downloader = downloader; _applicationSettingsProvider = applicationSettingsProvider; if (_applicationSettingsProvider != null) { _fileCache = GetFileCache(); _applicationSettingsProvider.SettingsChanged += ApplicationSettingsProviderOnSettingsChanged; } _onlineVersion = new ApplicationVersion(new System.Version(0, 0, 0, 0), "", "", new List <Release>()); }
public Tester( IFileSystem fileSystem, IEnvironmentTemporaryDirectoryProvider temporaryDirectoryProvider, ITempFolderProvider tempFolderProvider, IPrintErrorMessage printErrorMessage, IAvailableProjectsRetriever availableProjectsRetriever, IModifyRunnerProjects modifyRunnerProjects, IBuild build) { _fileSystem = fileSystem; _temporaryDirectoryProvider = temporaryDirectoryProvider; _tempFolderProvider = tempFolderProvider; _printErrorMessage = printErrorMessage; _availableProjectsRetriever = availableProjectsRetriever; _modifyRunnerProjects = modifyRunnerProjects; _build = build; }
public void SetUp() { _currentSettings = new PdfCreatorSettings(null); _currentSettingsProvider = Substitute.For <ICurrentSettingsProvider>(); _currentSettingsProvider.Settings.Returns(_currentSettings); _settingsManager = Substitute.For <ISettingsManager>(); _tempFolderProvider = Substitute.For <ITempFolderProvider>(); _tempFolderProvider.TempFolder.Returns(TempFolder); var pathUtil = new PathUtil(Substitute.For <IPath>(), Substitute.For <IDirectory>()); _lastSaveDirectoryHelper = new LastSaveDirectoryHelper(_currentSettingsProvider, _settingsManager, _tempFolderProvider, pathUtil); _job = new Job(new JobInfo(), new ConversionProfile(), new JobTranslations(), new Accounts()); _job.OutputFilenameTemplate = _outputFilenameTemplate; }
public void SetUp() { _job = new Job(new JobInfo(), new ConversionProfile(), new JobTranslations(), new Accounts()); _job.OutputFilenameTemplate = "MayNotStartWithTempfolder.pdf"; _job.OutputFiles.Add("NotEmpty.pdf"); _storedHistoryFullCapacity = new List <HistoricJob>(); _jobHistoryStorage = Substitute.For <IJobHistoryStorage>(); _storedHistoryFullCapacity = new List <HistoricJob>(); var hjPdf = new HistoricFile(@"X:\Foldername\PeeDeeEff.pdf", "PeeDeeEff.pdf", @"X:\Foldername\", "ABC123"); var historicFiles = new List <HistoricFile> { hjPdf }; for (int i = 0; i < _capacity; i++) { _storedHistoryFullCapacity.Add(new HistoricJob(historicFiles, OutputFormat.Pdf, DateTime.Now, new Metadata(), 23, false)); } _jobHistoryStorage.Load().Returns(_storedHistoryFullCapacity); var settingsProvider = Substitute.For <ISettingsProvider>(); _settings = new PdfCreatorSettings(null); _settings.ApplicationSettings.JobHistory.Enabled = true; _settings.ApplicationSettings.JobHistory.Capacity = _capacity; settingsProvider.Settings.Returns(_settings); _tempFolderProvider = Substitute.For <ITempFolderProvider>(); _tempFolderProvider.TempFolder.Returns(TempFolder); _file = Substitute.For <IFile>(); _file.Exists(Arg.Any <string>()).Returns(true); _hashUtil = Substitute.For <IHashUtil>(); _jobHistoryManager = new JobHistoryManager(settingsProvider, _jobHistoryStorage, _tempFolderProvider, _file, _hashUtil); }
public RssFeedViewModel(ICommandLocator commandLocator, ICurrentSettings <Conversion.Settings.RssFeed> rssFeedSettingsProvider, IGpoSettings gpoSettings, ITranslationUpdater translationUpdater, IWelcomeSettingsHelper welcomeSettingsHelper, IRssService rssService, IFileCacheFactory fileCacheFactory, ITempFolderProvider tempFolderProvider) : base(translationUpdater) { _rssFeedSettingsProvider = rssFeedSettingsProvider; _gpoSettings = gpoSettings; _rssService = rssService; _fileCacheFactory = fileCacheFactory; _tempFolderProvider = tempFolderProvider; _feedItems = new List <FeedItem>(); _fileCache = GetFileCache(); ShowWelcome = welcomeSettingsHelper.CheckIfRequiredAndSetCurrentVersion(); //Because the CheckIfRequiredAndSetCurrentVersion() sets the version in the registry, RaisePropertyChanged(nameof(ShowWelcome)); // ShowWelcome has to be set here in the ctor and not directly in the property UrlOpenCommand = commandLocator.GetCommand <UrlOpenCommand>(); ShowRssFeedCommand = new DelegateCommand(ShowRssFeed); ShowWelcomeWindow(); }
public static void ParseBackup( [NotNull] string pathToBackup, BackupType backupType, [NotNull] string resultInternalDataPath, [NotNull] string resultExternalDataPath, //[NotNull] string resultObbPath, [NotNull] ITempFolderProvider tempFolderProvider ) { Guard.NotNullArgument(pathToBackup, nameof(pathToBackup)); Guard.NotNullArgument(resultInternalDataPath, nameof(resultInternalDataPath)); Guard.NotNullArgument(resultExternalDataPath, nameof(resultExternalDataPath)); //Guard.NotNullArgument(resultObbPath, nameof(resultObbPath)); Guard.NotNullArgument(tempFolderProvider, nameof(tempFolderProvider)); switch (backupType) { case BackupType.Titanium: { #region Структура /* * * data * data * .external.appname * . * данные * appname * . * данные */ #endregion using (var extractedBackup = TempUtils.UseTempFolder(tempFolderProvider)) { ExtractTarByEntry(pathToBackup, extractedBackup.TempFolder); string path = Path.Combine(extractedBackup.TempFolder, "data", "data"); foreach (string dir in Directory.EnumerateDirectories(path)) { string dirName = Path.GetFileName(dir); if (string.IsNullOrEmpty(dirName)) { continue; } switch (dirName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[0]) { case "external obb": //CreateArchive(dir, resultObbPath); break; case "external": CreateArchive(dir, resultExternalDataPath); break; default: CreateArchive(dir, resultInternalDataPath); break; } } } break; } case BackupType.RomToolbox: { #region Структура /* * * data * data * appname * данные * storage\emulated\legacy * Android * data * appname * данные * */ #endregion using (var extractedBackup = TempUtils.UseTempFolder(tempFolderProvider)) { ExtractTarByEntry(pathToBackup, extractedBackup.TempFolder); IEnumerable <string> firstLevelDirs = Directory.EnumerateDirectories(extractedBackup.TempFolder); foreach (string firstLevelDir in firstLevelDirs) { if (Path.GetFileName(firstLevelDir) == "data") { string path = Path.Combine(firstLevelDir, "data"); string dir = Directory.EnumerateDirectories(path).FirstOrDefault(); if (dir == default) { continue; } CreateArchive(dir, Path.Combine(resultInternalDataPath)); } else { string dir = Directory.EnumerateDirectories(firstLevelDir, "Android", SearchOption.AllDirectories).FirstOrDefault(); if (dir == default) { continue; } string path = Path.Combine(dir, "data"); string dir2 = Directory.EnumerateDirectories(path).FirstOrDefault(); if (dir2 == default) { continue; } CreateArchive(dir2, resultExternalDataPath); } } } break; } case BackupType.LuckyPatcher: { #region Структура /* * * appname * data.lpbkp * данные * sddata.lpbkp * данные * */ #endregion string dataFile = Path.Combine(pathToBackup, "data.lpbkp"); string sddataFile = Path.Combine(pathToBackup, "sddata.lpbkp"); if (File.Exists(dataFile)) { File.Move(dataFile, resultInternalDataPath); } if (File.Exists(sddataFile)) { File.Move(sddataFile, resultExternalDataPath); } break; } default: throw new NotSupportedException($"`{backupType}` is not supported at the moment"); } }
private void ProcessAll() { Dispatcher.Invoke(LogBox.Clear); Log( string.Format( "{0}{1}Start{1}{0}ExePath = {2}{0}Resources = {3}", Environment.NewLine, Line, _globalVariables.PathToExe, _globalVariables.PathToResources ) ); const int totalSteps = 3; _visualProgress.SetBarUsual(); _visualProgress.ShowBar(); _taskBarManager.SetProgress(0); _taskBarManager.SetUsualState(); void SetStep(int currentStep, string status) { int percentage = (currentStep - 1) * 100 / totalSteps; _visualProgress.SetBarValue(percentage); _visualProgress.SetLabelText(status); _taskBarManager.SetProgress(percentage); } #region Инициализация SetStep(1, MainResources.StepInitializing); _visualProgress.ShowIndeterminateLabel(); string sourceApkPath = ViewModel.CurrentApk.Value; bool alternativeSigning = _settings.AlternativeSigning; string popupText = ViewModel.PopupBoxText.Value; int messagesCount = ViewModel.MessagesCount.Value; bool needSave; bool needMessage; { bool onlySave = ViewModel.OnlySave.Value; bool savePlusMessage = ViewModel.SavePlusMess.Value; bool onlyMessage = ViewModel.OnlyMess.Value; needSave = onlySave || savePlusMessage; needMessage = (savePlusMessage || onlyMessage) && !string.IsNullOrEmpty(popupText) && messagesCount > 0; } BackupType backupType = ViewModel.BackupType.Value; ITempFileProvider tempFileProvider = _tempUtils.CreateTempFileProvider(); ITempFolderProvider tempFolderProvider = _tempUtils.CreateTempFolderProvider(); string resultApkPath = sourceApkPath.Remove(sourceApkPath.Length - Path.GetExtension(sourceApkPath).Length) + "_mod.apk"; string pathToSave = ViewModel.CurrentSave.Value; IApktool apktool = _apktoolProvider.Get(); IProcessDataHandler dataHandler = new ProcessDataCombinedHandler(data => Log(data)); #endregion #region Изменение apk using (var tempApk = ATempUtils.UseTempFile(tempFileProvider)) { LFile.Copy(sourceApkPath, tempApk.TempFile, true); #region Добавление данных SetStep(2, MainResources.StepAddingData); var aes = new AesManaged { KeySize = 128 }; aes.GenerateIV(); aes.GenerateKey(); bool backupFilesAdded = false; // adding local and external backup files if (needSave) { using (var internalDataBackup = ATempUtils.UseTempFile(tempFileProvider)) using (var externalDataBackup = ATempUtils.UseTempFile(tempFileProvider)) { ApkModifer.ParseBackup( pathToBackup: pathToSave, backupType: backupType, resultInternalDataPath: internalDataBackup.TempFile, resultExternalDataPath: externalDataBackup.TempFile, tempFolderProvider: tempFolderProvider ); string internalBackup = internalDataBackup.TempFile; string externalBackup = externalDataBackup.TempFile; var fileToAssetsName = new Dictionary <string, string> { { internalBackup, "data.save" }, { externalBackup, "extdata.save" } }; foreach (var(file, assetsName) in fileToAssetsName.Enumerate()) { if (!LFile.Exists(file) || FileUtils.FileLength(file) == 0) { continue; } using (var tempEncrypted = ATempUtils.UseTempFile(tempFileProvider)) { CommonUtils.EncryptFile( filePath: file, outputPath: tempEncrypted.TempFile, iv: aes.IV, key: aes.Key ); ApkModifer.AddFileToZip( zipPath: tempApk.TempFile, filePath: tempEncrypted.TempFile, pathInZip: "assets/" + assetsName, newEntryCompression: CompressionType.Store ); } backupFilesAdded = true; } } } // adding smali file for restoring if (backupFilesAdded || needMessage) { using (var decompiledFolder = ATempUtils.UseTempFolder(tempFolderProvider)) { apktool.Baksmali( apkPath: tempApk.TempFile, resultFolder: decompiledFolder.TempFolder, tempFolderProvider: tempFolderProvider, dataHandler: dataHandler ); var manifestPath = Path.Combine(decompiledFolder.TempFolder, "AndroidManifest.xml"); apktool.ExtractSimpleManifest( apkPath: tempApk.TempFile, resultManifestPath: manifestPath, tempFolderProvider: tempFolderProvider ); // have to have smali folders in the same directory as manifest // to find the main smali var manifest = new AndroidManifest(manifestPath); if (manifest.MainSmaliFile == null) { throw new Exception("main smali file not found"); } // using this instead of just pasting "folder/smali" as there can be // no smali folder sometimes (smali_1, etc) string smaliDir = manifest.MainSmaliPath.Substring(decompiledFolder.TempFolder.Length + 1); smaliDir = smaliDir.Substring(0, smaliDir.IndexOf(Path.DirectorySeparatorChar)); string saveGameDir = Path.Combine(decompiledFolder.TempFolder, smaliDir, "com", "savegame"); LDirectory.CreateDirectory(saveGameDir); CommonUtils.GenerateAndSaveSmali( filePath: Path.Combine(saveGameDir, "SavesRestoringPortable.smali"), iv: aes.IV, key: aes.Key, addSave: backupFilesAdded, message: needMessage ? popupText : string.Empty, messagesCount: needMessage ? messagesCount : 0 ); manifest.MainSmaliFile.AddTextToMethod(FileResources.MainSmaliCall); manifest.MainSmaliFile.Save(); using (var folderWithDexes = ATempUtils.UseTempFolder(tempFolderProvider)) { apktool.Smali( folderWithSmali: decompiledFolder.TempFolder, resultFolder: folderWithDexes.TempFolder, dataHandler: dataHandler ); string[] dexes = LDirectory.GetFiles(folderWithDexes.TempFolder, "*.dex"); ApkModifer.AddFilesToZip( zipPath: tempApk.TempFile, filePaths: dexes, pathsInZip: Array.ConvertAll(dexes, Path.GetFileName), newEntryCompression: CompressionType.Store ); } } } #endregion #region Подпись SetStep(3, MainResources.StepSigning); Log(Line); Log(MainResources.StepSigning); Log(Line); apktool.Sign( sourceApkPath: tempApk.TempFile, signedApkPath: resultApkPath, tempFileProvider: tempFileProvider, dataHandler: dataHandler, deleteMetaInf: !alternativeSigning ); #endregion } #endregion _visualProgress.HideIndeterminateLabel(); SetStep(4, MainResources.AllDone); Log(MainResources.AllDone); Log(string.Empty, false); Log($"{MainResources.Path_to_file} {resultApkPath}"); _globalVariables.LatestModdedApkPath = resultApkPath; if (_settings.Notifications) { _notificationManager.Show( title: MainResources.Information_Title, text: MainResources.ModificationCompletedContent ); } string dialogResult = MessBox.ShowDial( $"{MainResources.Path_to_file} {resultApkPath}", MainResources.Successful, MainResources.OK, MainResources.Open, MainResources.Install ); _visualProgress.HideBar(); _taskBarManager.SetNoneState(); if (dialogResult == MainResources.Open) { Process.Start("explorer.exe", $"/select,{resultApkPath}"); } else if (dialogResult == MainResources.Install) { Dispatcher.Invoke(() => _adbInstallWindowProvider.Get().ShowDialog()); } }
protected override void QueryTargetFile() { if (!Job.Profile.SkipPrintDialog) { Job.ApplyMetadata(); var w = new PrintJobWindow(); var model = new PrintJobViewModel(Job.JobInfo, Job.Profile); w.DataContext = model; if ((TopMostHelper.ShowDialogTopMost(w, true) != true) || model.PrintJobAction == PrintJobAction.Cancel) { Cancel = true; WorkflowStep = WorkflowStep.AbortedByUser; return; } if (model.PrintJobAction == PrintJobAction.ManagePrintJobs) { throw new ManagePrintJobsException(); } Job.Profile = model.SelectedProfile.Copy(); Job.ApplyMetadata(); if (model.PrintJobAction == PrintJobAction.EMail) { Job.SkipSaveFileDialog = true; Job.Profile.EmailClient.Enabled = true; Job.Profile.AutoSave.Enabled = false; Job.Profile.OpenViewer = false; } } if (Job.SkipSaveFileDialog) { ITempFolderProvider tempFolderProvider = JobInfoQueue.Instance; var sendFilesFolder = _pathSafe.Combine(tempFolderProvider.TempFolder, "Job" + Job.JobInfo.SourceFiles[0].JobId + "_SendFiles"); Directory.CreateDirectory(sendFilesFolder); var filePath = _pathSafe.Combine(sendFilesFolder, Job.ComposeOutputFilename()); filePath = FileUtil.Instance.EllipsisForTooLongPath(filePath); Job.OutputFilenameTemplate = filePath; } else { var saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = _translator.GetTranslation("InteractiveWorkflow", "SelectDestination", "Select destination"); saveFileDialog.Filter = _translator.GetTranslation("InteractiveWorkflow", "PdfFile", "PDF file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfA1bFile", "PDF/A-1b file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfA2bFile", "PDF/A-2b file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfXFile", "PDF/X file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "JpegFile", "JPEG file") + @" (*.jpg)|*.jpg;*.jpeg;"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PngFile", "PNG file") + @" (*.png)|*.png;"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "TiffFile", "TIFF file") + @" (*.tif)|*.tif;*.tiff"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "TextFile", "Text file") + @" (*.txt)|*.txt;"; saveFileDialog.FilterIndex = ((int)Job.Profile.OutputFormat) + 1; saveFileDialog.OverwritePrompt = true; if (Job.Profile.SaveDialog.SetDirectory) { var saveDirectory = FileUtil.Instance.MakeValidFolderName(Job.TokenReplacer.ReplaceTokens(Job.Profile.SaveDialog.Folder)); DirectoryHelper = new DirectoryHelper(saveDirectory); if (DirectoryHelper.CreateDirectory()) { saveFileDialog.RestoreDirectory = true; saveFileDialog.InitialDirectory = saveDirectory; Logger.Debug("Set directory in save file dialog: " + saveDirectory); } else { Logger.Warn("Could not create directory for save file dialog. It will be opened with default save location."); } } Cancel = !LaunchSaveFileDialog(saveFileDialog); } }
public LastSaveDirectoryHelper(ISettingsProvider settingsProvider, ISettingsManager settingsManager, ITempFolderProvider tempFolderProvider) { _settingsProvider = settingsProvider; _settingsManager = settingsManager; _tempFolderProvider = tempFolderProvider; }
public PdfCreatorFolderCleanUp(ITempFolderProvider tempFolderProvider, ISpoolerProvider spoolFolderProvider, IFolderCleaner folderCleaner) { _tempFolderProvider = tempFolderProvider; _spoolFolderProvider = spoolFolderProvider; _folderCleaner = folderCleaner; }
/// <summary> /// Create a new GhostscriptJob instance /// </summary> /// <param name="jobInfo">JobInfo of the job to convert</param> /// <param name="profile">Profile that determines the conversion process</param> /// <param name="tempFolder"> /// TempFolderProvider that gives the full Temp path, i.e. C:\Users\Admin\Local /// Settings\Temp\clawPDF /// </param> /// <param name="jobTranslations">Translations needed for the job</param> public GhostscriptJob(IJobInfo jobInfo, ConversionProfile profile, ITempFolderProvider tempFolder, JobTranslations jobTranslations) : this(jobInfo, profile, jobTranslations, tempFolder, new FileWrap(), new DirectoryWrap()) { }
private void ProcessAll(byte[] xxhdpiBytes, byte[] xhdpiBytes, byte[] hdpiBytes, byte[] mdpiBytes, Dispatcher uiThreadDispatcher) { const string internalDataInApkName = "data.save"; const string externalDataInApkName = "extdata.save"; IVisualProgress visualProgress = VisualProgress.Value; ITaskBarManager taskBarManager = TaskBarManager.Value; string apkFile = Apk.Value; string saveFile = Save.Value; string androidDataFile = Data.Value; string[] androidObbFiles = (string[])Obb.Value?.Clone() ?? new string[0]; string appTitle = AppTitle.Value; bool alternativeSigning = _settings.AlternativeSigning; BackupType backupType = _settings.BackupType; // initializing visualProgress?.SetBarIndeterminate(); visualProgress?.ShowBar(); visualProgress?.ShowIndeterminateLabel(); taskBarManager?.SetProgress(0); taskBarManager?.SetUsualState(); void SetStep(string step, int stepNumber) { WindowTitle.Value = step; Log(step); const int maxStep = 5; int percentage = (stepNumber - 1) * 100 / maxStep; visualProgress?.SetLabelText(step); taskBarManager?.SetProgress(percentage); } SetStep(MainResources.StepInitializing, 1); string resultFilePath = Path.Combine( Path.GetDirectoryName(apkFile) ?? string.Empty, Path.GetFileNameWithoutExtension(apkFile) + "_mod.apk" ); IApktool apktool = _apktoolProvider.Get(); IProcessDataHandler dataHandler = new ProcessDataCombinedHandler(Log); ITempFileProvider tempFileProvider = _tempUtils.CreateTempFileProvider(); ITempFolderProvider tempFolderProvider = _tempUtils.CreateTempFolderProvider(); using (var stgContainerExtracted = AndroidHelper.Logic.Utils.TempUtils.UseTempFolder(tempFolderProvider)) { // extracting SaveToGame container app SetStep(MainResources.CopyingStgApk, 2); string containerZipPath = Path.Combine(_globalVariables.PathToResources, "apk.zip"); using (var zip = new ZipFile(containerZipPath) { Password = _globalVariables.AdditionalFilePassword }) { zip.ExtractAll(stgContainerExtracted.TempFolder); } SetStep(MainResources.AddingData, 3); // creating assets folder for data string stgContainerAssetsPath = Path.Combine(stgContainerExtracted.TempFolder, "assets"); LDirectory.CreateDirectory(stgContainerAssetsPath); // adding backup if (!string.IsNullOrEmpty(saveFile)) { string internalDataPath = Path.Combine(stgContainerAssetsPath, internalDataInApkName); string externalDataPath = Path.Combine(stgContainerAssetsPath, externalDataInApkName); ApkModifer.ParseBackup( pathToBackup: saveFile, backupType: backupType, resultInternalDataPath: internalDataPath, resultExternalDataPath: externalDataPath, tempFolderProvider: tempFolderProvider ); } // adding external data if (!string.IsNullOrEmpty(androidDataFile)) { LFile.Copy( androidDataFile, Path.Combine(stgContainerAssetsPath, externalDataInApkName) ); } // adding obb files if (androidObbFiles.Length != 0) { using (var obbParts = AndroidHelper.Logic.Utils.TempUtils.UseTempFolder(tempFolderProvider)) { ApkModifer.SplitObbFiles( obbFilePaths: androidObbFiles, partsFolderPath: obbParts.TempFolder, // todo: add progress progressNotifier: null ); string assetsDir = Path.Combine(stgContainerExtracted.TempFolder, "assets", "111111222222333333"); LDirectory.CreateDirectory(assetsDir); IEnumerable <string> filesToAdd = LDirectory.EnumerateFiles(obbParts.TempFolder); foreach (var file in filesToAdd) { LFile.Copy(file, Path.Combine(assetsDir, Path.GetFileName(file))); } } } // adding resigned apk to container using (var sourceResigned = AndroidHelper.Logic.Utils.TempUtils.UseTempFile(tempFileProvider)) { apktool.Sign( sourceApkPath: apkFile, signedApkPath: sourceResigned.TempFile, tempFileProvider: tempFileProvider, dataHandler: dataHandler, deleteMetaInf: !alternativeSigning ); LFile.Copy( sourceFileName: sourceResigned.TempFile, destFileName: Path.Combine(stgContainerAssetsPath, "install.bin"), overwrite: false ); } // modifying AndroidManifest { string pathToManifest = Path.Combine(stgContainerExtracted.TempFolder, "AndroidManifest.xml"); string sourcePackageName; using (var sourceManifest = AndroidHelper.Logic.Utils.TempUtils.UseTempFile(tempFileProvider)) { apktool.ExtractSimpleManifest( apkPath: apkFile, resultManifestPath: sourceManifest.TempFile, tempFolderProvider: tempFolderProvider ); sourcePackageName = new AndroidManifest(sourceManifest.TempFile).Package; } LFile.WriteAllText( pathToManifest, LFile.ReadAllText(pathToManifest, Encoding.UTF8) .Replace("change_package", sourcePackageName) .Replace("@string/app_name", appTitle) ); } // adding icons { string iconsFolder = Path.Combine(stgContainerExtracted.TempFolder, "res", "mipmap-"); void DeleteIcon(string folder) => LFile.Delete(Path.Combine($"{iconsFolder}{folder}", "ic_launcher.png")); DeleteIcon("xxhdpi-v4"); DeleteIcon("xhdpi-v4"); DeleteIcon("hdpi-v4"); DeleteIcon("mdpi-v4"); void WriteIcon(string folder, byte[] imageBytes) => LFile.WriteAllBytes(Path.Combine($"{iconsFolder}{folder}", "ic_launcher.png"), imageBytes); WriteIcon("xxhdpi-v4", xxhdpiBytes); WriteIcon("xhdpi-v4", xhdpiBytes); WriteIcon("hdpi-v4", hdpiBytes); WriteIcon("mdpi-v4", mdpiBytes); } // compiling + signing using (var compiledContainer = AndroidHelper.Logic.Utils.TempUtils.UseTempFile(tempFileProvider)) { // compiling SetStep(MainResources.StepCompiling, 4); // todo: check errors List <Error> compilationErrors; apktool.Compile( projectFolderPath: stgContainerExtracted.TempFolder, destinationApkPath: compiledContainer.TempFile, dataHandler: dataHandler, errors: out compilationErrors ); if (compilationErrors.Count > 0) { Log(MainResources.ErrorUp); return; } // signing SetStep(MainResources.StepSigning, 5); apktool.Sign( sourceApkPath: compiledContainer.TempFile, signedApkPath: resultFilePath, tempFileProvider: tempFileProvider, dataHandler: dataHandler, deleteMetaInf: !alternativeSigning ); } } visualProgress?.HideIndeterminateLabel(); visualProgress?.HideBar(); SetStep(MainResources.AllDone, 6); Log(string.Empty); Log($"{MainResources.Path_to_file} {resultFilePath}"); _globalVariables.LatestModdedApkPath = resultFilePath; if (_settings.Notifications) { _notificationManager.Show( title: MainResources.Information_Title, text: MainResources.ModificationCompletedContent ); } string dialogResult = MessBox.ShowDial( $"{MainResources.Path_to_file} {resultFilePath}", MainResources.Successful, MainResources.OK, MainResources.Open, MainResources.Install ); if (dialogResult == MainResources.Open) { Process.Start("explorer.exe", $"/select,{resultFilePath}"); } else if (dialogResult == MainResources.Install) { uiThreadDispatcher.Invoke(() => _adbInstallWindowProvider.Get().ShowDialog()); } taskBarManager?.SetNoneState(); }
public PdfCreatorCleanUp(ITempFolderProvider tempFolderProvider, ISpoolerProvider spoolFolderProvider) { _tempFolderProvider = tempFolderProvider; _spoolFolderProvider = spoolFolderProvider; _timeSpan = TimeSpan.FromDays(1); }
private void ProcessAll() { Dispatcher.Invoke(LogBox.Clear); Log( string.Format( "{0}{1}Start{1}{0}ExePath = {2}{0}Resources = {3}", Environment.NewLine, Line, _globalVariables.PathToExe, _globalVariables.PathToResources ) ); const int totalSteps = 3; _visualProgress.SetBarUsual(); _visualProgress.ShowBar(); _taskBarManager.SetProgress(0); _taskBarManager.SetUsualState(); void SetStep(int currentStep, string status) { int percentage = (currentStep - 1) * 100 / totalSteps; _visualProgress.SetBarValue(percentage); _visualProgress.SetLabelText(status); _taskBarManager.SetProgress(percentage); } #region Инициализация SetStep(1, MainResources.StepInitializing); _visualProgress.ShowIndeterminateLabel(); string sourceApkPath = ViewModel.CurrentApk.Value; bool alternativeSigning = _settings.AlternativeSigning; string popupText = ViewModel.PopupBoxText.Value; int messagesCount = ViewModel.MessagesCount.Value; bool needMessage = true; BackupType backupType = ViewModel.BackupType.Value; ITempFileProvider tempFileProvider = _tempUtils.CreateTempFileProvider(); ITempFolderProvider tempFolderProvider = _tempUtils.CreateTempFolderProvider(); string resultApkPath = sourceApkPath.Remove(sourceApkPath.Length - Path.GetExtension(sourceApkPath).Length) + "_signed.apk"; string pathToSave = ViewModel.CurrentSave.Value; IApktool apktool = _apktoolProvider.Get(); IProcessDataHandler dataHandler = new ProcessDataCombinedHandler(data => Log(data)); #endregion #region Change apk // Temp using (var tempApk = ATempUtils.UseTempFile(tempFileProvider)) { LFile.Copy(sourceApkPath, tempApk.TempFile, true); //Copy apk file to temp #region Adding data SetStep(2, MainResources.StepAddingData); var aes = new AesManaged { KeySize = 128 }; aes.GenerateIV(); aes.GenerateKey(); // adding smali file for restoring using (var decompiledFolder = ATempUtils.UseTempFolder(tempFolderProvider)) { apktool.Baksmali( apkPath: tempApk.TempFile, resultFolder: decompiledFolder.TempFolder, tempFolderProvider: tempFolderProvider, dataHandler: dataHandler ); var manifestPath = Path.Combine(decompiledFolder.TempFolder, "AndroidManifest.xml"); apktool.ExtractSimpleManifest( apkPath: tempApk.TempFile, resultManifestPath: manifestPath, tempFolderProvider: tempFolderProvider ); // have to have smali folders in the same directory as manifest // to find the main smali var manifest = new AndroidManifest(manifestPath); if (manifest.MainSmaliFile == null) { throw new Exception("main smali file not found"); } // using this instead of just pasting "folder/smali" as there can be // no smali folder sometimes (smali_1, etc) string smaliDir = manifest.MainSmaliPath.Substring(decompiledFolder.TempFolder.Length + 1); smaliDir = smaliDir.Substring(0, smaliDir.IndexOf(Path.DirectorySeparatorChar)); string saveGameDir = Path.Combine(decompiledFolder.TempFolder, smaliDir, "com", "savegame"); LDirectory.CreateDirectory(saveGameDir); //Encrypt smali CommonUtils.GenerateAndSaveSmali( filePath: Path.Combine(saveGameDir, "SavesRestoringPortable.smali"), message: needMessage ? popupText : string.Empty, messagesCount: needMessage ? messagesCount : 0 ); manifest.MainSmaliFile.AddTextToMethod(FileResources.MainSmaliCall); manifest.MainSmaliFile.Save(); using (var folderWithDexes = ATempUtils.UseTempFolder(tempFolderProvider)) { apktool.Smali( folderWithSmali: decompiledFolder.TempFolder, resultFolder: folderWithDexes.TempFolder, dataHandler: dataHandler ); string[] dexes = LDirectory.GetFiles(folderWithDexes.TempFolder, "*.dex"); ApkModifer.AddFilesToZip( zipPath: tempApk.TempFile, filePaths: dexes, pathsInZip: Array.ConvertAll(dexes, Path.GetFileName), newEntryCompression: CompressionType.Store ); } } #endregion #region Подпись SetStep(3, MainResources.StepSigning); Log(Line); Log(MainResources.StepSigning); Log(Line); LFile.Copy(tempApk.TempFile, Path.GetDirectoryName(sourceApkPath) + "\\" + Path.GetFileNameWithoutExtension(sourceApkPath) + "_unsigned.apk", true); //Copy apk file to temp //Signing //tempApk.TempFile "C:\\Users\\xxxxx\\AppData\\Local\\SaveToGame\\temp\\temp_entry_1" apktool.Sign( sourceApkPath: tempApk.TempFile, signedApkPath: resultApkPath, tempFileProvider: tempFileProvider, dataHandler: dataHandler, deleteMetaInf: !alternativeSigning ); #endregion } #endregion _visualProgress.HideIndeterminateLabel(); SetStep(4, MainResources.AllDone); Log(MainResources.AllDone); Log(string.Empty, false); Log($"{MainResources.Path_to_file} {resultApkPath}"); _globalVariables.LatestModdedApkPath = resultApkPath; if (_settings.Notifications) { _notificationManager.Show( title: MainResources.Information_Title, text: MainResources.ModificationCompletedContent ); } string dialogResult = MessBox.ShowDial( $"{MainResources.Path_to_file} {resultApkPath}", MainResources.Successful, MainResources.OK, MainResources.Open, MainResources.Install ); _visualProgress.HideBar(); _taskBarManager.SetNoneState(); //Dialog result if (dialogResult == MainResources.Open) { Process.Start("explorer.exe", $"/select,{resultApkPath}"); } else if (dialogResult == MainResources.Install) { Dispatcher.Invoke(() => _adbInstallWindowProvider.Get().ShowDialog()); } }