Пример #1
0
        public override async Task <IActionResult> Update([FromBody] ConfigurationFile model, CancellationToken cancellationToken)
        {
            if (ForbidDueToModeConflicts())
            {
                return(Forbid());
            }

            var config = instanceManager.GetInstance(Instance).Configuration;

            try
            {
                var newFile = await config.Write(model.Path, AuthenticationContext.SystemIdentity, model.Content, model.LastReadHash, cancellationToken).ConfigureAwait(false);

                if (newFile == null)
                {
                    return(Conflict());
                }

                newFile.Content = null;

                return(model.LastReadHash == null ? (IActionResult)StatusCode((int)HttpStatusCode.Created, newFile) : Json(newFile));
            }
            catch (NotImplementedException)
            {
                return(StatusCode((int)HttpStatusCode.NotImplemented));
            }
        }
Пример #2
0
        public override async Task <IActionResult> Read(CancellationToken cancellationToken)
        {
            var instance           = instanceManager.GetInstance(Instance);
            var dreamMakerSettings = await DatabaseContext.DreamMakerSettings.Where(x => x.InstanceId == Instance.Id).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);

            return(Json(dreamMakerSettings.ToApi()));
        }
        public override async Task <IActionResult> Create([FromBody] DreamDaemon model, CancellationToken cancellationToken)
        {
            //alias for launching DD
            var instance = instanceManager.GetInstance(Instance);

            if (instance.Watchdog.Running)
            {
                return(StatusCode((int)HttpStatusCode.Gone));
            }

            var job = new Models.Job
            {
                Description      = "Launch DreamDaemon",
                CancelRight      = (ulong)DreamDaemonRights.Shutdown,
                CancelRightsType = RightsType.DreamDaemon,
                Instance         = Instance,
                StartedBy        = AuthenticationContext.User
            };
            await jobManager.RegisterOperation(job,
                                               async (paramJob, serviceProvider, progressHandler, innerCt) =>
            {
                var result = await instance.Watchdog.Launch(innerCt).ConfigureAwait(false);
                if (result == null)
                {
                    throw new InvalidOperationException("Watchdog already running!");
                }
            },
                                               cancellationToken).ConfigureAwait(false);

            return(Accepted(job.ToApi()));
        }
        public async Task <IActionResult> Update([FromBody] ConfigurationFile model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (ForbidDueToModeConflicts(model.Path, out var systemIdentity))
            {
                return(Forbid());
            }

            var config = instanceManager.GetInstance(Instance).Configuration;

            try
            {
                var newFile = await config.Write(model.Path, systemIdentity, model.Content, model.LastReadHash, cancellationToken).ConfigureAwait(false);

                if (newFile == null)
                {
                    return(Conflict(new ErrorMessage
                    {
                        Message = "This file has been updated since you last viewed it!"
                    }));
                }

                newFile.Content = null;

                return(model.LastReadHash == null ? (IActionResult)StatusCode((int)HttpStatusCode.Created, newFile) : Json(newFile));
            }
            catch (IOException e)
            {
                Logger.LogInformation("IOException while updating file {0}: {1}", model.Path, e);
                return(Conflict(new ErrorMessage
                {
                    Message = e.Message
                }));
            }
            catch (NotImplementedException)
            {
                return(StatusCode((int)HttpStatusCode.NotImplemented));
            }
        }
Пример #5
0
        public override async Task <IActionResult> Read(CancellationToken cancellationToken)
        {
            var instance    = instanceManager.GetInstance(Instance);
            var projectName = await DatabaseContext.DreamMakerSettings.Where(x => x.InstanceId == Instance.Id).Select(x => x.ProjectName).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);

            return(Json(new Api.Models.DreamMaker
            {
                ProjectName = projectName,
                Status = instance.DreamMaker.Status
            }));
        }
        public async Task <IActionResult> Create(CancellationToken cancellationToken)
        {
            // alias for launching DD
            var instance = instanceManager.GetInstance(Instance);

            if (instance.Watchdog.Running)
            {
                return(StatusCode((int)HttpStatusCode.Gone));
            }

            var job = new Models.Job
            {
                Description      = "Launch DreamDaemon",
                CancelRight      = (ulong)DreamDaemonRights.Shutdown,
                CancelRightsType = RightsType.DreamDaemon,
                Instance         = Instance,
                StartedBy        = AuthenticationContext.User
            };
            await jobManager.RegisterOperation(job, (paramJob, databaseContext, progressHandler, innerCt) => instance.Watchdog.Launch(innerCt), cancellationToken).ConfigureAwait(false);

            return(Accepted(job.ToApi()));
        }
        public async Task <IActionResult> Create([FromBody] Api.Models.ChatBot model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (String.IsNullOrWhiteSpace(model.Name))
            {
                return(BadRequest(new ErrorMessage {
                    Message = "name cannot be null or whitespace!"
                }));
            }

            if (String.IsNullOrWhiteSpace(model.ConnectionString))
            {
                return(BadRequest(new ErrorMessage {
                    Message = "connection_string cannot be null or whitespace!"
                }));
            }

            if (!model.Provider.HasValue)
            {
                return(BadRequest(new ErrorMessage {
                    Message = "provider cannot be null!"
                }));
            }

            switch (model.Provider)
            {
            case ChatProvider.Discord:
            case ChatProvider.Irc:
                break;

            default:
                return(BadRequest(new ErrorMessage {
                    Message = "Invalid provider!"
                }));
            }

            if (model.ReconnectionInterval == 0)
            {
                return(BadRequest(new ErrorMessage {
                    Message = "ReconnectionInterval must not be zero!"
                }));
            }

            if (!model.ValidateProviderChannelTypes())
            {
                return(BadRequest(new ErrorMessage {
                    Message = "One or more of channels aren't formatted correctly for the given provider!"
                }));
            }

            model.Enabled = model.Enabled ?? false;
            model.ReconnectionInterval = model.ReconnectionInterval ?? 1;

            // try to update das db first
            var dbModel = new Models.ChatBot
            {
                Name                 = model.Name,
                ConnectionString     = model.ConnectionString,
                Enabled              = model.Enabled,
                Channels             = model.Channels?.Select(x => ConvertApiChatChannel(x)).ToList() ?? new List <Models.ChatChannel>(),    // important that this isn't null
                InstanceId           = Instance.Id,
                Provider             = model.Provider,
                ReconnectionInterval = model.ReconnectionInterval
            };

            DatabaseContext.ChatBots.Add(dbModel);

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            try
            {
                try
                {
                    // try to create it
                    var instance = instanceManager.GetInstance(Instance);
                    await instance.Chat.ChangeSettings(dbModel, cancellationToken).ConfigureAwait(false);

                    if (dbModel.Channels.Count > 0)
                    {
                        await instance.Chat.ChangeChannels(dbModel.Id, dbModel.Channels, cancellationToken).ConfigureAwait(false);
                    }
                }
                catch
                {
                    // undo the add
                    DatabaseContext.ChatBots.Remove(dbModel);
                    await DatabaseContext.Save(default).ConfigureAwait(false);
Пример #8
0
        public async Task <IActionResult> Create([FromBody] Repository model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (model.Origin == null)
            {
                return(BadRequest(new ErrorMessage {
                    Message = "Missing repo origin!"
                }));
            }

            if (model.AccessUser == null ^ model.AccessToken == null)
            {
                return(BadRequest(new ErrorMessage {
                    Message = "Either both accessToken and accessUser must be present or neither!"
                }));
            }

            var currentModel = await DatabaseContext.RepositorySettings.Where(x => x.InstanceId == Instance.Id).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);

            if (currentModel == default)
            {
                return(StatusCode((int)HttpStatusCode.Gone));
            }

            // normalize github urls
            const string BadGitHubUrl = "://www.github.com/";
            var          uiOrigin     = model.Origin.ToUpperInvariant();
            var          uiBad        = BadGitHubUrl.ToUpperInvariant();
            var          uiGitHub     = Components.Repository.Repository.GitHubUrl.ToUpperInvariant();

            if (uiOrigin.Contains(uiBad, StringComparison.Ordinal))
            {
                model.Origin = uiOrigin.Replace(uiBad, uiGitHub, StringComparison.Ordinal);
            }

            currentModel.AccessToken = model.AccessToken;
            currentModel.AccessUser  = model.AccessUser;            // intentionally only these fields, user not allowed to change anything else atm
            var cloneBranch = model.Reference;
            var origin      = model.Origin;

            var repoManager = instanceManager.GetInstance(Instance).RepositoryManager;

            if (repoManager.CloneInProgress)
            {
                return(Conflict(new ErrorMessage
                {
                    Message = "A clone operation is in progress!"
                }));
            }

            if (repoManager.InUse)
            {
                return(Conflict(new ErrorMessage
                {
                    Message = "The repo is busy!"
                }));
            }

            using (var repo = await repoManager.LoadRepository(cancellationToken).ConfigureAwait(false))
            {
                // clone conflict
                if (repo != null)
                {
                    return(Conflict(new ErrorMessage
                    {
                        Message = "The repository already exists!"
                    }));
                }

                var job = new Models.Job
                {
                    Description      = String.Format(CultureInfo.InvariantCulture, "Clone branch {1} of repository {0}", origin, cloneBranch ?? "master"),
                    StartedBy        = AuthenticationContext.User,
                    CancelRightsType = RightsType.Repository,
                    CancelRight      = (ulong)RepositoryRights.CancelClone,
                    Instance         = Instance
                };
                var api = currentModel.ToApi();
                await jobManager.RegisterOperation(job, async (paramJob, databaseContext, progressReporter, ct) =>
                {
                    using (var repos = await repoManager.CloneRepository(new Uri(origin), cloneBranch, currentModel.AccessUser, currentModel.AccessToken, progressReporter, ct).ConfigureAwait(false))
                    {
                        if (repos == null)
                        {
                            throw new JobException("Filesystem conflict while cloning repository!");
                        }
                        var instance = new Models.Instance
                        {
                            Id = Instance.Id
                        };
                        databaseContext.Instances.Attach(instance);
                        if (await PopulateApi(api, repos, databaseContext, instance, ct).ConfigureAwait(false))
                        {
                            await databaseContext.Save(ct).ConfigureAwait(false);
                        }
                    }
                }, cancellationToken).ConfigureAwait(false);

                api.Origin    = model.Origin;
                api.Reference = model.Reference;
                api.ActiveJob = job.ToApi();

                return(StatusCode((int)HttpStatusCode.Created, api));
            }
        }
Пример #9
0
 public Task <IActionResult> Read() => Task.FromResult <IActionResult>(
     Json(new Api.Models.Byond
 {
     Version = instanceManager.GetInstance(Instance).ByondManager.ActiveVersion
 }));
 public override Task <IActionResult> Read(CancellationToken cancellationToken) => Task.FromResult <IActionResult>(
     Json(new Api.Models.Byond
 {
     Version = instanceManager.GetInstance(Instance).ByondManager.ActiveVersion
 }));
Пример #11
0
        public async Task <IActionResult> Create([FromBody] Api.Models.ChatBot model, CancellationToken cancellationToken)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var earlyOut = StandardModelChecks(model, true);

            if (earlyOut != null)
            {
                return(earlyOut);
            }

            var countOfExistingBotsInInstance = await DatabaseContext
                                                .ChatBots
                                                .AsQueryable()
                                                .Where(x => x.InstanceId == Instance.Id)
                                                .CountAsync(cancellationToken)
                                                .ConfigureAwait(false);

            if (countOfExistingBotsInInstance >= Instance.ChatBotLimit.Value)
            {
                return(Conflict(new ErrorMessage(ErrorCode.ChatBotMax)));
            }

            model.Enabled ??= false;
            model.ReconnectionInterval ??= 1;

            // try to update das db first
            var dbModel = new Models.ChatBot
            {
                Name                 = model.Name,
                ConnectionString     = model.ConnectionString,
                Enabled              = model.Enabled,
                Channels             = model.Channels?.Select(x => ConvertApiChatChannel(x)).ToList() ?? new List <Models.ChatChannel>(),    // important that this isn't null
                InstanceId           = Instance.Id,
                Provider             = model.Provider,
                ReconnectionInterval = model.ReconnectionInterval,
                ChannelLimit         = model.ChannelLimit
            };

            DatabaseContext.ChatBots.Add(dbModel);

            await DatabaseContext.Save(cancellationToken).ConfigureAwait(false);

            var instance = instanceManager.GetInstance(Instance);

            try
            {
                // try to create it
                await instance.Chat.ChangeSettings(dbModel, cancellationToken).ConfigureAwait(false);

                if (dbModel.Channels.Count > 0)
                {
                    await instance.Chat.ChangeChannels(dbModel.Id, dbModel.Channels, cancellationToken).ConfigureAwait(false);
                }
            }
            catch
            {
                // undo the add
                DatabaseContext.ChatBots.Remove(dbModel);
                await DatabaseContext.Save(default).ConfigureAwait(false);