Exemple #1
0
 public CommandController(IOptions <ElasticConfig> config,
                          ILoggerFactory loggerFactory,
                          IElasticConnectionClient elasticConnectionClient,
                          SynkerDbContext context)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
 }
Exemple #2
0
 public MediaRefService(SynkerDbContext synkerDbContext, IElasticConnectionClient elasticConnectionClient,
                        ILoggerFactory loggerFactory)
 {
     _dbcontext = synkerDbContext;
     _elasticConnectionClient = elasticConnectionClient;
     _logger = loggerFactory.CreateLogger(nameof(MediaRefService));
 }
 public PlaylistHealthHostedService(ILoggerFactory loggerFactory, IPlaylistService playlistService, SynkerDbContext synkerDbContext,
                                    IBus requestClient)
 {
     _logger          = loggerFactory.CreateLogger <PlaylistHealthHostedService>();
     _playlistService = playlistService;
     _dbContext       = synkerDbContext;
     _bus             = requestClient;
 }
Exemple #4
0
 public BaseController(IOptions <ElasticConfig> elasticConfig, ILoggerFactory loggerFactory, IElasticConnectionClient elasticConnectionClient,
                       SynkerDbContext context)
 {
     _logger = loggerFactory.CreateLogger(nameof(BaseController));
     _elasticConnectionClient = elasticConnectionClient;
     _elasticConfig           = elasticConfig.Value;
     _dbContext = context;
 }
Exemple #5
0
 public PiconsController(IPiconsService piconsService, IOptions <ElasticConfig> config, ILoggerFactory loggerFactory,
                         IElasticConnectionClient elasticConnectionClient, SynkerDbContext context, IMediaScraper mediaScraper, IOptions <GlobalOptions> globalOptions)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _piconsService = piconsService ?? throw new ArgumentNullException(nameof(piconsService));
     _mediaScraper  = mediaScraper ?? throw new ArgumentNullException(nameof(mediaScraper));
     _globalOptions = globalOptions.Value ?? throw new ArgumentNullException(nameof(globalOptions));
 }
 public SitePackController(IMemoryCache memoryCache, ISitePackService sitePackService, IOptions <ElasticConfig> config, ILoggerFactory loggerFactory,
                           IElasticConnectionClient elasticConnectionClient, SynkerDbContext context, IPasteBinService pasteBinService)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _memoryCache     = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
     _sitePackService = sitePackService ?? throw new ArgumentNullException(nameof(sitePackService));
     _pasteBinService = pasteBinService ?? throw new ArgumentNullException(nameof(pasteBinService));
 }
Exemple #7
0
        //public string EndPoint => $"http://rabbitmq.synker.ovh/diff_playlist_{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}_queue";
        //public string TraceEndPoint => $"http://rabbitmq.synker.ovh/trace_{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}_queue";

        public DiffHostedService(ILogger <DiffHostedService> logger, IPlaylistService playlistService, SynkerDbContext synkerDbContext,
                                 IBus requestClient, IProviderFactory providerFactory)
        {
            _logger          = logger;
            _playlistService = playlistService;
            _dbContext       = synkerDbContext;
            _bus             = requestClient;
            _providerFactory = providerFactory;
        }
Exemple #8
0
 public PlaylistService(SynkerDbContext synkerDbContext, IElasticConnectionClient elasticConnectionClient,
                        IContextTvgMediaHandler contextHandler, ILoggerFactory loggerFactory, IOptions <ElasticConfig> elasticConfig, ISitePackService sitePackService, IProviderFactory providerFactory)
 {
     _dbcontext = synkerDbContext;
     _elasticConnectionClient = elasticConnectionClient;
     _contextHandler          = contextHandler;
     _logger          = loggerFactory.CreateLogger(nameof(PlaylistService));
     _elasticConfig   = elasticConfig;
     _sitePackService = sitePackService;
     _providerFactory = providerFactory;
 }
Exemple #9
0
 public MediaServerController(IOptions <ElasticConfig> config,
                              MediaServerService mediaServerService,
                              IOptions <MediaServerOptions> mediaServerOptions,
                              ILoggerFactory loggerFactory,
                              IElasticConnectionClient elasticConnectionClient,
                              SynkerDbContext context)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _mediaServerService = mediaServerService;
     _mediaServerOptions = mediaServerOptions;
 }
 public PlaylistsController(IMemoryCache memoryCache, IMediaScraper mediaScraper, IOptions <ElasticConfig> config, ILoggerFactory loggerFactory, IOptions <GlobalOptions> globalOptions,
                            IElasticConnectionClient elasticConnectionClient, SynkerDbContext context, IPlaylistService playlistService, ISitePackService sitePackService, IXtreamService xtreamService,
                            IProviderFactory providerFactory)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _playlistService = playlistService ?? throw new ArgumentNullException(nameof(playlistService));
     _mediaScraper    = mediaScraper ?? throw new ArgumentNullException(nameof(mediaScraper));
     _memoryCache     = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
     _sitePackService = sitePackService ?? throw new ArgumentNullException(nameof(sitePackService));
     _globalOptions   = globalOptions.Value ?? throw new ArgumentNullException(nameof(globalOptions));
     _xtreamService   = xtreamService ?? throw new ArgumentNullException(nameof(xtreamService));
     _providerFactory = providerFactory ?? throw new ArgumentNullException(nameof(providerFactory));
 }
Exemple #11
0
 public NotificationController(IMessageQueueService notificationService, IOptions <ElasticConfig> config, ILoggerFactory loggerFactory,
                               IElasticConnectionClient elasticConnectionClient, SynkerDbContext context, IHubContext <NotificationHub> notifcationHubContext, IOptions <VapidKeysOptions> vapidKeysOptions)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _notificationService   = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
     _vapidKeysConfig       = vapidKeysOptions.Value;
     _notifcationHubContext = notifcationHubContext;
 }
Exemple #12
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            _serviceDescriptors = services;
            string connectionstring = Configuration.GetConnectionString("PlDatabase");
            bool   isTestEnv        = string.IsNullOrEmpty(connectionstring) || CurrentEnvironment.IsEnvironment("Testing");

            services.
            AddSingleton <IElasticConnectionClient, ElasticConnectionClient>()
            .AddSingleton <IPasteBinService, PasteBinService>()
            .AddSingleton <IProviderFactory, ProviderFactory>()
            .AddSingleton <IContextTvgMediaHandler, ContextTvgMediaHandler>()
            .AddScoped <IXmltvService, XmltvService>()
            .AddScoped <IPiconsService, PiconsService>()
            .AddScoped <IPlaylistService, PlaylistService>()
            .AddScoped <IMediaRefService, MediaRefService>()
            .AddScoped <ISitePackService, SitePackService>()
            .AddScoped <ICommandService, CommandService>()
            .AddScoped <IXtreamService, XtreamService>()
            .AddScoped <IMediaScraper, MediaScraper>()
            .AddScoped <IWebGrabConfigService, WebGrabConfigService>()
            .AddScoped <IMessageQueueService, MessageQueueService>()
            .Configure <RabbitMQConfiguration>(Configuration.GetSection(nameof(RabbitMQConfiguration)))
            .Configure <List <PlaylistProviderOption> >(Configuration.GetSection(PlaylistProviderOption.PlaylistProvidersConfigurationKeyName))
            .Configure <ElasticConfig>(Configuration.GetSection(nameof(ElasticConfig)))
            .Configure <JwtBearerOptions>(Configuration.GetSection(nameof(JwtBearerOptions)))
            .Configure <MediaServerOptions>(Configuration.GetSection(nameof(MediaServerOptions)))
            .Configure <GlobalOptions>(Configuration.GetSection(nameof(GlobalOptions)))
            .Configure <PastBinOptions>(Configuration.GetSection(nameof(PastBinOptions)))
            .Configure <VapidKeysOptions>(Configuration.GetSection(nameof(VapidKeysOptions)));

            var retryPolicy = HttpPolicyExtensions
                              .HandleTransientHttpError()
                              .RetryAsync(3);
            //.CircuitBreaker(5, TimeSpan.FromSeconds(30));

            var noOp = Policy.NoOpAsync().AsAsyncPolicy <HttpResponseMessage>();

            services.AddHttpClient <MediaServerService>(c =>
            {
                var ServerMediaOptions = Provider.GetService <IOptions <MediaServerOptions> >();
                var scheme             = ServerMediaOptions.Value.IsSecure ? "https" : "http";
                c.BaseAddress          = new Uri($"{scheme}://{ServerMediaOptions.Value.Host}:{ServerMediaOptions.Value.Port}/");
                c.DefaultRequestHeaders.Add("Accept", "application/json");
                c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
            }).AddPolicyHandler(request => request.Method == HttpMethod.Get ? retryPolicy : noOp);

            //.AddTransientHttpErrorPolicy(p => p.RetryAsync(3))
            //.AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));

            services.AddSingleton(typeof(HubLifetimeManager <>), typeof(DefaultHubLifetimeManager <>));
            services.AddSingleton(typeof(IHubProtocolResolver), typeof(DefaultHubProtocolResolver));
            services.AddScoped(typeof(IHubActivator <>), typeof(DefaultHubActivator <>));

            services.AddHttpContextAccessor();
            services.AddSignalR();
            services.AddMemoryCache();

            if (isTestEnv)
            {
                services.AddDbContext <SynkerDbContext>(options =>
                {
                    options.UseInMemoryDatabase("playlist");
                });
            }
            else
            {
                services.AddDbContext <SynkerDbContext>(options =>
                {
                    options.UseNpgsql(Configuration.GetConnectionString("PlDatabase"),
                                      sqlOptions =>
                    {
                        sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                        //Configuring Connection Resiliency:
                        sqlOptions.
                        EnableRetryOnFailure(3, TimeSpan.FromSeconds(30), null);
                    });

                    //// Changing default behavior when client evaluation occurs to throw.
                    //// Default in EFCore would be to log warning when client evaluation is done.
                    //options.ConfigureWarnings(warnings => warnings.Throw(
                    //RelationalEventId.QueryClientEvaluationWarning));
                });

                _synkerDbContext = Provider.GetService <SynkerDbContext>();
                _synkerDbContext.Database.EnsureCreated();
            }

            services.AddRabbitMq();
            services.AddSecurity();

            #region Compression
            services.Configure <GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
            services.AddResponseCompression(options =>
            {
                options.MimeTypes = new[]
                {
                    // Default
                    "text/plain",
                    "text/css",
                    "application/javascript",
                    "text/html",
                    "application/xml",
                    "text/xml",
                    "application/json",
                    "text/json",
                    // Custom
                    "image/svg+xml"
                };
            });
            #endregion

            //Logger
            LoggerFactory loggerFactory = new LoggerFactory();

            //cache
            services.AddResponseCaching(options =>
            {
                options.UseCaseSensitivePaths = true;
                options.MaximumBodySize       = 1024;
            });

            //MVC
            services.AddMvc(config =>
            {
                config.EnableEndpointRouting = false;
                config.Filters.Add(typeof(GlobalExceptionFilterAttribute));
                config.CacheProfiles.Add("Default",
                                         new CacheProfile()
                {
                    Duration = 60,
                    Location = ResponseCacheLocation.Any
                });
                config.CacheProfiles.Add("Long",
                                         new CacheProfile()
                {
                    Duration = 60
                });
                config.CacheProfiles.Add("Never",
                                         new CacheProfile()
                {
                    Location = ResponseCacheLocation.None,
                    NoStore  = true
                });
            })
            .AddJsonOptions(
                options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.Formatting            = Formatting.Indented;
                options.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
            }
                ).SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });

            //https://github.com/domaindrivendev/Swashbuckle.AspNetCore
            var jwtOptions = Configuration.GetSection(nameof(JwtBearerOptions)).Get <JwtBearerOptions>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "Synker API",
                    Description    = $"Synchronize playlists API {AssemblyVersion}",
                    TermsOfService = "None",
                    Contact        = new Contact {
                        Name = "Synker", Email = "*****@*****.**", Url = "https://www.github.com/fazzani/synker2"
                    },
                    License = new License {
                        Name = "Use under MIT", Url = ""
                    },
                });
                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Description      = "OAuth2 Implicit Grant",
                    Flow             = "implicit",
                    AuthorizationUrl = $"{jwtOptions.Authority}/connect/authorize",
                    TokenUrl         = $"{jwtOptions.Authority}/connect/token",
                    Scopes           = new Dictionary <string, string>
                    {
                        { "synkerapi.full_access", "Full access operations" },
                        { "synkerapi.readonly", "ReadOnly access operations" }
                    }
                });

                c.OperationFilter <SecurityRequirementsOperationFilter>();
                c.DescribeAllEnumsAsStrings();
                c.DescribeStringEnumsInCamelCase();
                c.IgnoreObsoleteActions();
                c.IgnoreObsoleteProperties();
                c.SchemaFilter <AutoRestSchemaFilter>();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.WithOrigins(CurrentEnvironment.IsDevelopment() ? "http://localhost:56810" : "https://synker.ovh", "https://www.synker.ovh", "https://xviewer.synker.ovh", "https://holo.synker.ovh")
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            #region Webhooks
            // services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.UseGithubWebhook(() => new GithubOptions
            {
                ApiKey        = Configuration.GetValue <string>("GitHubHookApiKey"),
                WebHookAction = genericHookAction
            }).UseAppVeyorWebhook(() => new AppveyorOptions
            {
                ApiKey        = Configuration.GetValue <string>("AppveyorHookApiKey"),
                WebHookAction = genericHookAction
            });
            #endregion
        }
Exemple #13
0
        /// <summary>
        ///  This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="synkerDbContext"></param>
        /// <param name="applicationLifetime"></param>
        /// <param name="serviceProvider"></param>
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory,
                              SynkerDbContext synkerDbContext, Microsoft.AspNetCore.Hosting.IApplicationLifetime applicationLifetime, IServiceProvider serviceProvider)
        {
            app.UseCookiePolicy();
            app.UseCors("CorsPolicy");

            ILogger <Startup> log = loggerFactory.CreateLogger <Startup>();

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            app.Map("/liveness", lapp => lapp.Run(async ctx => ctx.Response.StatusCode = 200));

            app.UseHttpContext();
            app.UseResponseCompression();

            string appAbout = JsonConvert.SerializeObject(new ApplicationAbout
            {
                Author          = "Synker corporation",
                ApplicationName = "Synker",
            });

            app.Map("/about", lapp => lapp.Run(async ctx =>
            {
                log.LogDebug("about");
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 200;
                await ctx.Response.WriteAsync(appAbout);
            }));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            synkerDbContext.Database.Migrate();

            loggerFactory.AddFile(Configuration.GetSection("Logging"));

            if (env.IsDevelopment())
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
            }

            try
            {
                if (Configuration.GetValue <bool>("UseLoadTest"))
                {
                    app.UseMiddleware <ByPassAuthMiddleware>();
                }
                app.UseAuthentication();

                #region Swagger

                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Synker API V1");
                    c.OAuthClientId("synker_swagger_api");
                    c.OAuthAppName("Synker API - Swagger");
                    //c.DefaultModelExpandDepth(2);
                    //c.DefaultModelRendering(ModelRendering.Model);
                    //c.DefaultModelsExpandDepth(-1);
                    c.DisplayOperationId();
                    c.DisplayRequestDuration();
                    c.DocExpansion(DocExpansion.None);
                    c.EnableDeepLinking();
                    c.EnableFilter();
                    //c.MaxDisplayedTags(5);
                    c.ShowExtensions();
                    c.EnableValidator();
                    c.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Post, SubmitMethod.Delete, SubmitMethod.Put);
                });
                #endregion

                app.UseWebHooks(typeof(AppveyorReceiver));
                app.UseWebHooks(typeof(GithubReceiver));
                //Cache
                app.UseResponseCaching();

                app.UseStaticFiles();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=HealthCheck}/{action=Index}/{id?}");
                });

                app.UseSignalR(routes =>
                {
                    routes.MapHub <NotificationHub>("/hubs/notification");
                });
            }
            catch (Exception ex)
            {
                app.Run(
                    async context =>
                {
                    log.LogError($"{ex.Message}");

                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync(ex.Message).ConfigureAwait(false);
                    await context.Response.WriteAsync(ex.StackTrace).ConfigureAwait(false);
                });
            }
        }
Exemple #14
0
 public CommandService(SynkerDbContext synkerDbContext, ILoggerFactory loggerFactory)
 {
     _dbcontext = synkerDbContext;
     _logger    = loggerFactory.CreateLogger(nameof(CommandService));
 }
Exemple #15
0
 public TvgMediaController(IOptions <ElasticConfig> config, ILoggerFactory loggerFactory, IElasticConnectionClient elasticConnectionClient,
                           SynkerDbContext context, ISitePackService sitePackService)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _sitePackService = sitePackService ?? throw new ArgumentNullException(nameof(sitePackService));
 }
Exemple #16
0
 public static void InitializeDbForTests(SynkerDbContext context)
 {
     SynkerInitializer.Initialize(context);
 }
Exemple #17
0
 public XtreamController(IXtreamService xtreamService, IOptions <ElasticConfig> config, ILoggerFactory loggerFactory,
                         IElasticConnectionClient elasticConnectionClient, SynkerDbContext context)
     : base(config, loggerFactory, elasticConnectionClient, context)
 {
     _xtreamService = xtreamService ?? throw new ArgumentNullException(nameof(xtreamService));
 }
Exemple #18
0
 public WebGrabConfigService(SynkerDbContext synkerDbContext, ILoggerFactory loggerFactory)
 {
     _dbcontext = synkerDbContext;
     _logger    = loggerFactory.CreateLogger(nameof(WebGrabConfigService));
 }