Beispiel #1
0
        private static void HandleCriticalFileError()
        {
            var messageService = StaticResolver.Resolve <IMessageBoxService>();

            messageService.Show(CommonRes.FileFailureErrorMessage, CommonRes.FileFailureErrorTitle, MessageBoxButton.OK);
            Environment.Exit(1);
        }
Beispiel #2
0
        private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            object selectedItem = e.NewValue;

            if (selectedItem == null || selectedItem is PresetFolderViewModel)
            {
                // If it's a folder that got "selected" we ignore it and leave the previous preset selected for real
                return;
            }

            if (PresetComboBox.PresetComboOpen)
            {
                // If inside a combo box the combo box binding on close will handle it.
                return;
            }

            DispatchUtilities.BeginInvoke(() =>
            {
                // This might be in the layout phase. Invoke on dispatcher to process cleanly.
                var newSelectedPreset = (PresetViewModel)selectedItem;
                if (this.presetsService.TryUpdateSelectedPreset(newSelectedPreset))
                {
                    StaticResolver.Resolve <Main>().ReadTextToScreenReader(newSelectedPreset.DisplayName);
                }
            });
        }
Beispiel #3
0
        /// <summary>
        /// Opens all tracked windows that are open according to config.
        /// </summary>
        /// <remarks>Call at app startup.</remarks>
        public void OpenTrackedWindows()
        {
            bool windowOpened = false;

            foreach (var definition in Definitions.Where(d => d.IsOpenConfigKey != null))
            {
                bool canOpen = true;
                if (definition.CanOpen != null)
                {
                    IDisposable disposable = definition.CanOpen().Subscribe(value =>
                    {
                        canOpen = value;
                    });

                    disposable.Dispose();
                }

                if (canOpen && Config.Get <bool>(definition.IsOpenConfigKey))
                {
                    this.OpenWindow(StaticResolver.Resolve(definition.ViewModelType), userInitiated: false);
                    windowOpened = true;
                }
            }

            if (windowOpened)
            {
                this.Focus(this.mainViewModel);
            }
        }
Beispiel #4
0
        private void ExecuteAction()
        {
            var processingService = StaticResolver.Resolve <ProcessingService>();

            processingService.EncodeCompleteAction = processingService.EncodeCompleteActions.Single(a => a.ActionType == EncodeCompleteActionType.DoNothing);

            switch (actionType)
            {
            case EncodeCompleteActionType.Sleep:
                this.systemOperations.Sleep();
                break;

            case EncodeCompleteActionType.LogOff:
                this.systemOperations.LogOff();
                break;

            case EncodeCompleteActionType.Shutdown:
                this.systemOperations.ShutDown();
                break;

            case EncodeCompleteActionType.Hibernate:
                this.systemOperations.Hibernate();
                break;
            }
        }
Beispiel #5
0
        public IList <string> GetFileNames(string initialDirectory)
        {
            var dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.Multiselect = true;

            if (!string.IsNullOrEmpty(initialDirectory))
            {
                try
                {
                    string fullDirectory = Path.GetFullPath(initialDirectory);

                    if (Directory.Exists(fullDirectory))
                    {
                        dialog.InitialDirectory = fullDirectory;
                    }
                }
                catch (NotSupportedException)
                {
                    StaticResolver.Resolve <IAppLogger>().Log("Could not recognize initial directory " + initialDirectory);
                }
            }

            bool?result = dialog.ShowDialog();

            if (result == false)
            {
                return(null);
            }

            return(new List <string>(dialog.FileNames));
        }
Beispiel #6
0
        public static FolderType GetFolderType(string directory)
        {
            try
            {
                var directoryInfo = new DirectoryInfo(directory);
                if (!directoryInfo.Exists)
                {
                    return(FolderType.NonExistent);
                }

                if (File.Exists(Path.Combine(directory, @"VIDEO_TS.IFO")) || File.Exists(Path.Combine(directory, @"VIDEO_TS\VIDEO_TS.IFO")))
                {
                    return(FolderType.Dvd);
                }

                if (Directory.Exists(Path.Combine(directory, "BDMV")))
                {
                    return(FolderType.BluRay);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                StaticResolver.Resolve <IAppLogger>().Log("Could not determine folder type: " + ex);
            }

            return(FolderType.VideoFiles);
        }
Beispiel #7
0
        private void BuildSeed(IDbContext _context)
        {
            //_context.BeginTrans();
            var admin = new User
            {
                UserName    = "******",
                Password    = "******",
                DisplayName = "管理员"
            };
            var administrators = new UserRole
            {
                RoleName = "管理员组"
            };

            _userRepo            = StaticResolver.Resolve <IRepository <User> >();
            _userRoleRepo        = StaticResolver.Resolve <IRepository <UserRole> >();
            _userUserRoleMapRepo = StaticResolver.Resolve <IRepository <User_UserRole_Map> >();
            _context.BeginTrans();
            _userRepo.Insert(admin);
            _userRoleRepo.Insert(administrators);
            _context.SaveChanges();
            var relation = new User_UserRole_Map
            {
                UserId     = admin.Id,
                UserRoleId = administrators.Id
            };

            _userUserRoleMapRepo.Insert(relation);
            //_context.SaveChanges();
        }
Beispiel #8
0
        public void PlayTitle(string discPath, int title)
        {
            string executablePath = this.PlayerExecutable;

            if (!File.Exists(executablePath))
            {
                string message = string.Format(
                    MiscRes.CouldNotFindVideoPlayerError,
                    this.Display);
                StaticResolver.Resolve <IMessageBoxService>().Show(message);
                return;
            }

            if (!discPath.EndsWith(@"\", StringComparison.Ordinal))
            {
                discPath += @"\";
            }

            try
            {
                this.PlayTitleInternal(executablePath, discPath, title);
            }
            catch (Exception exception)
            {
                string message =
                    MiscRes.ErrorPlayingSource + Environment.NewLine + Environment.NewLine + exception.Message;
                StaticResolver.Resolve <IMessageBoxService>().Show(message);
            }
        }
Beispiel #9
0
        public static void RegisterGlobalHotkeys(this Window window)
        {
            var converter = new KeyConverter();

            foreach (var definition in WindowManager.Definitions.Where(d => d.InputGestureText != null))
            {
                if (definition.InputGestureText.Contains("+"))
                {
                    string[] parts = definition.InputGestureText.Split('+');
                    if (parts.Length == 2)
                    {
                        Type windowViewModelType = definition.ViewModelType;

                        var key = (Key)converter.ConvertFrom(parts[1]);

                        ReactiveCommand <Unit, Unit> openCommand = ReactiveCommand.Create(() =>
                        {
                            windowManager.OpenOrFocusWindow(windowViewModelType);
                        });

                        window.InputBindings.Add(new InputBinding(
                                                     openCommand,
                                                     new KeyGesture(key, ModifierKeys.Control)));
                    }
                    else
                    {
                        throw new ArgumentException("InputGestureText not recognized: " + definition.InputGestureText);
                    }
                }
            }

            window.InputBindings.Add(new InputBinding(windowManager.CreateOpenCommand(typeof(OptionsDialogViewModel), openAsDialog: true), new KeyGesture(Key.G, ModifierKeys.Control)));
            window.InputBindings.Add(new InputBinding(StaticResolver.Resolve <ProcessingService>().Encode, new KeyGesture(Key.F5)));
        }
Beispiel #10
0
        private string CreateTitle(OutputSizeInfo size)
        {
            if (size.Par.Num == size.Par.Den)
            {
                return(string.Format(PreviewRes.PreviewWindowTitleSimple, size.OutputWidth, size.OutputHeight));
            }
            else
            {
                int width     = size.OutputWidth;
                int height    = size.OutputHeight;
                int parWidth  = size.Par.Num;
                int parHeight = size.Par.Den;

                if (parWidth <= 0 || parHeight <= 0)
                {
                    StaticResolver.Resolve <IAppLogger>().LogError("HandBrake returned a negative pixel aspect ratio. Cannot show preview.");
                    return(PreviewRes.NoVideoSourceTitle);
                }

                return(string.Format(
                           PreviewRes.PreviewWindowTitleComplex,
                           Math.Round(width * ((double)parWidth / parHeight)),
                           height,
                           width,
                           height));
            }
        }
Beispiel #11
0
 public static ConnectionMultiplexer GetMuxer()
 {
     if (_muxer == null || !_muxer.IsConnected)
     {
         var config = StaticResolver.Resolve <AppConfig>();
         _muxer = ConnectionMultiplexer.Connect(config.RedisCachingConnectionString);
     }
     return(_muxer);
 }
Beispiel #12
0
        public void Scan(string source)
        {
            var mainVM = StaticResolver.Resolve <MainViewModel>();

            DispatchUtilities.Invoke(() =>
            {
                mainVM.ScanFromAutoplay(source);
            });
        }
Beispiel #13
0
        public void Activate(string appUserModelId, string invokedArgs, NOTIFICATION_USER_INPUT_DATA[] data, uint dataCount)
        {
            StaticResolver.Resolve <Main>().RestoreWindow();

            DispatchUtilities.BeginInvoke(() =>
            {
                StaticResolver.Resolve <Main>().Activate();
            });
        }
Beispiel #14
0
        public void Encode(string source, string destination, string preset, string picker)
        {
            var processingService = StaticResolver.Resolve <ProcessingService>();

            DispatchUtilities.Invoke(() =>
            {
                processingService.Process(source, destination, preset, picker);
            });
        }
Beispiel #15
0
        public void OnVideoFailed()
        {
            this.PlayingPreview = false;
            MessageBoxResult result = StaticResolver.Resolve <IMessageBoxService>().Show(this, PreviewRes.VideoErrorMessage, PreviewRes.VideoErrorTitle, MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                FileService.Instance.PlayVideo(this.previewFilePath);
            }
        }
Beispiel #16
0
        private void ScanNextJob()
        {
            SourcePath path = this.pathsToScan[this.currentJobIndex];

            IScanProxy scanProxy = Utilities.CreateScanProxy();

            scanProxy.ScanProgress += (sender, args) =>
            {
                lock (this.currentJobIndexLock)
                {
                    this.currentJobProgress = args.Value;
                    this.RaisePropertyChanged(nameof(this.Progress));
                }
            };

            scanProxy.ScanCompleted += (sender, args) =>
            {
                if (args.Value != null)
                {
                    JsonScanObject scanObject = JsonConvert.DeserializeObject <JsonScanObject>(args.Value);
                    this.ScanResults.Add(new ScanResult {
                        SourcePath = path, VideoSource = scanObject.ToVideoSource()
                    });
                }
                else
                {
                    this.ScanResults.Add(new ScanResult {
                        SourcePath = path
                    });
                }

                lock (this.currentJobIndexLock)
                {
                    this.currentJobIndex++;
                    this.currentJobProgress = 0;
                    this.RaisePropertyChanged(nameof(this.Progress));

                    if (this.ScanFinished)
                    {
                        DispatchUtilities.BeginInvoke(() =>
                        {
                            this.Cancel.Execute(null);
                        });
                    }
                    else
                    {
                        this.ScanNextJob();
                    }
                }
            };

            var scanLogger = StaticResolver.Resolve <AppLoggerFactory>().ResolveRemoteScanLogger(path.Path);

            scanProxy.StartScan(path.Path, scanLogger);
        }
Beispiel #17
0
        public override bool OnClosing()
        {
            Config.OptionsDialogLastTab = this.SelectedTabIndex;

            if (this.DialogResult)
            {
                StaticResolver.Resolve <OutputPathService>().NotifyDefaultOutputFolderChanged();
            }

            return(base.OnClosing());
        }
Beispiel #18
0
        public void SetDatabaseInitializer()
        {
            var dbcontext = StaticResolver.Resolve <IDbContext>();

            if (dbcontext.db().EnsureCreated())
            {
                BuildSeed(dbcontext);
            }
            else
            {
                dbcontext.db().Migrate();
            }
        }
Beispiel #19
0
        private static void OnPreviewDrop(object sender, DragEventArgs dragEventArgs)
        {
            var data = dragEventArgs.Data as DataObject;

            if (data != null && data.ContainsFileDropList())
            {
                StringCollection itemList = data.GetFileDropList();
                var  listView             = dragEventArgs.Source as ListView;
                bool alwaysQueue          = listView?.Name == "queueView";

                StaticResolver.Resolve <MainViewModel>().HandlePaths(itemList.Cast <string>().ToList(), alwaysQueue);
            }
        }
Beispiel #20
0
 public static IDatabase GetDb()
 {
     if (_db == null || !_muxer.IsConnected)
     {
         var config = StaticResolver.Resolve <AppConfig>();
         if (_muxer == null || !_muxer.IsConnected)
         {
             _muxer = ConnectionMultiplexer.Connect(config.RedisCachingConnectionString);
         }
         _db = _muxer.GetDatabase(config.RedisCachingDataBaseId);
     }
     return(_db);
 }
Beispiel #21
0
        public static void Initialize()
        {
            mainThreadId = Thread.CurrentThread.ManagedThreadId;

            int databaseVersion = DatabaseConfig.Version;

            if (databaseVersion > Utilities.CurrentDatabaseVersion)
            {
                databaseVersion = HandleTooHighDatabaseVersion(databaseVersion);
            }

            if (databaseVersion == Utilities.CurrentDatabaseVersion)
            {
                return;
            }

            BackupDatabaseFile(databaseVersion);

            using (SQLiteTransaction transaction = Connection.BeginTransaction())
            {
                // Update DB schema
                if (databaseVersion < 35)
                {
                    string message = string.Format(CultureInfo.CurrentCulture, MainRes.DataTooOldRunVidCoderVersion, "3.15");
                    StaticResolver.Resolve <IMessageBoxService>().Show(message);
                    StaticResolver.Resolve <IMessageBoxService>().Show(message);
                    throw new InvalidOperationException("Database too old");
                }

                if (databaseVersion < 36)
                {
                    UpgradeDatabaseTo36();
                }

                // Update encoding profiles if we need to. Everything is at least 28 now from the JSON upgrade.
                int oldDatabaseVersion = Math.Max(databaseVersion, 28);
                if (oldDatabaseVersion < Utilities.LastUpdatedEncodingProfileDatabaseVersion)
                {
                    UpgradeEncodingProfiles(oldDatabaseVersion);
                }

                if (oldDatabaseVersion < Utilities.LastUpdatedPickerDatabaseVersion)
                {
                    UpgradePickers(oldDatabaseVersion);
                }

                SetDatabaseVersionToLatest();
                transaction.Commit();
            }
        }
Beispiel #22
0
        public void Execute()
        {
            var settings = StaticResolver.Resolve <DataSettings>();

            if (settings != null && settings.IsValid())
            {
                var provider = StaticResolver.Resolve <IDataProvider>();
                if (provider == null)
                {
                    throw new SusException("No IDataProvider found");
                }
                provider.SetDatabaseInitializer();
            }
        }
Beispiel #23
0
        public RedisCacheManager(AppConfig config)
        {
            if (String.IsNullOrEmpty(config.RedisCachingConnectionString))
            {
                throw new Exception("Redis connection string is empty");
            }

            //this._muxer = ConnectionMultiplexer.Connect(config.RedisCachingConnectionString);

            //this._db = _muxer.GetDatabase(config.RedisCachingDataBaseId);
            this._perRequestCacheManager = StaticResolver.Resolve <ICacheManager>();

            //var logger = NLog.LogManager.GetCurrentClassLogger();
            //logger.Debug("初始化Redis--1");
        }
Beispiel #24
0
        /// <summary>
        /// Creates a command to open a window.
        /// </summary>
        /// <param name="viewModelType">The type of window viewmodel to open.</param>
        /// <param name="openAsDialog">True to open as a dialog, false to open as a window.</param>
        /// <returns>The command.</returns>
        public ICommand CreateOpenCommand(Type viewModelType, bool openAsDialog = false)
        {
            var command = ReactiveCommand.Create(() =>
            {
                if (openAsDialog)
                {
                    this.OpenDialog(StaticResolver.Resolve(viewModelType));
                }
                else
                {
                    this.OpenOrFocusWindow(viewModelType);
                }
            });

            return(command);
        }
Beispiel #25
0
        private static void OnPreviewDragOver(object sender, DragEventArgs dragEventArgs)
        {
            if (StaticResolver.Resolve <MainViewModel>().VideoSourceState == VideoSourceState.Scanning)
            {
                var data = dragEventArgs.Data as DataObject;
                if (data != null)
                {
                    dragEventArgs.Effects = DragDropEffects.None;
                    dragEventArgs.Handled = true;
                }

                return;
            }

            Utilities.SetDragIcon(dragEventArgs);
        }
Beispiel #26
0
        public void CreateSubFolder(PresetFolderViewModel folderViewModel)
        {
            var dialogVM = new ChooseNameViewModel(EncodingRes.ChooseNameSubfolder, new List <string>());

            dialogVM.Name = EncodingRes.DefaultPresetFolderName;
            var windowManager = StaticResolver.Resolve <IWindowManager>();

            windowManager.OpenDialog(dialogVM, windowManager.Find <EncodingWindowViewModel>());

            if (dialogVM.DialogResult)
            {
                string subfolderName = dialogVM.Name;

                PresetFolder newFolder = PresetFolderStorage.AddFolder(subfolderName, folderViewModel.Id);
                folderViewModel.AddSubfolder(PresetFolderViewModel.FromPresetFolder(newFolder, this));
            }
        }
Beispiel #27
0
        private static void BackupDatabaseFile(int databaseVersion)
        {
            Connection.Close();
            connection = null;

            try
            {
                string backupFilePath = GetBackupDatabaseFilePath(databaseVersion);
                Directory.CreateDirectory(BackupDatabaseFolder);

                File.Copy(DatabaseFile, backupFilePath, overwrite: true);
            }
            catch (Exception exception)
            {
                StaticResolver.Resolve <IAppLogger>().Log("Could not backup database file:" + Environment.NewLine + exception);
            }
        }
Beispiel #28
0
        public bool PromptToApplyUpdate(bool relaunchWhenComplete)
        {
            if (Utilities.SupportsUpdates)
            {
                // If updates are enabled, and we are the last process instance, prompt to apply the update.
                if (Config.UpdatesEnabled && Utilities.CurrentProcessInstances == 1)
                {
                    // See if the user has already applied the update manually
                    Version updateVersion;
                    if (Version.TryParse(Config.UpdateVersion, out updateVersion) && updateVersion.FillInWithZeroes() <= Utilities.CurrentVersion)
                    {
                        // If we already have the newer version clear all the update info and cancel
                        ClearUpdateMetadata();
                        DeleteUpdatesFolder();
                        return(false);
                    }

                    string installerPath = Config.UpdateInstallerLocation;

                    if (installerPath != string.Empty && File.Exists(installerPath))
                    {
                        // An update is ready, to give a prompt to apply it.
                        var updateConfirmation = new ApplyUpdateConfirmation();
                        updateConfirmation.Owner = StaticResolver.Resolve <View.Main>();
                        updateConfirmation.ShowDialog();

                        if (updateConfirmation.Result == "Yes")
                        {
                            this.ApplyUpdate(relaunchWhenComplete);
                            return(true);
                        }
                        else if (updateConfirmation.Result == "Disable")
                        {
                            Config.UpdatesEnabled = false;
                        }
                    }
                    else
                    {
                        this.updateDownloadCancellationTokenSource?.Cancel();
                    }
                }
            }

            return(false);
        }
Beispiel #29
0
        public void Scan(string source)
        {
            var mainVM = StaticResolver.Resolve <MainViewModel>();

            DispatchUtilities.Invoke(() =>
            {
                try
                {
                    mainVM.ScanFromAutoplay(source);
                }
                catch (Exception exception)
                {
                    throw new FaultException <AutomationError>(new AutomationError {
                        Message = exception.Message
                    });
                }
            });
        }
Beispiel #30
0
        public void Encode(string source, string destination, string preset, string picker)
        {
            var processingService = StaticResolver.Resolve <ProcessingService>();

            DispatchUtilities.Invoke(() =>
            {
                try
                {
                    processingService.Process(source, destination, preset, picker);
                }
                catch (Exception exception)
                {
                    throw new FaultException <AutomationError>(new AutomationError {
                        Message = exception.Message
                    });
                }
            });
        }