Exemplo n.º 1
0
        public object ExecuteTool(string uid, [FromBody] IDictionary parameters = null)
        {
            if (uid == null)
            {
                throw new ArgumentNullException(nameof(uid));
            }

            if (parameters == null)
            {
                parameters = new PythonDictionary();
            }

            Package package;

            try
            {
                package = _packageManagerService.LoadPackage(PackageUid.Parse(uid));
            }
            catch (WirehomePackageNotFoundException)
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(null);
            }

            try
            {
                var scriptHost = _pythonScriptHostFactoryService.CreateScriptHost(null);
                scriptHost.Compile(package.Script);
                return(scriptHost.InvokeFunction("main", parameters));
            }
            catch (Exception exception)
            {
                return(new ExceptionPythonModel(exception).ConvertToPythonDictionary());
            }
        }
        public async Task ForkPackage(string uid, string forkUid)
        {
            if (uid == null)
            {
                throw new ArgumentNullException(nameof(uid));
            }
            if (uid == null)
            {
                throw new ArgumentNullException(nameof(forkUid));
            }

            var packageUid = PackageUid.Parse(uid);

            if (string.IsNullOrEmpty(packageUid.Version))
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            var packageForkUid = PackageUid.Parse(forkUid);

            if (string.IsNullOrEmpty(packageForkUid.Version))
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            await _packageManagerService.ForkPackageAsync(packageUid, packageForkUid);
        }
Exemplo n.º 3
0
        ServiceInstance CreateServiceInstance(string id, ServiceConfiguration configuration)
        {
            var packageUid = new PackageUid(id, configuration.Version);
            var package    = _repositoryService.LoadPackage(packageUid);

            var scriptHost = _pythonScriptHostFactoryService.CreateScriptHost();

            scriptHost.Compile(package.Script);

            var context = new PythonDictionary
            {
                ["service_id"]      = id,
                ["service_version"] = configuration.Version,
                ["service_uid"]     = new PackageUid(id, configuration.Version).ToString()
            };

            scriptHost.AddToWirehomeWrapper("context", context);

            var serviceInstance = new ServiceInstance(id, configuration, scriptHost);

            if (configuration.Variables != null)
            {
                foreach (var variable in configuration.Variables)
                {
                    serviceInstance.SetVariable(variable.Key, variable.Value);
                }
            }

            return(serviceInstance);
        }
        public IFileInfo GetFileInfo(string subpath)
        {
            if (subpath == null)
            {
                throw new ArgumentNullException(nameof(subpath));
            }

            var fullPath = subpath.Trim(Path.PathSeparator, Path.AltDirectorySeparatorChar);

            if (_defaultFileNames.Contains(fullPath))
            {
                subpath = "index.html";
            }

            var packageUid      = _globalVariablesService.GetValue(_packageUidGlobalVariableUid) as string;
            var packageRootPath = _packageManagerService.GetPackageRootPath(PackageUid.Parse(packageUid));

            fullPath = Path.Combine(packageRootPath, fullPath);

            if (!File.Exists(fullPath))
            {
                return(new NotFoundFileInfo(subpath));
            }

            return(new PhysicalFileInfo(new FileInfo(fullPath)));
        }
        public void DeletePackage(string uid)
        {
            if (uid == null)
            {
                throw new ArgumentNullException(nameof(uid));
            }

            _packageManagerService.DeletePackage(PackageUid.Parse(uid));
        }
    public PackageMetaData GetPackageMetaData(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        return(LoadPackage(uid).MetaData);
    }
    public string GetPackageDescription(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        return(LoadPackage(uid).Description);
    }
    public string GetPackageReleaseNotes(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        return(LoadPackage(uid).ReleaseNotes);
    }
Exemplo n.º 9
0
    public string get_file_uri(string uid, string filename)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        var packageUid = PackageUid.Parse(uid);

        return($"/packages/{packageUid.Id}/{packageUid.Version}/{filename}");
    }
Exemplo n.º 10
0
    public void download_package(string uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        var packageUid = PackageUid.Parse(uid);

        _packageManagerService.DownloadPackageAsync(packageUid).GetAwaiter().GetResult();
    }
    public bool PackageExists(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        var path = GetPackageRootPath(uid);

        return(Directory.Exists(path));
    }
Exemplo n.º 12
0
    public async Task PostSetup(string appPackageUid = "[email protected]", string configuratorPackageUid = "[email protected]")
    {
        if (!string.IsNullOrWhiteSpace(appPackageUid?.Trim()))
        {
            await _packageManagerService.DownloadPackageAsync(PackageUid.Parse(appPackageUid)).ConfigureAwait(false);
        }

        if (!string.IsNullOrWhiteSpace(configuratorPackageUid?.Trim()))
        {
            await _packageManagerService.DownloadPackageAsync(PackageUid.Parse(configuratorPackageUid)).ConfigureAwait(false);
        }
    }
        public async Task DownloadAsync(PackageUid packageUid, string targetPath)
        {
            if (packageUid == null)
            {
                throw new ArgumentNullException(nameof(packageUid));
            }
            if (targetPath == null)
            {
                throw new ArgumentNullException(nameof(targetPath));
            }

            var tempPath = targetPath + "_downloading";

            if (Directory.Exists(tempPath))
            {
                Directory.Delete(tempPath, true);
            }

            Directory.CreateDirectory(tempPath);

            using (var httpClient = new HttpClient())
            {
                // The User-Agent is mandatory for using the GitHub API.
                // https://developer.github.com/v3/?#user-agent-required
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Wirehome.Core");

                var uri = $"{_settings.OfficialRepositoryBaseUri}/{packageUid.Id}/{packageUid.Version}";
                _logger.LogInformation($"Downloading file list from '{uri}'.");

                var fileListContent = await httpClient.GetStringAsync(uri).ConfigureAwait(false);

                var fileList = JsonConvert.DeserializeObject <List <GitHubFileEntry> >(fileListContent);

                foreach (var fileEntry in fileList)
                {
                    uri = fileEntry.DownloadUrl;
                    _logger.LogInformation($"Downloading file '{uri}' (Size = {fileEntry.Size} bytes).");

                    var fileContent = await httpClient.GetByteArrayAsync(uri).ConfigureAwait(false);

                    var filename = Path.Combine(tempPath, fileEntry.Name);

                    await File.WriteAllBytesAsync(filename, fileContent).ConfigureAwait(false);
                }

                if (Directory.Exists(targetPath))
                {
                    Directory.Delete(targetPath, true);
                }

                Directory.Move(tempPath, targetPath);
            }
        }
    public Task DownloadPackageAsync(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        _storageService.SafeReadSerializedValue(out PackageManagerServiceOptions options, DefaultDirectoryNames.Configuration, PackageManagerServiceOptions.Filename);

        var downloader = new GitHubRepositoryPackageDownloader(options, _logger);

        return(downloader.DownloadAsync(uid, GetPackageRootPath(uid)));
    }
    string GetLatestVersionPath(string id)
    {
        var packageRootPath = Path.Combine(_rootPath, id);

        if (!Directory.Exists(packageRootPath))
        {
            throw new WirehomePackageNotFoundException(PackageUid.Parse(id));
        }

        var versions = Directory.GetDirectories(packageRootPath).OrderByDescending(d => d.ToLowerInvariant());

        return(versions.First());
    }
Exemplo n.º 16
0
        public async Task DownloadPackage(string uid)
        {
            if (uid == null)
            {
                throw new ArgumentNullException(nameof(uid));
            }

            var packageUid = PackageUid.Parse(uid);

            if (string.IsNullOrEmpty(packageUid.Version))
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            await _packageManagerService.DownloadPackageAsync(packageUid).ConfigureAwait(false);
        }
    public Package LoadPackage(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        if (string.IsNullOrEmpty(uid.Id))
        {
            throw new ArgumentException("The ID of the package UID is not set.");
        }

        var path   = GetPackageRootPath(uid);
        var source = LoadPackage(uid, path);

        return(source);
    }
    public void DeletePackage(PackageUid uid)
    {
        if (uid == null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        var rootPath = GetPackageRootPath(uid);

        if (!Directory.Exists(rootPath))
        {
            return;
        }

        Directory.Delete(rootPath, true);
        _logger.Log(LogLevel.Information, $"Deleted package '{uid}'.");
    }
        public string GetReleaseNotes(string uid)
        {
            if (uid == null)
            {
                throw new ArgumentNullException(nameof(uid));
            }

            var packageUid = PackageUid.Parse(uid);

            if (string.IsNullOrEmpty(packageUid.Version))
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(null);
            }

            return(_packageManagerService.GetReleaseNotes(packageUid));
        }
Exemplo n.º 20
0
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            if (subpath == null)
            {
                throw new ArgumentNullException(nameof(subpath));
            }

            var packageUid      = _globalVariablesService.GetValue(_packageUidGlobalVariableUid) as string;
            var packageRootPath = _packageManagerService.GetPackageRootPath(PackageUid.Parse(packageUid));

            var fullPath = Path.Combine(packageRootPath, subpath.Trim(Path.PathSeparator, Path.AltDirectorySeparatorChar));

            if (!Directory.Exists(fullPath))
            {
                return(new NotFoundDirectoryContents());
            }

            return(new PhysicalDirectoryContents(fullPath));
        }
Exemplo n.º 21
0
    public async Task DownloadAsync(PackageUid packageUid, string targetPath)
    {
        if (packageUid == null)
        {
            throw new ArgumentNullException(nameof(packageUid));
        }

        if (targetPath == null)
        {
            throw new ArgumentNullException(nameof(targetPath));
        }

        var tempPath = targetPath + "_downloading";

        if (Directory.Exists(tempPath))
        {
            Directory.Delete(tempPath, true);
        }

        Directory.CreateDirectory(tempPath);

        using (var httpClient = new HttpClient())
        {
            // The User-Agent is mandatory for using the GitHub API.
            // https://developer.github.com/v3/?#user-agent-required
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Wirehome.Core");

            var rootItem = new GitHubItem
            {
                Type        = "dir",
                DownloadUrl = $"{_options.OfficialRepositoryBaseUri}/{packageUid.Id}/{packageUid.Version}"
            };

            await DownloadDirectoryAsync(httpClient, rootItem, tempPath).ConfigureAwait(false);
        }

        if (Directory.Exists(targetPath))
        {
            Directory.Delete(targetPath, true);
        }

        Directory.Move(tempPath, targetPath);
    }
Exemplo n.º 22
0
        public async Task PostSetup(
            string appPackageUid          = "[email protected]",
            string configuratorPackageUid = "[email protected]",
            bool fixStartupScripts        = true)
        {
            if (!string.IsNullOrEmpty(appPackageUid.Trim()))
            {
                await _packageManagerService.DownloadPackageAsync(PackageUid.Parse(appPackageUid));
            }

            if (!string.IsNullOrEmpty(configuratorPackageUid.Trim()))
            {
                await _packageManagerService.DownloadPackageAsync(PackageUid.Parse(configuratorPackageUid));
            }

            if (fixStartupScripts)
            {
                FixStartupScripts();
            }
        }
    public string GetPackageRootPath(PackageUid uid)
    {
        if (uid is null)
        {
            throw new ArgumentNullException(nameof(uid));
        }

        var path = _rootPath;

        if (string.IsNullOrEmpty(uid.Version))
        {
            path = GetLatestVersionPath(uid.Id);
        }
        else
        {
            path = Path.Combine(path, uid.Id, uid.Version);
        }

        return(path);
    }
Exemplo n.º 24
0
        private ServiceInstance CreateServiceInstance(string id, ServiceConfiguration configuration)
        {
            var packageUid = new PackageUid(id, configuration.Version);
            var package    = _repositoryService.LoadPackage(packageUid);

            var scriptHost = _pythonScriptHostFactoryService.CreateScriptHost(_logger);

            scriptHost.Compile(package.Script);

            var serviceInstance = new ServiceInstance(id, configuration, scriptHost);

            if (configuration.Variables != null)
            {
                foreach (var variable in configuration.Variables)
                {
                    serviceInstance.SetVariable(variable.Key, variable.Value);
                }
            }

            return(serviceInstance);
        }
    public Task ForkPackageAsync(PackageUid packageUid, PackageUid packageForkUid)
    {
        if (packageUid == null)
        {
            throw new ArgumentNullException(nameof(packageUid));
        }

        if (packageForkUid == null)
        {
            throw new ArgumentNullException(nameof(packageForkUid));
        }

        if (!PackageExists(packageUid))
        {
            throw new WirehomePackageNotFoundException(packageUid);
        }

        if (PackageExists(packageForkUid))
        {
            throw new InvalidOperationException($"Package '{packageForkUid}' already exists.");
        }

        var sourcePath      = GetPackageRootPath(packageUid);
        var destinationPath = GetPackageRootPath(packageForkUid);

        Directory.CreateDirectory(destinationPath);

        foreach (var directory in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
        {
            Directory.CreateDirectory(directory.Replace(sourcePath, destinationPath, StringComparison.Ordinal));
        }

        foreach (var file in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
        {
            File.Copy(file, file.Replace(sourcePath, destinationPath, StringComparison.Ordinal), true);
        }

        return(Task.CompletedTask);
    }
    static Package LoadPackage(PackageUid uid, string path)
    {
        if (!Directory.Exists(path))
        {
            throw new WirehomePackageNotFoundException(uid);
        }

        var source = new Package();

        var metaFile = Path.Combine(path, "meta.json");

        if (!File.Exists(metaFile))
        {
            throw new WirehomePackageException($"Package directory '{path}' contains no 'meta.json'.");
        }

        try
        {
            var metaData = File.ReadAllText(metaFile, Encoding.UTF8);
            source.MetaData = JsonConvert.DeserializeObject <PackageMetaData>(metaData);
        }
        catch (Exception exception)
        {
            throw new WirehomePackageException("Unable to parse 'meta.json'.", exception);
        }

        source.Uid = new PackageUid
        {
            Id      = Directory.GetParent(path).Name,
            Version = new DirectoryInfo(path).Name
        };

        source.Description  = ReadFileContent(path, "description.md");
        source.ReleaseNotes = ReadFileContent(path, "releaseNotes.md");
        source.Script       = ReadFileContent(path, "script.py");

        return(source);
    }
 public WirehomePackageNotFoundException(PackageUid uid)
     : base($"Package '{uid}' not found.", null)
 {
 }
Exemplo n.º 28
0
 public void DeletePackage(string uid)
 {
     _packageManagerService.DeletePackage(PackageUid.Parse(uid));
 }