Exemplo n.º 1
0
        // for existing sites, update settings from configuration once
        public async override Task ActivatedAsync()
        {
            var section = _shellConfiguration.GetSection("StatCan_Configuration");

            if (section.GetValue <bool>("OverwriteSmtpSettings"))
            {
                await UpdateConfiguration();
            }
        }
Exemplo n.º 2
0
        public Startup(IShellConfiguration shellConfiguration)
        {
            var configurationSection = shellConfiguration.GetSection("OrchardCore.Media");

            _maxBrowserCacheDays = configurationSection.GetValue("MaxBrowserCacheDays", 30);
            _maxCacheDays        = configurationSection.GetValue("MaxCacheDays", 365);
        }
        public void Configure(string name, DocumentOptions options)
        {
            var config = _cache.GetOrAdd(name, name =>
            {
                var options = _shellConfiguration.GetSection(name).Get <DocumentOptions>() ?? new DocumentOptions();

                options.CacheKey ??= name;
                options.CacheIdKey ??= "ID_" + name;
                options.CheckConcurrency ??= true;
                options.CheckConsistency ??= true;
                options.SynchronizationLatency ??= TimeSpan.FromSeconds(1);

                options.Serializer = DefaultDocumentSerializer.Instance;

                if (options.CompressThreshold == 0)
                {
                    options.CompressThreshold = 10_000;
                }

                return(options);
            });

            options.CacheKey               = config.CacheKey;
            options.CacheIdKey             = config.CacheIdKey;
            options.CheckConcurrency       = config.CheckConcurrency;
            options.CheckConsistency       = config.CheckConsistency;
            options.SynchronizationLatency = config.SynchronizationLatency;
            options.Serializer             = config.Serializer;
            options.CompressThreshold      = config.CompressThreshold;
        }
Exemplo n.º 4
0
        public Startup(IShellConfiguration shellConfiguration)
        {
            var configurationSection = shellConfiguration.GetSection("OrchardCore.Setup");

            _defaultCulture    = configurationSection["DefaultCulture"];
            _supportedCultures = configurationSection.GetSection("SupportedCultures").Get <string[]>();
        }
Exemplo n.º 5
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.Configure <MediaBlobStorageOptions>(_configuration.GetSection("OrchardCore.Media.Azure"));

            // Only replace default implementation if options are valid.
            var connectionString = _configuration[$"OrchardCore.Media.Azure:{nameof(MediaBlobStorageOptions.ConnectionString)}"];
            var containerName    = _configuration[$"OrchardCore.Media.Azure:{nameof(MediaBlobStorageOptions.ContainerName)}"];

            if (MediaBlobStorageOptionsCheckFilter.CheckOptions(connectionString, containerName, _logger))
            {
                services.Replace(ServiceDescriptor.Singleton <IMediaFileStore>(serviceProvider =>
                {
                    var options             = serviceProvider.GetRequiredService <IOptions <MediaBlobStorageOptions> >().Value;
                    var clock               = serviceProvider.GetRequiredService <IClock>();
                    var contentTypeProvider = serviceProvider.GetRequiredService <IContentTypeProvider>();

                    var fileStore = new BlobFileStore(options, clock, contentTypeProvider);

                    var mediaBaseUri = fileStore.BaseUri;
                    if (!String.IsNullOrEmpty(options.PublicHostName))
                    {
                        mediaBaseUri = new UriBuilder(mediaBaseUri)
                        {
                            Host = options.PublicHostName
                        }
                    }
                    .Uri;

                    return(new MediaFileStore(fileStore, mediaBaseUri.ToString()));
                }));
Exemplo n.º 6
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddNavigation();

            services.Configure <MvcOptions>((options) =>
            {
                options.Filters.Add(typeof(AdminFilter));
                options.Filters.Add(typeof(AdminMenuFilter));

                // Ordered to be called before any global filter.
                options.Filters.Add(typeof(AdminZoneFilter), -1000);
            });

            services.AddTransient <IAreaControllerRouteMapper, AdminAreaControllerRouteMapper>();

            services.AddScoped <IPermissionProvider, Permissions>();
            services.AddScoped <IThemeSelector, AdminThemeSelector>();
            services.AddScoped <IAdminThemeService, AdminThemeService>();

            services.AddScoped <IDisplayDriver <ISite>, AdminSiteSettingsDisplayDriver>();
            services.AddScoped <IPermissionProvider, PermissionsAdminSettings>();
            services.AddScoped <INavigationProvider, AdminMenu>();

            services.Configure <AdminOptions>(_configuration.GetSection("OrchardCore.Admin"));

            services.AddSingleton <IPageRouteModelProvider, AdminPageRouteModelProvider>();
        }
Exemplo n.º 7
0
        public Startup(IShellConfiguration shellConfiguration)
        {
            var configurationSection = shellConfiguration.GetSection("OrchardCore_Setup");

            _defaultCulture    = configurationSection["DefaultCulture"] ?? _defaultCulture;
            _supportedCultures = configurationSection.GetSection("SupportedCultures").Get <List <string> >()?.ToArray() ?? _supportedCultures;
        }
Exemplo n.º 8
0
        public Startup(IShellConfiguration shellConfiguration)
        {
            var configurationSection = shellConfiguration.GetSection("OrchardCore.Media");

            _supportedSizes      = configurationSection.GetSection("SupportedSizes").Get <int[]>() ?? DefaultSizes;
            _maxBrowserCacheDays = configurationSection.GetValue("MaxBrowserCacheDays", 30);
            _maxCacheDays        = configurationSection.GetValue("MaxCacheDays", 365);
        }
Exemplo n.º 9
0
 public override void ConfigureServices(IServiceCollection services)
 {
     services.AddLiquidFilter <SwitchCultureUrlFilter>("switch_culture_url");
     services.AddScoped <INavigationProvider, AdminMenu>();
     services.AddScoped <IContentCulturePickerService, ContentCulturePickerService>();
     services.AddScoped <IDisplayDriver <ISite>, ContentCulturePickerSettingsDriver>();
     services.AddScoped <IDisplayDriver <ISite>, ContentRequestCultureProviderSettingsDriver>();
     services.Configure <RequestLocalizationOptions>(options => options.AddInitialRequestCultureProvider(new ContentRequestCultureProvider()));
     services.Configure <CulturePickerOptions>(_shellConfiguration.GetSection("OrchardCore_ContentLocalization_CulturePickerOptions"));
 }
Exemplo n.º 10
0
 public override void ConfigureServices(IServiceCollection services)
 {
     services.AddScoped <ReverseProxySettingsUpdater>();
     services.AddScoped <IFeatureEventHandler>(sp => sp.GetRequiredService <ReverseProxySettingsUpdater>());
     services.AddScoped <IModularTenantEvents>(sp => sp.GetRequiredService <ReverseProxySettingsUpdater>());
     if (_shellConfiguration.GetSection("StatCan_Configuration").GetValue <bool>("OverwriteReverseProxySettings"))
     {
         var serviceDescriptor = services.FirstOrDefault(descriptor => descriptor.ImplementationType == typeof(ReverseProxy.AdminMenu));
         services.Remove(serviceDescriptor);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// The configure services.
        /// </summary>
        /// <param name="services">
        /// The services.
        /// </param>
        public override void ConfigureServices(IServiceCollection services)
        {
            var configuration = _shellConfiguration.GetSection(ConfigSectionName);

            services.Configure <AutoSetupOptions>(configuration);

            if (configuration.Exists())
            {
                services.Configure <AutoSetupOptions>(o => o.ConfigurationExists = true);
            }
        }
Exemplo n.º 12
0
        public MediaFileProvider(
            IMediaFileStore mediaStore,
            IOptions <ImageSharpMiddlewareOptions> options,
            IShellConfiguration shellConfiguration)
        {
            _mediaStore      = mediaStore;
            _formatUtilities = new FormatUtilities(options.Value.Configuration);

            var configurationSection = shellConfiguration.GetSection("OrchardCore.Media");

            _supportedSizes = configurationSection.GetSection("SupportedSizes").Get <int[]>()?.OrderBy(s => s).ToArray() ?? DefaultSizes;
        }
Exemplo n.º 13
0
    public static AwsStorageOptions BindConfiguration(this AwsStorageOptions options, IShellConfiguration shellConfiguration)
    {
        var section = shellConfiguration.GetSection("OrchardCore_Media_AmazonS3");

        if (section == null)
        {
            return(options);
        }

        options.BucketName   = section.GetValue(nameof(options.BucketName), String.Empty);
        options.BasePath     = section.GetValue(nameof(options.BasePath), String.Empty);
        options.CreateBucket = section.GetValue(nameof(options.CreateBucket), false);

        var credentials = section.GetSection("Credentials");

        if (credentials.Exists())
        {
            options.Credentials = new AwsStorageCredentials
            {
                RegionEndpoint =
                    credentials.GetValue(nameof(options.Credentials.RegionEndpoint), RegionEndpoint.USEast1.SystemName),
                SecretKey   = credentials.GetValue(nameof(options.Credentials.SecretKey), String.Empty),
                AccessKeyId = credentials.GetValue(nameof(options.Credentials.AccessKeyId), String.Empty),
            };
        }
        else
        {
            // Attempt to load Credentials from Profile.
            var profileName = section.GetValue("ProfileName", String.Empty);
            if (!String.IsNullOrEmpty(profileName))
            {
                var chain = new CredentialProfileStoreChain();
                if (chain.TryGetProfile(profileName, out var basicProfile))
                {
                    var awsCredentials = basicProfile.GetAWSCredentials(chain)?.GetCredentials();
                    if (awsCredentials != null)
                    {
                        options.Credentials = new AwsStorageCredentials
                        {
                            RegionEndpoint = basicProfile.Region.SystemName ?? RegionEndpoint.USEast1.SystemName,
                            SecretKey      = awsCredentials.SecretKey,
                            AccessKeyId    = awsCredentials.AccessKey
                        };
                    }
                }
            }
        }

        return(options);
    }
Exemplo n.º 14
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IDynamicCacheService, DefaultDynamicCacheService>();
            services.AddScoped <ITagRemovedEventHandler>(sp => sp.GetRequiredService <IDynamicCacheService>());

            services.AddScoped <IShapeDisplayEvents, DynamicCacheShapeDisplayEvents>();
            services.AddShapeAttributes <CachedShapeWrapperShapes>();

            services.AddSingleton <IDynamicCache, DefaultDynamicCache>();
            services.AddSingleton <DynamicCacheTagHelperService>();
            services.AddTagHelpers <DynamicCacheTagHelper>();
            services.AddTagHelpers <CacheDependencyTagHelper>();

            services.AddTransient <IConfigureOptions <CacheOptions>, CacheOptionsConfiguration>();
            services.Configure <DynamicCacheOptions>(_shellConfiguration.GetSection("OrchardCore_DynamicCache"));
        }
Exemplo n.º 15
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CulturePickerOptions>(_shellConfiguration.GetSection("OrchardCore_ContentLocalization_CulturePickerOptions"));

            services.AddScoped <IContentPartIndexHandler, LocalizationPartIndexHandler>();
            services.AddSingleton <ILocalizationEntries, LocalizationEntries>();
            services.AddContentLocalization();

            services.AddScoped <IPermissionProvider, Permissions>();
            services.AddScoped <IAuthorizationHandler, LocalizeContentAuthorizationHandler>();

            services.AddScoped <IContentsAdminListFilter, LocalizationPartContentsAdminListFilter>();
            services.AddScoped <IDisplayDriver <ContentOptionsViewModel>, LocalizationContentsAdminListDisplayDriver>();

            services.AddLiquidFilter <ContentLocalizationFilter>("localization_set");
            services.AddLiquidFilter <SwitchCultureUrlFilter>("switch_culture_url");
        }
Exemplo n.º 16
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddNavigation();

            services.Configure <MvcOptions>((options) =>
            {
                options.Filters.Add(typeof(AdminFilter));
                options.Filters.Add(typeof(AdminMenuFilter));

                // Ordered to be called before any global filter.
                options.Filters.Add(typeof(AdminZoneFilter), -1000);
            });

            services.AddScoped <IPermissionProvider, Permissions>();
            services.AddScoped <IThemeSelector, AdminThemeSelector>();
            services.AddScoped <IAdminThemeService, AdminThemeService>();
            services.Configure <AdminOptions>(_configuration.GetSection("OrchardCore.Admin"));
        }
        public void Configure(MediaBlobStorageOptions options)
        {
            var section = _shellConfiguration.GetSection("OrchardCore_Media_Azure");

            options.BasePath         = section.GetValue(nameof(options.BasePath), String.Empty);
            options.ContainerName    = section.GetValue(nameof(options.ContainerName), String.Empty);
            options.ConnectionString = section.GetValue(nameof(options.ConnectionString), String.Empty);
            options.CreateContainer  = section.GetValue(nameof(options.CreateContainer), true);

            var templateContext = new TemplateContext();

            templateContext.MemberAccessStrategy.Register <ShellSettings>();
            templateContext.MemberAccessStrategy.Register <MediaBlobStorageOptions>();
            templateContext.SetValue("ShellSettings", _shellSettings);

            ParseContainerName(options, templateContext);
            ParseBasePath(options, templateContext);
        }
Exemplo n.º 18
0
    public static AwsStorageOptions BindConfiguration(this AwsStorageOptions options, IShellConfiguration shellConfiguration, ILogger logger)
    {
        var section = shellConfiguration.GetSection("OrchardCore_Media_AmazonS3");

        if (!section.Exists())
        {
            return(options);
        }

        options.BucketName   = section.GetValue(nameof(options.BucketName), String.Empty);
        options.BasePath     = section.GetValue(nameof(options.BasePath), String.Empty);
        options.CreateBucket = section.GetValue(nameof(options.CreateBucket), false);

        try
        {
            // Binding AWS Options
            options.AwsOptions = shellConfiguration.GetAWSOptions("OrchardCore_Media_AmazonS3");

            // In case Credentials sections was specified, trying to add BasicAWSCredential to AWSOptions
            // since by design GetAWSOptions skips Credential section while parsing config.
            var credentials = section.GetSection("Credentials");
            if (credentials.Exists())
            {
                var secretKey = credentials.GetValue(Constants.AwsCredentialParamNames.SecretKey, String.Empty);
                var accessKey = credentials.GetValue(Constants.AwsCredentialParamNames.AccessKey, String.Empty);

                if (!String.IsNullOrWhiteSpace(accessKey) ||
                    !String.IsNullOrWhiteSpace(secretKey))
                {
                    var awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
                    options.AwsOptions.Credentials = awsCredentials;
                }
            }

            return(options);
        }
        catch (ConfigurationException ex)
        {
            logger.LogCritical(ex, ex.Message);
            throw;
        }
    }
        public void Configure(MediaOptions options)
        {
            var section = _shellConfiguration.GetSection("OrchardCore.Media");

            // Because IShellConfiguration treats arrays as key value pairs, we replace the array value,
            // rather than letting Configure merge the default array with the appsettings value.
            options.SupportedSizes = section.GetSection("SupportedSizes")
                                     .Get <int[]>()?.OrderBy(s => s).ToArray() ?? DefaultSupportedSizes;

            options.AllowedFileExtensions = new HashSet <string>(
                section.GetSection("AllowedFileExtensions").Get <string[]>() ?? DefaultAllowedFileExtensions,
                StringComparer.OrdinalIgnoreCase);

            options.MaxBrowserCacheDays = section.GetValue("MaxBrowserCacheDays", DefaultMaxBrowserCacheDays);
            options.MaxCacheDays        = section.GetValue("MaxCacheDays", DefaultMaxCacheDays);
            options.MaxFileSize         = section.GetValue("MaxFileSize", DefaultMaxFileSize);
            options.CdnBaseUrl          = section.GetValue("CdnBaseUrl", String.Empty).TrimEnd('/').ToLower();
            options.AssetsRequestPath   = section.GetValue("AssetsRequestPath", DefaultAssetsRequestPath);
            options.AssetsPath          = section.GetValue("AssetsPath", DefaultAssetsPath);
        }
Exemplo n.º 20
0
        public void Configure(MediaS3StorageOptions options)
        {
            var section = _shellConfiguration.GetSection("OrchardCore_Media_S3");

            options.S3BucketName    = section.GetValue(nameof(options.S3BucketName), "orchardcoremedia");
            options.S3BasePath      = section.GetValue(nameof(options.S3BasePath), string.Empty);
            options.S3HostEndpoint  = section.GetValue(nameof(options.S3HostEndpoint), string.Empty);
            options.S3Region        = section.GetValue(nameof(options.S3Region), RegionEndpoint.EUCentral1.SystemName);
            options.S3AccessKey     = section.GetValue(nameof(options.S3AccessKey), string.Empty);
            options.S3SecretKey     = section.GetValue(nameof(options.S3SecretKey), string.Empty);
            options.CreateContainer = section.GetValue(nameof(options.CreateContainer), true);

            var templateContext = new TemplateContext();

            templateContext.MemberAccessStrategy.Register <ShellSettings>();
            templateContext.MemberAccessStrategy.Register <MediaS3StorageOptions>();
            templateContext.SetValue("ShellSettings", _shellSettings);

            ParseContainerName(options, templateContext);
            ParseBasePath(options, templateContext);
        }
Exemplo n.º 21
0
        public void Configure(string name, DocumentOptions options)
        {
            var config = _shellConfiguration.GetSection(name).Get <DocumentOptions>() ?? new DocumentOptions();

            config.CacheKey ??= name;
            config.CacheIdKey ??= "ID_" + name;
            config.CheckConcurrency ??= true;
            config.CheckConsistency ??= true;
            config.SynchronizationLatency ??= TimeSpan.FromSeconds(1);

            config.Serializer = DefaultDocumentSerializer.Instance;

            if (config.CompressThreshold == 0)
            {
                config.CompressThreshold = 10_000;
            }

            // Only used by an explicit atomic update.
            if (config.LockTimeout <= 0)
            {
                config.LockTimeout = 10_000;
            }

            if (config.LockExpiration <= 0)
            {
                config.LockExpiration = 10_000;
            }

            options.CacheKey               = config.CacheKey;
            options.CacheIdKey             = config.CacheIdKey;
            options.CheckConcurrency       = config.CheckConcurrency;
            options.CheckConsistency       = config.CheckConsistency;
            options.SynchronizationLatency = config.SynchronizationLatency;
            options.Serializer             = config.Serializer;
            options.CompressThreshold      = config.CompressThreshold;

            // Only used by an explicit atomic update.
            options.LockTimeout    = config.LockTimeout;
            options.LockExpiration = config.LockExpiration;
        }
        public void Configure(MediaOptions options)
        {
            var section = _shellConfiguration.GetSection("OrchardCore_Media");

            // Because IShellConfiguration treats arrays as key value pairs, we replace the array value,
            // rather than letting Configure merge the default array with the appsettings value.
            options.SupportedSizes = section.GetSection("SupportedSizes")
                                     .Get <int[]>()?.OrderBy(s => s).ToArray() ?? DefaultSupportedSizes;

            options.AllowedFileExtensions = new HashSet <string>(
                section.GetSection("AllowedFileExtensions").Get <string[]>() ?? DefaultAllowedFileExtensions,
                StringComparer.OrdinalIgnoreCase);

            options.MaxBrowserCacheDays     = section.GetValue("MaxBrowserCacheDays", DefaultMaxBrowserCacheDays);
            options.MaxCacheDays            = section.GetValue("MaxCacheDays", DefaultMaxCacheDays);
            options.MaxFileSize             = section.GetValue("MaxFileSize", DefaultMaxFileSize);
            options.CdnBaseUrl              = section.GetValue("CdnBaseUrl", String.Empty).TrimEnd('/').ToLower();
            options.AssetsRequestPath       = section.GetValue("AssetsRequestPath", DefaultAssetsRequestPath);
            options.AssetsPath              = section.GetValue("AssetsPath", DefaultAssetsPath);
            options.AssetsUsersFolder       = section.GetValue("AssetsUsersFolder", DefaultAssetsUsersFolder);
            options.UseTokenizedQueryString = section.GetValue("UseTokenizedQueryString", DefaultUseTokenizedQueryString);

            var contentSecurityPolicy = section.GetValue("ContentSecurityPolicy", DefaultContentSecurityPolicy);

            // Use the same cache control header as ImageSharp does for resized images.
            var cacheControl = "public, must-revalidate, max-age=" + TimeSpan.FromDays(options.MaxBrowserCacheDays).TotalSeconds.ToString();

            options.StaticFileOptions = new StaticFileOptions
            {
                RequestPath           = options.AssetsRequestPath,
                ServeUnknownFileTypes = true,
                OnPrepareResponse     = ctx =>
                {
                    ctx.Context.Response.Headers[HeaderNames.CacheControl]          = cacheControl;
                    ctx.Context.Response.Headers[HeaderNames.ContentSecurityPolicy] = contentSecurityPolicy;
                }
            };
        }
Exemplo n.º 23
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.Configure <MediaBlobStorageOptions>(_configuration.GetSection("OrchardCore.Media.Azure"));

            // Only replace default implementation if options are valid.
            var connectionString = _configuration[$"OrchardCore.Media.Azure:{nameof(MediaBlobStorageOptions.ConnectionString)}"];
            var containerName    = _configuration[$"OrchardCore.Media.Azure:{nameof(MediaBlobStorageOptions.ContainerName)}"];

            if (CheckOptions(connectionString, containerName, _logger))
            {
                // Register a media cache file provider.
                services.AddSingleton <IMediaFileStoreCacheFileProvider>(serviceProvider =>
                {
                    var hostingEnvironment = serviceProvider.GetRequiredService <IWebHostEnvironment>();

                    if (String.IsNullOrWhiteSpace(hostingEnvironment.WebRootPath))
                    {
                        throw new Exception("The wwwroot folder for serving cache media files is missing.");
                    }

                    var mediaOptions  = serviceProvider.GetRequiredService <IOptions <MediaOptions> >().Value;
                    var shellOptions  = serviceProvider.GetRequiredService <IOptions <ShellOptions> >();
                    var shellSettings = serviceProvider.GetRequiredService <ShellSettings>();
                    var logger        = serviceProvider.GetRequiredService <ILogger <DefaultMediaFileStoreCacheFileProvider> >();

                    var mediaCachePath = GetMediaCachePath(hostingEnvironment, DefaultMediaFileStoreCacheFileProvider.AssetsCachePath, shellSettings);

                    if (!Directory.Exists(mediaCachePath))
                    {
                        Directory.CreateDirectory(mediaCachePath);
                    }

                    return(new DefaultMediaFileStoreCacheFileProvider(logger, mediaOptions.AssetsRequestPath, mediaCachePath));
                });

                // Replace the default media file provider with the media cache file provider.
                services.Replace(ServiceDescriptor.Singleton <IMediaFileProvider>(serviceProvider =>
                                                                                  serviceProvider.GetRequiredService <IMediaFileStoreCacheFileProvider>()));

                // Register the media cache file provider as a file store cache provider.
                services.AddSingleton <IMediaFileStoreCache>(serviceProvider =>
                                                             serviceProvider.GetRequiredService <IMediaFileStoreCacheFileProvider>());

                // Replace the default media file store with a blob file store.
                services.Replace(ServiceDescriptor.Singleton <IMediaFileStore>(serviceProvider =>
                {
                    var blobStorageOptions = serviceProvider.GetRequiredService <IOptions <MediaBlobStorageOptions> >().Value;
                    var shellOptions       = serviceProvider.GetRequiredService <IOptions <ShellOptions> >();
                    var shellSettings      = serviceProvider.GetRequiredService <ShellSettings>();
                    var mediaOptions       = serviceProvider.GetRequiredService <IOptions <MediaOptions> >().Value;
                    var clock = serviceProvider.GetRequiredService <IClock>();
                    var contentTypeProvider = serviceProvider.GetRequiredService <IContentTypeProvider>();
                    var fileStore           = new BlobFileStore(blobStorageOptions, clock, contentTypeProvider);

                    var mediaPath = GetMediaPath(shellOptions.Value, shellSettings, mediaOptions.AssetsPath);

                    var mediaUrlBase = "/" + fileStore.Combine(shellSettings.RequestUrlPrefix, mediaOptions.AssetsRequestPath);

                    var originalPathBase = serviceProvider.GetRequiredService <IHttpContextAccessor>()
                                           .HttpContext?.Features.Get <ShellContextFeature>()?.OriginalPathBase ?? null;

                    if (originalPathBase.HasValue)
                    {
                        mediaUrlBase = fileStore.Combine(originalPathBase.Value, mediaUrlBase);
                    }

                    return(new DefaultMediaFileStore(fileStore, mediaUrlBase, mediaOptions.CdnBaseUrl));
                }));
            }
        }
Exemplo n.º 24
0
        public override void ConfigureServices(IServiceCollection services)
        {
            // Book
            services.AddScoped <IDisplayDriver <Book>, BookDisplayDriver>();
            services.AddScoped <IDisplayManager <Book>, DisplayManager <Book> >();
            services.AddScoped <IDataMigration, BookMigrations>();
            services.AddSingleton <IIndexProvider, BookIndexProvider>();

            // Person Part
            services.AddContentPart <PersonPart>();
            services.AddScoped <IDataMigration, PersonMigrations>();
            services.AddScoped <IContentPartDisplayDriver, PersonPartDisplayDriver>();
            services.AddSingleton <IIndexProvider, PersonPartIndexProvider>();

            // Color Field
            services.AddContentField <ColorField>();
            services.AddScoped <IContentFieldDisplayDriver, ColorFieldDisplayDriver>();
            services.AddScoped <IContentPartFieldDefinitionDisplayDriver, ColorFieldSettingsDriver>();
            services.AddScoped <IContentFieldIndexHandler, ColorFieldIndexHandler>();

            // Resources
            services.AddScoped <IResourceManifestProvider, ResourceManifest>();

            // Permissions
            services.AddScoped <IPermissionProvider, PersonPermissions>();

            // Admin Menu
            services.AddScoped <INavigationProvider, PersonsAdminMenu>();

            // Demo Settings
            services.Configure <DemoSettings>(_shellConfiguration.GetSection("Lombiq_TrainingDemo"));
            services.AddTransient <IConfigureOptions <DemoSettings>, DemoSettingsConfiguration>();
            services.AddScoped <IDisplayDriver <ISite>, DemoSettingsDisplayDriver>();
            services.AddScoped <IPermissionProvider, DemoSettingsPermissions>();
            services.AddScoped <INavigationProvider, DemoSettingsAdminMenu>();


            // Filters
            services.Configure <MvcOptions>((options) =>
            {
                options.Filters.Add(typeof(ShapeInjectionFilter));
                options.Filters.Add(typeof(ResourceInjectionFilter));
            });

            // File System
            services.AddSingleton <ICustomFileStore>(serviceProvider =>
            {
                // So our goal here is to have a custom folder in the tenant's own folder. The Media folder is also
                // there but we won't use that. To get tenant-specific data we need to use the ShellOptions and
                // ShellShettings objects.
                var shellOptions  = serviceProvider.GetRequiredService <IOptions <ShellOptions> >().Value;
                var shellSettings = serviceProvider.GetRequiredService <ShellSettings>();

                var tenantFolderPath = PathExtensions.Combine(
                    // This is the absolute path of the "App_Data" folder.
                    shellOptions.ShellsApplicationDataPath,
                    // This is the folder which contains the tenants which is Sites by default.
                    shellOptions.ShellsContainerName,
                    // This is the tenant name. We want our custom folder inside this folder.
                    shellSettings.Name);

                // And finally our full base path.
                var customFolderPath = PathExtensions.Combine(tenantFolderPath, "CustomFiles");

                // Now register our CustomFileStore instance with the path given.
                return(new CustomFileStore(customFolderPath));

                // NEXT STATION: Controllers/FileManagementController and find the CreateFileInCustomFolder method.
            });

            // Caching
            //services.AddScoped<IDateTimeCachingService, DateTimeCachingService>();

            // Background tasks
            services.AddSingleton <IBackgroundTask, DemoBackgroundTask>();
        }
Exemplo n.º 25
0
        public void Configure(string name, DocumentOptions options)
        {
            var sharedConfig = _shellConfiguration
                               .GetSection("OrchardCore_Documents")
                               .Get <DocumentSharedOptions>()
                               ?? new DocumentSharedOptions();

            var namedConfig = _shellConfiguration
                              .GetSection(name)
                              .Get <DocumentNamedOptions>()
                              ?? new DocumentNamedOptions();

            // Only from the named config or default.
            options.CacheKey   = namedConfig.CacheKey ?? name;
            options.CacheIdKey = namedConfig.CacheIdKey ?? "ID_" + name;

            // Only from the shared config or default.
            options.FailoverRetryLatency = sharedConfig.FailoverRetryLatency ?? DefaultFailoverRetryLatency;

            // From the named or shared config or default.
            options.CheckConcurrency = namedConfig.CheckConcurrency ?? sharedConfig.CheckConcurrency ?? true;
            options.CheckConsistency = namedConfig.CheckConsistency ?? sharedConfig.CheckConsistency ?? true;

            options.SynchronizationLatency = namedConfig.SynchronizationLatency
                                             ?? sharedConfig.SynchronizationLatency
                                             ?? TimeSpan.FromSeconds(1);

            options.Serializer = DefaultDocumentSerializer.Instance;

            options.CompressThreshold = namedConfig.CompressThreshold;
            if (options.CompressThreshold == 0)
            {
                options.CompressThreshold = sharedConfig.CompressThreshold;
                if (options.CompressThreshold == 0)
                {
                    options.CompressThreshold = 10_000;
                }
            }

            // Only used by an explicit atomic update.
            options.LockTimeout = namedConfig.LockTimeout;
            if (options.LockTimeout <= 0)
            {
                options.LockTimeout = sharedConfig.LockTimeout;
                if (options.LockTimeout <= 0)
                {
                    options.LockTimeout = 10_000;
                }
            }

            // Only used by an explicit atomic update.
            options.LockExpiration = namedConfig.LockExpiration;
            if (options.LockExpiration <= 0)
            {
                options.LockExpiration = sharedConfig.LockExpiration;
                if (options.LockExpiration <= 0)
                {
                    options.LockExpiration = 10_000;
                }
            }

            // Inherited 'DistributedCacheEntryOptions'.
            options.AbsoluteExpiration = namedConfig.AbsoluteExpiration ?? sharedConfig.AbsoluteExpiration;
            options.AbsoluteExpirationRelativeToNow = namedConfig.AbsoluteExpirationRelativeToNow ?? sharedConfig.AbsoluteExpirationRelativeToNow;
            options.SlidingExpiration = namedConfig.SlidingExpiration ?? sharedConfig.SlidingExpiration;
        }
Exemplo n.º 26
0
        public async Task <ActionResult <object> > Upload(
            string path,
            string contentType,
            ICollection <IFormFile> files)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia))
            {
                return(Unauthorized());
            }

            if (string.IsNullOrEmpty(path))
            {
                path = "";
            }

            var section = _shellConfiguration.GetSection("OrchardCore.Media");

            // var maxUploadSize = section.GetValue("MaxRequestBodySize", 100_000_000);
            var maxFileSize           = section.GetValue("MaxFileSize", 30_000_000);
            var allowedFileExtensions = section.GetValue("AllowedFileExtensions", DefaultAllowedFileExtensions);

            var result = new List <object>();

            // Loop through each file in the request
            foreach (var file in files)
            {
                // TODO: support clipboard

                if (!allowedFileExtensions.Contains(Path.GetExtension(file.FileName), StringComparer.OrdinalIgnoreCase))
                {
                    result.Add(new
                    {
                        name   = file.FileName,
                        size   = file.Length,
                        folder = path,
                        error  = T["This file extension is not allowed: {0}", Path.GetExtension(file.FileName)].ToString()
                    });

                    _logger.LogInformation($"File extension not allowed: '{file.FileName}'");

                    continue;
                }

                if (file.Length > maxFileSize)
                {
                    result.Add(new
                    {
                        name   = file.FileName,
                        size   = file.Length,
                        folder = path,
                        error  = T["The file {0} is too big. The limit is {1}MB", file.FileName, (int)Math.Floor((double)maxFileSize / 1024 / 1024)].ToString()
                    });

                    _logger.LogInformation($"File too big: '{file.FileName}' ({file.Length}B)");

                    continue;
                }

                try
                {
                    var mediaFilePath = _mediaFileStore.Combine(path, file.FileName);

                    using (var stream = file.OpenReadStream())
                    {
                        await _mediaFileStore.CreateFileFromStream(mediaFilePath, stream);
                    }

                    var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath);

                    result.Add(CreateFileResult(mediaFile));
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "An error occured while uploading a media");

                    result.Add(new
                    {
                        name   = file.FileName,
                        size   = file.Length,
                        folder = path,
                        error  = ex.Message
                    });
                }
            }

            return(new { files = result.ToArray() });
        }
Exemplo n.º 27
0
        public void Configure(SqliteOptions options)
        {
            var section = _shellConfiguration.GetSection("OrchardCore_Data_Sqlite");

            options.UseConnectionPooling = section.GetValue(nameof(options.UseConnectionPooling), DefaultUseConnectionPooling);
        }
Exemplo n.º 28
0
 public override void ConfigureServices(IServiceCollection services)
 {
     services.AddHealthChecks();
     services.Configure <HealthChecksOptions>(_shellConfiguration.GetSection("OrchardCore_HealthChecks"));
 }