Exemplo n.º 1
0
        public void SetUpFixture()
        {
            FServerConfigurationManager = new SQLCEServerConfigurationManager();
            FConfiguration = FServerConfigurationManager.GetTestConfiguration("TestInstance");
            FServerConfigurationManager.ResetInstance();
            FServer = FServerConfigurationManager.GetServer();
            FServer.Start();

            IServerSession LSession = FServer.Connect(new SessionInfo("Admin", ""));

            try
            {
                IServerProcess LProcess = LSession.StartProcess(new ProcessInfo(LSession.SessionInfo));
                try
                {
                    LProcess.ExecuteScript("EnsureLibraryRegistered('Frontend');");
                    LProcess.ExecuteScript("EnsureLibraryRegistered('TestFramework.Coverage.Base');");
                }
                finally
                {
                    LSession.StopProcess(LProcess);
                }
            }
            finally
            {
                FServer.Disconnect(LSession);
            }
        }
Exemplo n.º 2
0
        public object Get(GetBrandingCss request)
        {
            var result = ServerConfigurationManager.GetConfiguration <BrandingOptions>("branding");

            // When null this throws a 405 error under Mono OSX, so default to empty string
            return(ResultFactory.GetResult(Request, result.CustomCss ?? string.Empty, "text/css"));
        }
Exemplo n.º 3
0
        //public PackageCache ApplicationPackageCache {get;}


        public PhotonServer()
        {
            Http = new HttpServer(this);
            Projects = new ProjectManager();
            Sessions = new ServerSessionManager();
            MessageRegistry = new MessageProcessorRegistry();
            Variables = new VariableSetDocumentManager();
            HealthChecks = new HealthCheckService();
            UserMgr = new UserGroupManager();
            ProjectPackageCache = new ProjectPackageCache();
            ServerConfiguration = new ServerConfigurationManager();
            Agents = new ServerAgentManager();

            ProjectPackages = new ProjectPackageManager {
                PackageDirectory = Configuration.ProjectPackageDirectory,
            };

            ApplicationPackages = new ApplicationPackageManager {
                PackageDirectory = Configuration.ApplicationPackageDirectory,
            };

            Queue = new ScriptQueue {
                MaxDegreeOfParallelism = Configuration.Parallelism,
            };

            ProjectPackages.PackageAdded += ProjectPackages_OnPackageAdded;
        }
Exemplo n.º 4
0
        private void CatalogRegressionTest(ServerConfigurationManager AServerConfigurationManager)
        {
            // Create a test configuration
            ServerConfiguration LTestConfiguration = AServerConfigurationManager.GetTestConfiguration("TestInstance");

            // Reset the instance
            AServerConfigurationManager.ResetInstance();

            // Start a server based on the StoreRegression instance
            Server LServer = AServerConfigurationManager.GetServer();

            LServer.Start();

            // Stop the server
            LServer.Stop();

            // Start the server
            LServer.Start();

            // Stop the server
            LServer.Stop();

            // Reset the instance
            AServerConfigurationManager.ResetInstance();
        }
Exemplo n.º 5
0
        public ApplicationHost(
            IServerApplicationPaths applicationPaths,
            ILoggerFactory loggerFactory,
            IStartupOptions options,
            IConfiguration startupConfig,
            IFileSystem fileSystem,
            IServiceCollection serviceCollection)
        {
            ApplicationPaths   = applicationPaths;
            LoggerFactory      = loggerFactory;
            _startupOptions    = options;
            _startupConfig     = startupConfig;
            _fileSystemManager = fileSystem;
            ServiceCollection  = serviceCollection;

            Logger = LoggerFactory.CreateLogger <ApplicationHost>();
            fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));

            ApplicationVersion       = typeof(ApplicationHost).Assembly.GetName().Version;
            ApplicationVersionString = ApplicationVersion.ToString(3);
            ApplicationUserAgent     = Name.Replace(' ', '-') + "/" + ApplicationVersionString;

            _xmlSerializer       = new MyXmlSerializer();
            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
            _pluginManager       = new PluginManager(
                LoggerFactory.CreateLogger <PluginManager>(),
                this,
                ConfigurationManager.Configuration,
                ApplicationPaths.PluginsPath,
                ApplicationVersion);
        }
Exemplo n.º 6
0
        private void MigrateModularConfigurations()
        {
            var saveConfig = false;

            if (ServerConfigurationManager.Configuration.DlnaOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("dlna", ServerConfigurationManager.Configuration.DlnaOptions);
                ServerConfigurationManager.Configuration.DlnaOptions = null;
                saveConfig = true;
            }

            if (ServerConfigurationManager.Configuration.ChapterOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("chapters", ServerConfigurationManager.Configuration.ChapterOptions);
                ServerConfigurationManager.Configuration.ChapterOptions = null;
                saveConfig = true;
            }

            if (ServerConfigurationManager.Configuration.ChannelOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("channels", ServerConfigurationManager.Configuration.ChannelOptions);
                ServerConfigurationManager.Configuration.ChannelOptions = null;
                saveConfig = true;
            }

            if (ServerConfigurationManager.Configuration.NotificationOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("notifications", ServerConfigurationManager.Configuration.NotificationOptions);
                ServerConfigurationManager.Configuration.NotificationOptions = null;
                saveConfig = true;
            }

            if (ServerConfigurationManager.Configuration.LiveTvOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("livetv", ServerConfigurationManager.Configuration.LiveTvOptions);
                ServerConfigurationManager.Configuration.LiveTvOptions = null;
                saveConfig = true;
            }

            if (ServerConfigurationManager.Configuration.TvFileOrganizationOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("autoorganize", new AutoOrganizeOptions {
                    TvOptions = ServerConfigurationManager.Configuration.TvFileOrganizationOptions
                });
                ServerConfigurationManager.Configuration.TvFileOrganizationOptions = null;
                saveConfig = true;
            }

            if (ServerConfigurationManager.Configuration.SubtitleOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("subtitles", ServerConfigurationManager.Configuration.SubtitleOptions);
                ServerConfigurationManager.Configuration.SubtitleOptions = null;
                saveConfig = true;
            }

            if (saveConfig)
            {
                ServerConfigurationManager.SaveConfiguration();
            }
        }
Exemplo n.º 7
0
        private void SetEnvironment()
        {
            IConfigurationRoot root = Configuration as IConfigurationRoot;

            if (root == null)
            {
                return;
            }

            MemoryConfigurationProvider provider = root.Providers.OfType <MemoryConfigurationProvider>().FirstOrDefault();

            if (provider == null)
            {
                return;
            }

            string environment;

            if (!provider.TryGet(nameof(MessageBrokerEnvironment), out environment))
            {
                throw new Exception("Environment not specified");
            }

            environment = environment ?? "Test";
            MessageBrokerEnvironment   = environment.Parse <MessageBrokerEnvironment>(ignoreCase: true);
            MessageBrokerConfiguration = new ServerConfigurationManager().GetConfiguration(MessageBrokerEnvironment);
        }
Exemplo n.º 8
0
        public Task <object> Get(GetHlsPlaylistLegacy request)
        {
            var file = request.PlaylistId + Path.GetExtension(Request.PathInfo);

            file = Path.Combine(ServerConfigurationManager.GetTranscodePath(), file);

            return(GetFileResult(file, file));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public Task <object> Get(GetHlsAudioSegmentLegacy request)
        {
            // TODO: Deprecate with new iOS app
            var file = request.SegmentId + Path.GetExtension(Request.PathInfo);

            file = Path.Combine(ServerConfigurationManager.GetTranscodePath(), file);

            return(ResultFactory.GetStaticFileResult(Request, file, FileShareMode.ReadWrite));
        }
Exemplo n.º 10
0
        private void MigrateModularConfigurations()
        {
            var saveConfig = false;

            if (saveConfig)
            {
                ServerConfigurationManager.SaveConfiguration();
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Gets the output file path.
        /// </summary>
        private string GetOutputFilePath(StreamState state, EncodingOptions encodingOptions, string outputFileExtension)
        {
            var data = $"{state.MediaPath}-{state.UserAgent}-{state.Request.DeviceId}-{state.Request.PlaySessionId}";

            var filename = data.GetMD5().ToString("N", CultureInfo.InvariantCulture);
            var ext      = outputFileExtension?.ToLowerInvariant();
            var folder   = ServerConfigurationManager.GetTranscodePath();

            return(EnableOutputInSubFolder
                ? Path.Combine(folder, filename, filename + ext)
                : Path.Combine(folder, filename + ext));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Called when [configuration updated].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected override void OnConfigurationUpdated(object sender, EventArgs e)
        {
            base.OnConfigurationUpdated(sender, e);

            if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
            {
                ServerConfigurationManager.Configuration.IsPortAuthorized = false;
                ServerConfigurationManager.SaveConfiguration();

                NotifyPendingRestart();
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// This method refers to ServerConfigurationManager class --> IsEmpty() method
 /// in 'io.asgardio.dotnet.oidc.sdk' library and check whether each and every <app_settings> is
 /// completed in 'app.config' file. If <app_settings> data is empty it'll load the 'ConfigurationPage',
 /// else load the 'LoginPage'.
 /// </summary>
 public App()
 {
     if (ServerConfigurationManager.IsEmpty() == true)
     {
         ConfigurationPage configuration = new ConfigurationPage();
         configuration.Show();
     }
     else
     {
         LoginPage login = new LoginPage();
         login.Show();
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public Task <object> Get(GetHlsVideoSegmentLegacy request)
        {
            var file = request.SegmentId + Path.GetExtension(Request.PathInfo);
            var transcodeFolderPath = ServerConfigurationManager.GetTranscodePath();

            file = Path.Combine(transcodeFolderPath, file);

            var normalizedPlaylistId = request.PlaylistId;

            var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath)
                               .FirstOrDefault(i => string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1);

            return(GetFileResult(file, playlistPath));
        }
Exemplo n.º 15
0
        private bool startServer()
        {
            commandHandler = new ConsoleCommandHandler(this);
            var threadcommandreader = new ThreadCommandReader(this);

            threadcommandreader.setDaemon(true);
            threadcommandreader.start();
            ConsoleLogManager.init();
            logger.info("Starting Crafty version " + Crafty.VERSION + "(based on minecraft server version Beta 1.3)");

            logger.info("Loading properties");
            propertyManagerObj = new PropertyManager(new File("server.properties"));
            string s = propertyManagerObj.getStringProperty("server-ip", "");

            onlineMode        = propertyManagerObj.getBooleanProperty("online-mode", true);
            spawnPeacefulMobs = propertyManagerObj.getBooleanProperty("spawn-animals", true);
            pvpOn             = propertyManagerObj.getBooleanProperty("pvp", true);
            InetAddress inetaddress = null;

            if (s.Length > 0)
            {
                inetaddress = InetAddress.getByName(s);
            }
            int i = propertyManagerObj.getIntProperty("server-port", 25565);

            logger.info(
                (new StringBuilder()).append("Starting Minecraft server on ").append(s.Length != 0 ? s : "*").append(":")
                .append(i).toString());
            networkServer = new NetworkListenThread(this, inetaddress, i);
            if (!onlineMode)
            {
                logger.warning("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!");
                logger.warning("The server will make no attempt to authenticate usernames. Beware.");
                logger.warning(
                    "While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.");
                logger.warning("To change this, set \"online-mode\" to \"true\" in the server.settings file.");
            }
            configManager = new ServerConfigurationManager(this);
            entityTracker = new EntityTracker(this);
            long   l  = java.lang.System.nanoTime();
            string s1 = propertyManagerObj.getStringProperty("level-name", "world");

            logger.info((new StringBuilder()).append("Preparing level \"").append(s1).append("\"").toString());
            initWorld(new SaveConverterMcRegion(new File(".")), s1);
            logger.info(
                (new StringBuilder()).append("Done (").append(java.lang.System.nanoTime() - l).append(
                    "ns)! For help, type \"help\" or \"?\"").toString());
            return(true);
        }
Exemplo n.º 16
0
        public void FixtureSetup()
        {
            InstanceManager.Load();

            FConfigurationManager = new SQLCEServerConfigurationManager();
            FConfiguration        = FConfigurationManager.GetTestConfiguration("TestOOPInstance");

            if (InstanceManager.Instances.HasInstance("TestOOPInstance"))
            {
                InstanceManager.Instances.Remove("TestOOPInstance");
            }

            InstanceManager.Instances.Add("TestOOPInstance", FConfiguration);
            InstanceManager.Save();

            ProcessStartInfo LProcessStartInfo = new ProcessStartInfo();

            LProcessStartInfo.FileName              = Path.Combine(ServerConfigurationManager.GetInstallationDirectory(), "Dataphor\\bin\\DAEServer.exe");
            LProcessStartInfo.WorkingDirectory      = Path.GetDirectoryName(LProcessStartInfo.FileName);
            LProcessStartInfo.Arguments             = "-n \"TestOOPInstance\"";
            LProcessStartInfo.UseShellExecute       = false;
            LProcessStartInfo.RedirectStandardInput = true;
            FProcess = Process.Start(LProcessStartInfo);

            // TODO: This should be a wait for the process, but WaitForInputIdle only works on GUI apps
            //Thread.Sleep(10000);

            ConnectionAlias LAlias = new ConnectionAlias();

            LAlias.Name         = "TestOOPInstanceConnection";
            LAlias.InstanceName = "TestOOPInstance";

            int LRetryCount = 0;

            while ((FDataSession == null) && (LRetryCount++ < 3))
            {
                Thread.Sleep(500);
                try
                {
                    FDataSession       = new DataSession();
                    FDataSession.Alias = LAlias;
                    FDataSession.Open();
                }
                catch
                {
                    FDataSession = null;
                }
            }
        }
Exemplo n.º 17
0
        private bool EnableThrottling(StreamState state)
        {
            var encodingOptions = ServerConfigurationManager.GetEncodingOptions();

            // enable throttling when NOT using hardware acceleration
            if (encodingOptions.HardwareAccelerationType == string.Empty)
            {
                return(state.InputProtocol == MediaProtocol.File &&
                       state.RunTimeTicks.HasValue &&
                       state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks&&
                       state.IsInputVideo &&
                       state.VideoType == VideoType.VideoFile &&
                       !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase));
            }
            return(false);
        }
Exemplo n.º 18
0
        private bool EnableThrottling(StreamState state)
        {
            var encodingOptions = ServerConfigurationManager.GetEncodingOptions();

            // enable throttling when NOT using hardware acceleration
            if (string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
            {
                return(state.InputProtocol == MediaProtocol.File &&
                       state.RunTimeTicks.HasValue &&
                       state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks&&
                       state.IsInputVideo &&
                       state.VideoType == VideoType.VideoFile &&
                       !EncodingHelper.IsCopyCodec(state.OutputVideoCodec));
            }

            return(false);
        }
Exemplo n.º 19
0
        private void MigrateModularConfigurations()
        {
            var saveConfig = false;

            if (ServerConfigurationManager.Configuration.TvFileOrganizationOptions != null)
            {
                ServerConfigurationManager.SaveConfiguration("autoorganize", new AutoOrganizeOptions {
                    TvOptions = ServerConfigurationManager.Configuration.TvFileOrganizationOptions
                });
                ServerConfigurationManager.Configuration.TvFileOrganizationOptions = null;
                saveConfig = true;
            }

            if (saveConfig)
            {
                ServerConfigurationManager.SaveConfiguration();
            }
        }
Exemplo n.º 20
0
        protected override void OnStart(string[] args)
        {
            logger     = LogManager.GetCurrentClassLogger();
            components = new System.ComponentModel.Container();

            logger.Trace("Starting..." + DateTime.Now.ToString());
            sitClientManager           = new SitClientManager();
            serverConfigurationManager = new ServerConfigurationManager();

            logger.Trace("Checking entities in DB");
            sitClientManager.checkClientsEntities();
            sitClientManager.checkClientsHistoryEntities();
            serverConfigurationManager.checkConfigurationsEntities();

            logger.Trace("Resetting Ping Pending statuses");
            sitClientManager.UpdateResetPingPending();

            logger.Trace("Scheduling sitClientWatchDog execution");
            System.Threading.Thread myThread = new System.Threading.Thread(new System.Threading.ThreadStart(sitClientManager.sitClientWatchDog));
            myThread.Start();
        }
Exemplo n.º 21
0
        public void Post(UpdateItemContentType request)
        {
            var item = _libraryManager.GetItemById(request.ItemId);
            var path = item.ContainingFolderPath;

            var types = ServerConfigurationManager.Configuration.ContentTypes
                        .Where(i => !string.IsNullOrWhiteSpace(i.Name))
                        .Where(i => !string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase))
                        .ToList();

            if (!string.IsNullOrWhiteSpace(request.ContentType))
            {
                types.Add(new NameValuePair
                {
                    Name  = path,
                    Value = request.ContentType
                });
            }

            ServerConfigurationManager.Configuration.ContentTypes = types.ToArray();
            ServerConfigurationManager.SaveConfiguration();
        }
Exemplo n.º 22
0
        public PhotonServer()
        {
            Projects        = new ProjectManager();
            Sessions        = new ServerSessionManager();
            MessageRegistry = new MessageProcessorRegistry();
            Variables       = new VariableSetDocumentManager();

            ProjectPackages = new ProjectPackageManager {
                PackageDirectory = Configuration.ProjectPackageDirectory,
            };

            ApplicationPackages = new ApplicationPackageManager {
                PackageDirectory = Configuration.ApplicationPackageDirectory,
            };

            Queue = new ScriptQueue {
                MaxDegreeOfParallelism = Configuration.Parallelism,
            };

            ServerConfiguration = new ServerConfigurationManager();
            Agents = new ServerAgentManager();
        }
        /// <summary>
        /// Button click event for 'Update' button. This method refers to
        /// ServerConfigurationManager class --> UpdateAppSettings() method in 'org.wso2.identity.sdk.oidc' library
        /// and save user given data to 'app.config' file.
        /// </summary>
        private void UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            ServerConfigurationManager.UpdateAppSettings(Constants.ClientId, this.idTxt.Text);
            ServerConfigurationManager.UpdateAppSettings(Constants.ClientSecret, this.clientSecretTxt.Password);
            ServerConfigurationManager.UpdateAppSettings(Constants.AuthorizationEndpoint, this.authenticationTxt.Text);
            ServerConfigurationManager.UpdateAppSettings(Constants.TokenEndpoint, this.tokenTxt.Text);
            ServerConfigurationManager.UpdateAppSettings(Constants.UserInfoEndpoint, this.userinfoTxt.Text);
            ServerConfigurationManager.UpdateAppSettings(Constants.LogoutEndpoint, this.logoutTxt.Text);
            ServerConfigurationManager.UpdateAppSettings(Constants.RedirectURI, this.callbackTxt.Text);
            ServerConfigurationManager.UpdateAppSettings(Constants.PostLogoutRedirectURI, this.postLogoutTxt.Text);

            if (SSLcheckbox.IsChecked == true)
            {
                MessageBox.Show("Successfully Updated !", "Information");
                this.Close();
            }
            else
            {
                MessageBox.Show("Please enable ssl veification checkbox to establish trust relationship for the " +
                                "SSL/TLS secure channel.", "Information");
                this.Show();
            }
        }
Exemplo n.º 24
0
 public object Get(GetBrandingOptions request)
 {
     return(ServerConfigurationManager.GetConfiguration <BrandingOptions>("branding"));
 }
Exemplo n.º 25
0
        /// <summary>
        /// Registers resources that classes will depend on
        /// </summary>
        /// <returns>Task.</returns>
        protected override async Task RegisterResources(IProgress <double> progress)
        {
            await base.RegisterResources(progress).ConfigureAwait(false);

            RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));

            RegisterSingleInstance <IServerApplicationHost>(this);
            RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths);

            RegisterSingleInstance(ServerConfigurationManager);

            LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer);
            RegisterSingleInstance(LocalizationManager);

            RegisterSingleInstance <IBlurayExaminer>(() => new BdInfoExaminer());

            UserDataManager = new UserDataManager(LogManager, ServerConfigurationManager);
            RegisterSingleInstance(UserDataManager);

            UserRepository = await GetUserRepository().ConfigureAwait(false);

            RegisterSingleInstance(UserRepository);

            DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
            RegisterSingleInstance(DisplayPreferencesRepository);

            ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
            RegisterSingleInstance(ItemRepository);

            ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
            RegisterSingleInstance(ProviderRepository);

            FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);

            RegisterSingleInstance(FileOrganizationRepository);

            AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);

            RegisterSingleInstance(AuthenticationRepository);

            SyncRepository = await GetSyncRepository().ConfigureAwait(false);

            RegisterSingleInstance(SyncRepository);

            UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager, this, JsonSerializer);
            RegisterSingleInstance(UserManager);

            LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
            RegisterSingleInstance(LibraryManager);

            var musicManager = new MusicManager(LibraryManager);

            RegisterSingleInstance <IMusicManager>(new MusicManager(LibraryManager));

            LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
            RegisterSingleInstance(LibraryMonitor);

            ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
            RegisterSingleInstance(ProviderManager);

            SeriesOrderManager = new SeriesOrderManager();
            RegisterSingleInstance(SeriesOrderManager);

            RegisterSingleInstance <ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));

            if (IsFirstRun)
            {
                ServerConfigurationManager.Configuration.EnableWin8HttpListener = false;
                ServerConfigurationManager.SaveConfiguration();
                _supportsNativeWebSocket = false;
            }

            if (!ServerConfigurationManager.Configuration.EnableWin8HttpListener)
            {
                _supportsNativeWebSocket = false;
            }

            HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html", _supportsNativeWebSocket);
            RegisterSingleInstance(HttpServer, false);
            progress.Report(10);

            ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
            RegisterSingleInstance(ServerManager);

            var innerProgress = new ActionableProgress <double>();

            innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));

            ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
            RegisterSingleInstance(ImageProcessor);

            TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager);
            RegisterSingleInstance(TVSeriesManager);

            SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"), UserManager, () => DtoService, this, TVSeriesManager, () => MediaEncoder);
            RegisterSingleInstance(SyncManager);

            DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager, this);
            RegisterSingleInstance(DtoService);

            var encryptionManager = new EncryptionManager();

            RegisterSingleInstance <IEncryptionManager>(encryptionManager);

            ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager);
            RegisterSingleInstance(ConnectManager);

            DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer, Logger), UserManager, FileSystemManager, LibraryMonitor, ConfigurationManager, LogManager.GetLogger("DeviceManager"));
            RegisterSingleInstance(DeviceManager);

            SessionManager = new SessionManager(UserDataManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager);
            RegisterSingleInstance(SessionManager);

            var newsService = new Implementations.News.NewsService(ApplicationPaths, JsonSerializer);

            RegisterSingleInstance <INewsService>(newsService);

            var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);

            RegisterSingleInstance <IFileOrganizationService>(fileOrganizationService);

            progress.Report(15);

            ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient);
            RegisterSingleInstance(ChannelManager);

            var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);

            RegisterSingleInstance <IAppThemeManager>(appThemeManager);

            var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);

            RegisterSingleInstance <IDlnaManager>(dlnaManager);

            var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);

            RegisterSingleInstance <IConnectionManager>(connectionManager);

            CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
            RegisterSingleInstance(CollectionManager);

            var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);

            RegisterSingleInstance <IPlaylistManager>(playlistManager);

            LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
            RegisterSingleInstance(LiveTvManager);

            UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
            RegisterSingleInstance(UserViewManager);

            var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager, ChannelManager);

            RegisterSingleInstance <IContentDirectory>(contentDirectory);

            NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
            RegisterSingleInstance(NotificationManager);

            SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
            RegisterSingleInstance(SubtitleManager);

            ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
            RegisterSingleInstance(ChapterManager);

            await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);

            progress.Report(90);

            EncodingManager = new EncodingManager(FileSystemManager, Logger,
                                                  MediaEncoder, ChapterManager);
            RegisterSingleInstance(EncodingManager);

            var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);

            RegisterSingleInstance(activityLogRepo);
            RegisterSingleInstance <IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));

            var authContext = new AuthorizationContext(AuthenticationRepository);

            RegisterSingleInstance <IAuthorizationContext>(authContext);
            RegisterSingleInstance <ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
            RegisterSingleInstance <IAuthService>(new AuthService(UserManager, authContext, ServerConfigurationManager, ConnectManager, SessionManager, DeviceManager));

            SubtitleEncoder = new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer);
            RegisterSingleInstance(SubtitleEncoder);

            await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false);
            await ConfigureItemRepositories().ConfigureAwait(false);
            await ConfigureUserDataRepositories().ConfigureAwait(false);
            await ConfigureNotificationsRepository().ConfigureAwait(false);

            progress.Report(100);

            SetStaticProperties();

            await((UserManager)UserManager).Initialize().ConfigureAwait(false);

            SetKernelProperties();
        }
Exemplo n.º 26
0
        /// <summary>
        /// Starts the FFMPEG.
        /// </summary>
        /// <param name="state">The state.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="cancellationTokenSource">The cancellation token source.</param>
        /// <param name="workingDirectory">The working directory.</param>
        /// <returns>Task.</returns>
        protected async Task <TranscodingJob> StartFfMpeg(
            StreamState state,
            string outputPath,
            CancellationTokenSource cancellationTokenSource,
            string workingDirectory = null)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);

            if (state.VideoRequest != null && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                var auth = AuthorizationContext.GetAuthorizationInfo(Request);
                if (auth.User != null && !auth.User.Policy.EnableVideoPlaybackTranscoding)
                {
                    ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);

                    throw new ArgumentException("User does not have access to video transcoding");
                }
            }

            var encodingOptions = ServerConfigurationManager.GetEncodingOptions();

            var process = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    CreateNoWindow  = true,
                    UseShellExecute = false,

                    // Must consume both stdout and stderr or deadlocks may occur
                    //RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,

                    FileName         = MediaEncoder.EncoderPath,
                    Arguments        = GetCommandLineArguments(outputPath, encodingOptions, state, true),
                    WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? null : workingDirectory,

                    ErrorDialog = false
                },
                EnableRaisingEvents = true
            };

            var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
                                                                             state.Request.PlaySessionId,
                                                                             state.MediaSource.LiveStreamId,
                                                                             Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                                                                             TranscodingJobType,
                                                                             process,
                                                                             state.Request.DeviceId,
                                                                             state,
                                                                             cancellationTokenSource);

            var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;

            Logger.LogInformation(commandLineLogMessage);

            var logFilePrefix = "ffmpeg-transcode";

            if (state.VideoRequest != null &&
                string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
            {
                if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
                {
                    logFilePrefix = "ffmpeg-directstream";
                }
                else
                {
                    logFilePrefix = "ffmpeg-remux";
                }
            }

            var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");

            // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
            Stream logStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);

            var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
            await logStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);

            process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);

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

                ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);

                throw;
            }

            Logger.LogDebug("Launched ffmpeg process");
            state.TranscodingJob = transcodingJob;

            // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
            _ = new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, logStream);

            // Wait for the file to exist before proceeeding
            var ffmpegTargetFile = state.WaitForPath ?? outputPath;

            Logger.LogDebug("Waiting for the creation of {0}", ffmpegTargetFile);
            while (!File.Exists(ffmpegTargetFile) && !transcodingJob.HasExited)
            {
                await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
            }

            Logger.LogDebug("File {0} created or transcoding has finished", ffmpegTargetFile);

            if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
            {
                await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);

                if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
                {
                    await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
                }
            }

            if (!transcodingJob.HasExited)
            {
                StartThrottler(state, transcodingJob);
            }
            Logger.LogDebug("StartFfMpeg() finished successfully");

            return(transcodingJob);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Gets the state.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>StreamState.</returns>
        protected async Task <StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
        {
            ParseDlnaHeaders(request);

            if (!string.IsNullOrWhiteSpace(request.Params))
            {
                ParseParams(request);
            }

            ParseStreamOptions(request);

            var url = Request.PathInfo;

            if (string.IsNullOrEmpty(request.AudioCodec))
            {
                request.AudioCodec = EncodingHelper.InferAudioCodec(url);
            }

            var enableDlnaHeaders = !string.IsNullOrWhiteSpace(request.Params) ||
                                    string.Equals(GetHeader("GetContentFeatures.DLNA.ORG"), "1", StringComparison.OrdinalIgnoreCase);

            var state = new StreamState(MediaSourceManager, TranscodingJobType)
            {
                Request           = request,
                RequestedUrl      = url,
                UserAgent         = Request.UserAgent,
                EnableDlnaHeaders = enableDlnaHeaders
            };

            var auth = AuthorizationContext.GetAuthorizationInfo(Request);

            if (!auth.UserId.Equals(Guid.Empty))
            {
                state.User = UserManager.GetUserById(auth.UserId);
            }

            //if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
            //    (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
            //    (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
            //{
            //    state.SegmentLength = 6;
            //}

            if (state.VideoRequest != null && !string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
            {
                state.SupportedVideoCodecs    = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
                state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
            }

            if (!string.IsNullOrWhiteSpace(request.AudioCodec))
            {
                state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
                state.Request.AudioCodec   = state.SupportedAudioCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToAudioCodec(i))
                                             ?? state.SupportedAudioCodecs.FirstOrDefault();
            }

            if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
            {
                state.SupportedSubtitleCodecs = request.SubtitleCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
                state.Request.SubtitleCodec   = state.SupportedSubtitleCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToSubtitleCodec(i))
                                                ?? state.SupportedSubtitleCodecs.FirstOrDefault();
            }

            var item = LibraryManager.GetItemById(request.Id);

            state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);

            //var primaryImage = item.GetImageInfo(ImageType.Primary, 0) ??
            //             item.Parents.Select(i => i.GetImageInfo(ImageType.Primary, 0)).FirstOrDefault(i => i != null);
            //if (primaryImage != null)
            //{
            //    state.AlbumCoverPath = primaryImage.Path;
            //}

            MediaSourceInfo mediaSource = null;

            if (string.IsNullOrWhiteSpace(request.LiveStreamId))
            {
                var currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
                                 ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
                    : null;

                if (currentJob != null)
                {
                    mediaSource = currentJob.MediaSource;
                }

                if (mediaSource == null)
                {
                    var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(LibraryManager.GetItemById(request.Id), null, false, false, cancellationToken).ConfigureAwait(false)).ToList();

                    mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
                       ? mediaSources[0]
                       : mediaSources.Find(i => string.Equals(i.Id, request.MediaSourceId));

                    if (mediaSource == null && request.MediaSourceId.Equals(request.Id))
                    {
                        mediaSource = mediaSources[0];
                    }
                }
            }
            else
            {
                var liveStreamInfo = await MediaSourceManager.GetLiveStreamWithDirectStreamProvider(request.LiveStreamId, cancellationToken).ConfigureAwait(false);

                mediaSource = liveStreamInfo.Item1;
                state.DirectStreamProvider = liveStreamInfo.Item2;
            }

            var videoRequest = request as VideoStreamRequest;

            EncodingHelper.AttachMediaSourceInfo(state, mediaSource, url);

            var container = Path.GetExtension(state.RequestedUrl);

            if (string.IsNullOrEmpty(container))
            {
                container = request.Container;
            }

            if (string.IsNullOrEmpty(container))
            {
                container = request.Static ?
                            StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(state.InputContainer, state.MediaPath, null, DlnaProfileType.Audio) :
                            GetOutputFileExtension(state);
            }

            state.OutputContainer = (container ?? string.Empty).TrimStart('.');

            state.OutputAudioBitrate = EncodingHelper.GetAudioBitrateParam(state.Request, state.AudioStream);

            state.OutputAudioCodec = state.Request.AudioCodec;

            state.OutputAudioChannels = EncodingHelper.GetNumAudioChannelsParam(state, state.AudioStream, state.OutputAudioCodec);

            if (videoRequest != null)
            {
                state.OutputVideoCodec   = state.VideoRequest.VideoCodec;
                state.OutputVideoBitrate = EncodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);

                if (videoRequest != null)
                {
                    EncodingHelper.TryStreamCopy(state);
                }

                if (state.OutputVideoBitrate.HasValue && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
                {
                    var resolution = ResolutionNormalizer.Normalize(
                        state.VideoStream?.BitRate,
                        state.VideoStream?.Width,
                        state.VideoStream?.Height,
                        state.OutputVideoBitrate.Value,
                        state.VideoStream?.Codec,
                        state.OutputVideoCodec,
                        videoRequest.MaxWidth,
                        videoRequest.MaxHeight);

                    videoRequest.MaxWidth  = resolution.MaxWidth;
                    videoRequest.MaxHeight = resolution.MaxHeight;
                }
            }

            ApplyDeviceProfileSettings(state);

            var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
                ? GetOutputFileExtension(state)
                : ('.' + state.OutputContainer);

            var encodingOptions = ServerConfigurationManager.GetEncodingOptions();

            state.OutputFilePath = GetOutputFilePath(state, encodingOptions, ext);

            return(state);
        }
Exemplo n.º 28
0
 public void Init()
 {
     _manager = new ServerConfigurationManager(new ServerConfigurationXMLConverter());
     _manager.DeleteConfiguration();
 }