Exemplo n.º 1
0
        /// <summary>
        /// Adds capability to start a download when following some link to the
        /// configuration.
        /// </summary>
        /// <param name="configuration">The configuration to extend.</param>
        /// <param name="download">
        /// The callback to invoke when a download should be started. Returns true
        /// to signal an interest in downloading the response, otherwise false.
        /// </param>
        /// <returns>The new configuration.</returns>
        public static IConfiguration WithDownload(this IConfiguration configuration, Func <MimeType, IResponse, Boolean> download)
        {
            var oldFactory = configuration.Services.OfType <IDocumentFactory>().FirstOrDefault();
            var newFactory = new DownloadFactory(oldFactory, download);

            return(configuration.WithOnly <IDocumentFactory>(newFactory));
        }
 public HttpResponseMessage DownloadFile([FromBody] DownloadResponse request)
 {
     try
     {
         DownloadFactory     _downloadfactory = new DownloadFactory();
         var                 fStream          = _downloadfactory.DownloadFile(request.file);
         HttpResponseMessage response;
         if (fStream == null)
         {
             response = Request.CreateResponse(HttpStatusCode.Gone);
             return(response);
         }
         else
         {
             response = new HttpResponseMessage
             {
                 StatusCode = HttpStatusCode.OK,
                 Content    = new StreamContent(fStream)
             };
             //set content header of reponse as file attached in reponse
             response.Content.Headers.ContentDisposition =
                 new ContentDispositionHeaderValue("attachment")
             {
                 FileName = Path.GetFileName(fStream.Name)
             };
             //set the content header content type as application/octet-stream as it returning file as reponse
             response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
             return(response);
         }
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            // indicates if firstrun action is to be performed
            Boolean firstRunner = false;
            // set specified configuration file
            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();

            if (args.Length > 0)
            {
                configFileMap.ExeConfigFilename = args[0]; // full path to the config file
            }
            if (args.Length > 1)
            {
                firstRunner = Boolean.Parse(args[1]); // firstrun action, if not specified -> False
            }
            // Get the mapped configuration file
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            //now on use config object

            AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");

            //// read custom configuration for download OIS Settings
            OISServiceConfigurationSection oisSection = config.GetSection("oisdata") as OISServiceConfigurationSection;

            if (oisSection != null)
            {
                OISServiceConfigurationElementCollection collection = oisSection.CustomConfigurations;

                foreach (OISServiceConfigurationElement element in collection)
                {
                    IDownload id = DownloadFactory.createDownloader(element.Type);
                    id.setImportSettings(element);
                    Console.WriteLine(config.ConnectionStrings.ConnectionStrings["database"].ConnectionString);
                    id.setExportSettings(new SqlConnection(config.ConnectionStrings.ConnectionStrings["database"].ConnectionString));
                    id.startDownload(firstRunner);
                }
            }

            //// read custom configuration for scraping Web Settings
            ScrapingServiceConfigurationSection scrapingSection = config.GetSection("scraping") as ScrapingServiceConfigurationSection;

            if (scrapingSection != null)
            {
                ScrapingServiceConfigurationElementCollection collection = scrapingSection.CustomConfigurations;

                foreach (ScrapingServiceConfigurationElement element in collection)
                {
                    IDownload id = DownloadFactory.createDownloader(element.Type);
                    id.setImportSettings(element);
                    Console.WriteLine(config.ConnectionStrings.ConnectionStrings["database"].ConnectionString);
                    id.setExportSettings(new SqlConnection(config.ConnectionStrings.ConnectionStrings["database"].ConnectionString));
                    id.startDownload(firstRunner);
                }
            }
        }
        public async Task <HttpResponseMessage> GetDownloadData()
        {
            DownloadFactory _downloadFactory = new DownloadFactory();
            var             downloadResponse = await _downloadFactory.GetData().ConfigureAwait(false);

            HttpResponseMessage response;

            response = Request.CreateResponse(HttpStatusCode.OK, downloadResponse);
            return(response);
        }
Exemplo n.º 5
0
        public void TestCreateManagerWithPreferences(JObject data)
        {
            config.Merge(data);
            var manager = DownloadFactory.CreateManager(IONull.That, config);

            var field       = typeof(DownloadManager).GetField("preferences", BindingFlags.Instance | BindingFlags.NonPublic);
            var preferences = ((IEnumerable <(string Pattern, InstallationSource Prefer)>)field.GetValue(manager)).ToArray();

            Assert.IsTrue(Array.Exists(preferences, (item) => item.Pattern == "foo/bar" && item.Prefer == InstallationSource.Source));
            Assert.IsTrue(Array.Exists(preferences, (item) => item.Pattern == "foo/*" && item.Prefer == InstallationSource.Dist));
        }
Exemplo n.º 6
0
        public void TestCreateManager(JObject data)
        {
            config.Merge(data);
            var manager = DownloadFactory.CreateManager(IONull.That, config);

            var field = typeof(DownloadManager).GetField("preferSource", BindingFlags.Instance | BindingFlags.NonPublic);

            Assert.AreEqual(true, field.GetValue(manager));

            field = typeof(DownloadManager).GetField("preferDist", BindingFlags.Instance | BindingFlags.NonPublic);
            Assert.AreEqual(false, field.GetValue(manager));
        }
        public override async Task PerformAsync()
        {
            if (!Uri.TryCreate(_address, UriKind.Absolute, out var uri))
            {
                throw new Exception("URL not valid");
            }

            var downloader = DownloadFactory.GetDownloader(uri, _configs.SaveDirectoryPath);

            if (downloader is null)
            {
                throw new Exception("Domain not supported");
            }

            await downloader.DownloadAsync();
        }
Exemplo n.º 8
0
        private void Loading_Load(object sender, EventArgs e)
        {
            if (InstallPathExists() && !IsNewVersionAvailable())
            {
                ExecuteApplication();
            }
            else if (IsNewVersionAvailable())
            {
                NotifyNewVersionIsAvailable();
            }

            statusLabelMessage.Text    = "";
            fileDataReceivedLabel.Text = "";

            var fileProcess       = new FileProcess();
            var botDirectories    = new CreateBotDirectoriesCommand();
            var downloadFactory   = new DownloadFactory(_webClient, fileProcess);
            var downloadService   = new DownloadService(downloadFactory);
            var extractFactory    = new ExtractFactory();
            var extractService    = new ExtractService(extractFactory);
            var removeFactory     = new RemoveFactory();
            var removeService     = new RemoveService(removeFactory);
            var tesseractDownload = downloadService.Create(FileType.Tesseract, _binDirectory);
            var clientDownload    = downloadService.Create(FileType.Client, _installPath);
            var tesseractExtract  = extractService.Create(FileType.Tesseract, _binDirectory);
            var clientExtract     = extractService.Create(FileType.Client, _installPath);
            var tesseractRemove   = removeService.Create(FileType.Tesseract, _binDirectory);
            var clientRemove      = removeService.Create(FileType.Client, _installPath);

            _commandList.Add(botDirectories);
            _commandList.Add(tesseractDownload);
            _commandList.Add(clientDownload);
            _commandList.Add(tesseractExtract);
            _commandList.Add(clientExtract);
            _commandList.Add(tesseractRemove);
            _commandList.Add(clientRemove);

            Run();
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a <see cref="Bucket"/> object from specified <paramref name="cwd"/>.
        /// </summary>
        /// <remarks>If no <paramref name="cwd"/> is given, the current environment path will be used.</remarks>
        /// <param name="io">The input/output instance.</param>
        /// <param name="localBucket">either a configuration filename to read from, if null it will read from the default filename.</param>
        /// <param name="disablePlugins">Whether plugins should not be loaded.</param>
        /// <param name="cwd">Current working directory.</param>
        /// <param name="fullLoad">Whether to initialize everything or only main project stuff (used when loading the global bucket and auth).</param>
        /// <exception cref="InvalidArgumentException">If local config file not exists.</exception>
        public Bucket CreateBucket(IIO io, object localBucket = null, bool disablePlugins = false, string cwd = null, bool fullLoad = true)
        {
            cwd = cwd ?? Environment.CurrentDirectory;
            var    localFileSystem = new FileSystemLocal(cwd);
            var    config          = CreateConfig(io, cwd);
            string bucketFile      = null;

            if (localBucket == null || localBucket is string)
            {
                bucketFile = localBucket?.ToString();
                bucketFile = string.IsNullOrEmpty(bucketFile) ? GetBucketFile() : bucketFile;

                var localBucketFile = new JsonFile(bucketFile, localFileSystem, io);
                if (!localBucketFile.Exists())
                {
                    string message;
                    if (bucketFile == "./bucket.json" || bucketFile == "bucket.json")
                    {
                        message = $"Bucket could not find a bucket.json file in {cwd}";
                    }
                    else
                    {
                        message = $"Bucket could not find the config file {bucketFile} in {cwd}";
                    }

                    var instructions = "To initialize a project, please create a bucket.json";
                    throw new InvalidArgumentException(message + Environment.NewLine + instructions);
                }

                localBucketFile.Validate(false);

                io.WriteError($"Loading bucket file: {localBucketFile.GetPath()}", true, Verbosities.Debug);
                config.Merge(localBucketFile.Read());
                config.SetSourceBucket(new JsonConfigSource(localBucketFile));

                var localAuthFile = new JsonFile("./auth.json", localFileSystem, io);
                if (localAuthFile.Exists())
                {
                    io.WriteError($"Loading bucket file: {localAuthFile.GetPath()}", true, Verbosities.Debug);
                    config.Merge(new JObject
                    {
                        ["config"] = localAuthFile.Read(),
                    });
                    config.SetSourceAuth(new JsonConfigSource(localAuthFile, true));
                }

                localBucket = localBucketFile.Read <ConfigBucket>();
            }
            else if (localBucket is ConfigBucket configBucket)
            {
                config.Merge(JObject.FromObject(configBucket));
            }
            else
            {
                throw new UnexpectedException($"Params \"{localBucket}\" only allow {nameof(ConfigBucket)} type or string path.");
            }

            if (fullLoad)
            {
                new LoaderIOConfiguration(io).Load(config);
            }

            // initialize bucket.
            var bucket = new Bucket();

            bucket.SetConfig(config);

            var transport = CreateTransport(io, config);

            // initialize event dispatcher.
            var dispatcher = new BEventDispatcher(bucket, io);

            bucket.SetEventDispatcher(dispatcher);

            // initialize repository manager
            var repositoryManager = RepositoryFactory.CreateManager(io, config, dispatcher);

            bucket.SetRepositoryManager(repositoryManager);

            InitializeLocalInstalledRepository(io, repositoryManager, config.Get(Settings.VendorDir));

            // load root package
            var versionParser = new BVersionParser();
            var loader        = new LoaderPackageRoot(repositoryManager, config, io, versionParser);
            var package       = loader.Load <IPackageRoot>((ConfigBucket)localBucket);

            bucket.SetPackage(package);

            // create installation manager
            var installationManager = CreateInstallationManager();

            bucket.SetInstallationManager(installationManager);

            if (fullLoad)
            {
                var downloadManager = DownloadFactory.CreateManager(io, config, transport, dispatcher);
                bucket.SetDownloadManager(downloadManager);

                // todo: initialize archive manager
            }

            // must happen after downloadManager is created since they read it out of bucket.
            InitializeDefaultInstallers(installationManager, bucket, io);

            if (fullLoad)
            {
                Bucket globalBucket = null;
                if (BaseFileSystem.GetNormalizePath(cwd) != BaseFileSystem.GetNormalizePath(config.Get(Settings.Home)))
                {
                    globalBucket = CreateGlobalBucket(io, config, disablePlugins, false);
                }

                var pluginManager = new PluginManager(io, bucket, globalBucket, disablePlugins);
                bucket.SetPluginManager(pluginManager);
                pluginManager.LoadInstalledPlugins();
            }

            // init locker if locker exists.
            if (fullLoad && !string.IsNullOrEmpty(bucketFile))
            {
                var lockFile = Path.GetExtension(bucketFile) == ".json" ?
                               bucketFile.Substring(0, bucketFile.Length - 5) + ".lock" :
                               bucketFile + ".lock";
                var locker = new Locker(
                    io,
                    new JsonFile(lockFile, localFileSystem, io), installationManager, localFileSystem.Read(bucketFile).ToText());
                bucket.SetLocker(locker);
            }

            if (fullLoad)
            {
                // Raises an event only when it is fully loaded.
                dispatcher.Dispatch(PluginEvents.Init, this);
            }

            if (fullLoad)
            {
                // once everything is initialized we can purge packages from
                // local repos if they have been deleted on the filesystem.
                PurgePackages(repositoryManager.GetLocalInstalledRepository(), installationManager);
            }

            return(bucket);
        }
Exemplo n.º 10
0
 public DownloadService(DownloadFactory factory)
 {
     _downloadFactory = factory;
 }