Ejemplo n.º 1
0
        public override async void Initialize()
        {
            //CreatableTypes()
            //    .EndingWith("Service")
            //    .AsInterfaces()
            //    .RegisterAsLazySingleton();

            var fileStore    = Mvx.Resolve <IMvxFileStore>();
            var loginService = new LoginService("perm.token", ClientId, ClientSecret, AuthorizeUri, RedirectUri, AccessUri, fileStore);

            Mvx.RegisterSingleton <ILoginService>(loginService);

            var hasLogin = loginService.SilentLoginAsync().Result;

            var traktService = new TraktService(ClientId, ClientSecret, RedirectUri, loginService.Token);

            Mvx.RegisterSingleton <ITraktService>(traktService);

            if (hasLogin)
            {
                RegisterAppStart <ViewModels.MainViewModel>();
            }
            else
            {
                RegisterAppStart <ViewModels.LoginViewModel>();
            }
        }
Ejemplo n.º 2
0
        public async void Create_WithNullModelThrowsException()
        {
            // Arrange
            var userManagerMock           = UserManagerHelpers.MockUserManager <User>();
            var httpContextAccessorMock   = Mock.Of <IHttpContextAccessor>();
            var traktApiConfigurationMock = Mock.Of <TraktAPIConfiguration>();

            // Act
            var traktService = new TraktService(userManagerMock.Object, httpContextAccessorMock, traktApiConfigurationMock);

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(async() => { await traktService.Create(null); });
        }
Ejemplo n.º 3
0
        public void CreateTraktServiceIsNotNull()
        {
            // Arrange
            var userManagerMock           = UserManagerHelpers.MockUserManager <User>();
            var httpContextAccessorMock   = Mock.Of <IHttpContextAccessor>();
            var traktApiConfigurationMock = Mock.Of <TraktAPIConfiguration>();

            // Act
            var traktService = new TraktService(userManagerMock.Object, httpContextAccessorMock, traktApiConfigurationMock);

            // Assert
            Assert.NotNull(traktService);
        }
Ejemplo n.º 4
0
        private static void ScheduleCuratorUpdates(Curator curator, TraktService ts)
        {
            Log.Information($"Scheduling update every {Interval} ..");

            // Schedule update.
            Timer timer = null;

            using (timer = new Timer((t) =>
            {
                timer.Change(Timeout.Infinite, Timeout.Infinite);
                try
                {
                    isBusy = true;

                    var result = UpdateCurator(curator);
                    if (result.Is(Curator.CuratorResult.Error, Curator.CuratorResult.NotInitialized, Curator.CuratorResult.Stopped))
                    {
                        Environment.Exit(1);
                    }

                    if (result.Is(Curator.CuratorResult.TraktAuthenticationRequired))
                    {
                        if (!AuthenticateTrakt(ts))
                        {
                            Environment.Exit(1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ConnectivityScriptPath) && (ex.GetBaseException() is System.Net.Sockets.SocketException sEx && sEx.ErrorCode == 10013) || (ex is Traktor.Core.Services.Indexer.RarbgIndexer.RarBgTokenException rEx))
                    {
                        Log.Error($"Caught exception: {ex.Message} - potential connectivity issue, launch connectivity script: {ConnectivityScriptPath}");
                        var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(ConnectivityScriptPath)
                        {
                            CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardError = true
                        });
                        process.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => Log.Debug($"[ConnectivityScript:Output] {e.Data}");
                        process.ErrorDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => Log.Debug($"[ConnectivityScript:Error] {e.Data}");
                        process.WaitForExit();
                    }
Ejemplo n.º 5
0
        public Library(TraktService trakt)
        {
            this.trakt = trakt;

            this.indexCol = new Dictionary <string, Media>();

            this.db = new LibraryDbContext();
            this.db.Migrate();

            this.assets = new AssetService();

            var mediaItems = this.db.Media.ToList();

            if (mediaItems.Any())
            {
                foreach (var item in mediaItems.OfType <Episode>())
                {
                    var entry = this.db.Entry(item);
                    item.ShowId = new Media.MediaId(
                        entry.Property("ShowTrakt").CurrentValue as int?,
                        entry.Property("ShowSlug").CurrentValue as string,
                        entry.Property("ShowIMDB").CurrentValue as string,
                        entry.Property("ShowTVDB").CurrentValue as int?,
                        entry.Property("ShowTMDB").CurrentValue as int?);
                }

                this.indexCol = mediaItems.ToDictionary(k => GetKeyForMedia(k), v => v);
            }
            else
            {
                this.indexCol = new Dictionary <string, Media>();
                var initial = GetMoviesFromTraktCollection().Cast <Media>().Concat(GetEpisodesFromTraktCollection()).ToList();

                this.AddRange(initial);
                this.AddRange(GetMediaFromTraktWatchlist().ToList());
            }

            this.LastActivityUpdate = this.Any() ? this.Max(x => x.CollectedAt ?? x.WatchlistedAt ?? DateTime.MinValue) : DateTime.MinValue;
        }
Ejemplo n.º 6
0
 public Curator(TraktService ts)
 {
     trakt = ts;
 }
Ejemplo n.º 7
0
 public TraktController(DatabaseContext database, TraktService traktService)
 {
     _database     = database;
     _traktService = traktService;
 }
Ejemplo n.º 8
0
        private static void RunTraktor(string[] args)
        {
            var logLevelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            Log.Logger = new LoggerConfiguration().MinimumLevel.ControlledBy(logLevelSwitch).WriteTo.Console(outputTemplate: "{Message}{NewLine}").WriteTo.File("Logs/.log", outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day).CreateLogger();

            try
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(Environment.CurrentDirectory)
                             .AddCommandLine(args)
                             .AddJsonFile("appsettings.json", true, true)
                             .Build();

                Interval  = config.GetValue <TimeSpan?>("interval") ?? TimeSpan.FromMinutes(5);
                KeepAlive = config.GetValue <bool>("keepalive");
                ConnectivityScriptPath = config.GetValue <string>("connectscript");

                var logLevel = config.GetValue <string>("loglevel");
                if (!string.IsNullOrEmpty(logLevel))
                {
                    logLevelSwitch.MinimumLevel = Enum.Parse <Serilog.Events.LogEventLevel>(logLevel);
                }
                else if (System.Diagnostics.Debugger.IsAttached)
                {
                    logLevelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
                }

                Log.Information($"Minimum log level = {logLevelSwitch.MinimumLevel}");
                AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
                {
                    LogException((Exception)e.ExceptionObject);
                };

                AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
                {
                    Log.Information("Shutting down ..");
                };

                if (logLevelSwitch.MinimumLevel == Serilog.Events.LogEventLevel.Verbose)
                {
                    Log.Information("Logging all exceptions raised (First Chance), this also includes handled exceptions.");
                    AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
                    {
                        Log.Verbose($"Exception (FC): {e.Exception}");
                    };
                }

                DisplayBindingIp();

                //Console.ReadLine();
                //return;

                Curator.CuratorConfiguration traktorConfig = LoadCuratorConfiguration(config, args);

                TraktService ts      = new TraktService();
                Curator      curator = new Curator(ts);

                if (StartCurator(curator, ts, traktorConfig))
                {
                    if (!string.IsNullOrEmpty(config.GetValue <string>("urls")))
                    {
                        var startup = new Traktor.Web.Startup(config, curator);
                        var host    = Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(x =>
                        {
                            x.ConfigureServices(startup.ConfigureServices).Configure(startup.Configure);
                        }).UseConsoleLifetime().Build().RunAsync();

                        Log.Information($"Running Traktor.Web @ {string.Join(", ", startup.Addresses)}");
                    }

                    appSettingsHash = FileService.ComputeHash("appsettings.json");
                    ChangeToken.OnChange(() => config.GetReloadToken(), () =>
                    {
                        var currentHash = FileService.ComputeHash("appsettings.json");
                        if (currentHash.SequenceEqual(appSettingsHash))
                        {
                            return;
                        }

                        appSettingsHash = FileService.ComputeHash("appsettings.json");
                        curator.UpdateConfiguration(LoadCuratorConfiguration(config, args));

                        Log.Information("Updated configuration! (Changes to Downloader settings requires a restart to take effect)");
                    });

                    ScheduleCuratorUpdates(curator, ts);
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw;
            }
        }