コード例 #1
0
        public async Task <IActionResult> AddGatewayCommand([FromRoute] HexId gatewayId, [FromBody] Command command)
        {
            if (command == null)
            {
                return(BadRequest());
            }

            if (context.Gateways.FirstOrDefault(g => g.AgentId == gatewayId.Value) == null)
            {
                return(NotFound());
            }

            try
            {
                await helper.AddGatewayCommand(command, gatewayId);

                return(CreatedAtAction(nameof(Get), new { gatewayId, commandId = command.Id }, command));
            }
            catch (ArgumentException e)
            {
                return(BadRequest(e.Message));
            }
            catch (CommandQueues.InvalidGateway e)
            {
                return(StatusCode(StatusCodes.Status410Gone, $"Failed to add command, because {e.Message}. Try restarting gateway."));
            }
        }
コード例 #2
0
ファイル: GatewayController.cs プロジェクト: wisdark/C3
        public IActionResult GetGatewayExeArchitecture(Build.Architecture architecture, string name, [FromServices] ICustomizer customizer, [FromServices] GatewaysSyncService gss)
        {
            using (var ms = new MemoryStream())
            {
                var rand          = new Random();
                var agentId       = new HexId(rand.NextU64()).ToString();
                var nameOrAgentId = name ?? agentId;
                using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create))
                {
                    var gatewayEntry = zipArchive.CreateEntry($"Gateway{architecture}_{nameOrAgentId}.exe");
                    using (var bw = new BinaryWriter(gatewayEntry.Open()))
                    {
                        bw.Write(customizer.GetGateway(architecture));
                    }

                    var configEntry = zipArchive.CreateEntry("GatewayConfiguration.json");
                    var config      = new JObject()
                    {
                        ["BuildId"]         = new HexId(rand.NextU16()).ToString(),
                        ["AgentId"]         = agentId,
                        ["Name"]            = nameOrAgentId,
                        ["API Bridge IP"]   = gss.conf.apiBridge.ipAddress.ToString(),
                        ["API Bridge port"] = gss.conf.apiBridge.port,
                    };
                    using (var w = new StreamWriter(configEntry.Open()))
                    {
                        w.Write(config.ToString());
                    }
                }
                return(File(ms.ToArray(), "application/zip", $"Gateway_{nameOrAgentId}.zip"));
            }
        }
コード例 #3
0
        public ActionResult <IEnumerable <Command> > ListCommands([FromRoute] HexId gatewayId, int page = 1, int perPage = 10, bool all = false)
        {
            var commands = helper.ListCommands(gatewayId, all: all);

            Response.AddPaginationHeaders(page, perPage, commands.Count());
            return(commands.OrderByDescending(r => r.Id).TakePage(page, perPage).ToList());
        }
コード例 #4
0
        public ActionResult <GatewayViewModel> GetGateway(HexId gatewayId)
        {
            var gateway = context.Gateways
                          .Include(g => g.Routes)
                          .Include(g => g.Channels)
                          .Include(g => g.Peripherals)
                          .Include(g => g.Connectors)
                          .Include(g => g.Build)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Routes)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Channels)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Peripherals)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Build)
                          .FirstOrDefault(g => g.AgentId == gatewayId.Value);

            if (gateway is null)
            {
                return(NotFound($"Gateway with id = {gatewayId} not found"));
            }

            return(new GatewayViewModel(gateway));
        }
コード例 #5
0
ファイル: GatewayController.cs プロジェクト: wisdark/C3
        public ActionResult <GatewayViewModel> GetGateway(HexId gatewayId)
        {
            var gateway = context.Gateways
                          .Include(g => g.Routes)
                          .Include(g => g.Channels)
                          .Include(g => g.Peripherals)
                          .Include(g => g.Connectors)
                          .Include(g => g.Build)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Routes)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Channels)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Peripherals)
                          .Include(g => g.Relays)
                          .ThenInclude(r => r.Build)
                          .FirstOrDefault(g => g.AgentId == gatewayId.Value);

            if (gateway is null)
            {
                return(NotFound($"Gateway with id = {gatewayId} not found"));
            }

            var agentIds = gateway.Relays.Select(r => r.AgentId).Append(gateway.AgentId);
            var notes    = context.Notes.Where(n => agentIds.Any(i => i == n.AgentId)).ToList();

            return(new GatewayViewModel(gateway, notes));
        }
コード例 #6
0
ファイル: RelayController.cs プロジェクト: wisdark/C3
        public IEnumerable <Relay> ListRelays([FromRoute] HexId gatewayId, int page = 1, int perPage = 10)
        {
            var relays = context.Relays
                         .Where(relay => relay.GatewayAgentId == gatewayId.Value)
                         .OrderBy(relay => relay.AgentId);

            Response.AddPaginationHeaders(page, perPage, relays.Count());
            return(relays.TakePage(page, perPage));
        }
コード例 #7
0
 public Command Get(ulong commandId, HexId gatewayId, ulong?relayId = null, ulong?interfaceId = null)
 {
     return(context.Commands
            .Where(c => c.GatewayAgentId == gatewayId.Value)
            .Where(c => c.RelayAgentId == relayId)
            .Where(c => c.InterfaceId == interfaceId)
            .Where(c => c.Id == commandId)
            .FirstOrDefault());
 }
コード例 #8
0
        public ActionResult <Command> Get([FromRoute] HexId gatewayId, ulong commandId)
        {
            var request = helper.Get(commandId, gatewayId);

            if (request == null)
            {
                return(NotFound());
            }

            return(request);
        }
コード例 #9
0
ファイル: GatewayController.cs プロジェクト: wisdark/C3
 public ActionResult <GatewayCapabilityView> GetGatewayCapability(HexId gatewayId)
 {
     try
     {
         return(new GatewayCapabilityView(context.Gateways
                                          .Include(g => g.Build)
                                          .Single(g => g.AgentId == gatewayId.Value)
                                          .Build as GatewayBuild));
     }
     catch (InvalidOperationException e)
     {
         return(NotFound($"Gateway with id = {gatewayId} not found. {e.Message}"));
     }
 }
コード例 #10
0
ファイル: GatewayController.cs プロジェクト: wisdark/C3
 public ActionResult <IEnumerable <Route> > ListGatewayRoutes(HexId gatewayId)
 {
     try
     {
         return(context.Gateways
                .Include(g => g.Routes)
                .Single(g => g.AgentId == gatewayId.Value)
                .Routes
                .ToList());
     }
     catch (InvalidOperationException)
     {
         return(NotFound($"Gateway with id = {gatewayId} not found"));
     }
 }
コード例 #11
0
ファイル: BuildController.cs プロジェクト: xiao5gee/C3
        public ActionResult <RelayBuild> GetBuild(HexId buildId)
        {
            if (buildId.Value < 0 || buildId.Value > UInt16.MaxValue)
            {
                return(BadRequest("BuildID out of range"));
            }

            var build = context.RelayBuilds.Where(r => r.BuildId == buildId.Value).FirstOrDefault();

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

            return(NotFound());
        }
コード例 #12
0
ファイル: RelayController.cs プロジェクト: xinyuweb/C3
 public ActionResult <Relay> GetRelay([FromRoute] HexId gatewayId, [FromRoute] HexId relayId)
 {
     try
     {
         return(context.Relays
                .Include(r => r.Channels)
                .Include(r => r.Peripherals)
                .Include(r => r.Routes)
                .Where(r => r.GatewayAgentId == gatewayId.Value)
                .Single(r => r.AgentId == relayId.Value));
     }
     catch (InvalidOperationException)
     {
         return(NotFound());
     }
 }
コード例 #13
0
        public IQueryable <Command> ListCommands(HexId gatewayId, ulong?relayId = null, ulong?interfaceId = null, bool all = false)
        {
            var commands = context.Commands.Where(c => c.GatewayAgentId == gatewayId.Value);

            if (relayId != null || !all)
            {
                commands = commands.Where(c => c.RelayAgentId == relayId);
            }

            if (interfaceId != null || !all)
            {
                commands = commands.Where(c => c.InterfaceId == relayId);
            }

            return(commands);
        }
コード例 #14
0
ファイル: RelayController.cs プロジェクト: wisdark/C3
 public ActionResult <RelayViewModel> GetRelay([FromRoute] HexId gatewayId, [FromRoute] HexId relayId)
 {
     try
     {
         var relay = context.Relays
                     .Include(r => r.Channels)
                     .Include(r => r.Peripherals)
                     .Include(r => r.Routes)
                     .Where(r => r.GatewayAgentId == gatewayId.Value)
                     .Single(r => r.AgentId == relayId.Value);
         return(new RelayViewModel(relay, context.Notes.FirstOrDefault(n => n.AgentId == relay.AgentId)));
     }
     catch (InvalidOperationException)
     {
         return(NotFound());
     }
 }
コード例 #15
0
        /// <summary>
        /// Ensure the target project repository exists on the local SF server, cloning if necessary.
        /// </summary>
        private void EnsureProjectReposExists(UserSecret userSecret, ParatextProject target,
                                              IInternetSharedRepositorySource repositorySource)
        {
            string username          = GetParatextUsername(userSecret);
            bool   targetNeedsCloned =
                ScrTextCollection.FindById(username, target.ParatextId) == null;

            if (target is ParatextResource resource)
            {
                // If the target is a resource, install it
                InstallResource(resource, target.ParatextId, targetNeedsCloned);
            }
            else if (targetNeedsCloned)
            {
                SharedRepository targetRepo = new SharedRepository(target.ShortName, HexId.FromStr(target.ParatextId),
                                                                   RepositoryType.Shared);
                CloneProjectRepo(repositorySource, target.ParatextId, targetRepo);
            }
        }
コード例 #16
0
        // This is not perfect, but allows relay/command api (defined by relay capability) to affect relay data in controller db
        async void RelayAddNote(HexId gatewayId, HexId relayId, Command command)
        {
            try
            {
                // Id check should be enough, but check also name command for sanity.
                // Magic number is from enum Rename = static_cast<std::uint16_t>(-8).
                if ((int)command.Data["id"] != 65528 || (string)command.Data["command"] != "Rename")
                {
                    return;
                }

                if (context.Relays.Where(r => r.GatewayAgentId == gatewayId.Value).Count(r => r.AgentId == relayId.Value) != 1)
                {
                    throw new InvalidOperationException();
                }

                var name = command.Data["arguments"].FirstOrDefault(n => (string)n["name"] == "Name")["value"];
                if (name == null)
                {
                    throw new InvalidOperationException();
                }

                var note = context.Notes.FirstOrDefault(n => n.AgentId == relayId.Value);
                if (note != null)
                {
                    note.DisplayName = (string)name;
                }
                else
                {
                    context.Add(new Note
                    {
                        AgentId     = relayId.Value,
                        DisplayName = (string)name,
                    });
                }

                await context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
        }
コード例 #17
0
        private async Task AddCommand(Command command, HexId gatewayId, HexId relayId = null, HexId deviceId = null, string deviceType = null)
        {
            if (deviceId != null && deviceType is null)
            {
                throw new NullReferenceException("Got DeviceId without device type");
            }

            command.GatewayAgentId = gatewayId.Value;
            command.RelayAgentId   = relayId?.Value;
            command.InterfaceId    = deviceId?.Value;
            command.DeviceType     = deviceType;
            context.Add(command);
            using (var transaction = await context.Database.BeginTransactionAsync())
            {
                // save changes to force command.Id generation
                context.SaveChanges();
                commandQueues.Enqueue(gatewayId.Value, new Models.Action(command));
                // commit only if enqueue doesn't throw
                transaction.Commit();
            }
        }
コード例 #18
0
ファイル: RelayController.cs プロジェクト: wisdark/C3
        public async Task <ActionResult> AddNote([FromRoute] HexId gatewayId, [FromRoute] HexId relayId, string name, string description)
        {
            try
            {
                if (context.Relays.Where(r => r.GatewayAgentId == gatewayId.Value).Count(r => r.AgentId == relayId.Value) != 1)
                {
                    throw new InvalidOperationException();
                }

                var note = context.Notes.FirstOrDefault(n => n.AgentId == relayId.Value);
                if (note != null)
                {
                    if (name != null)
                    {
                        note.DisplayName = name;
                    }
                    if (description != null)
                    {
                        note.Description = description;
                    }
                }
                else
                {
                    note = new Note
                    {
                        AgentId     = relayId.Value,
                        DisplayName = name,
                        Description = description,
                    };
                    context.Add(note);
                }
                await context.SaveChangesAsync();

                return(Ok());
            }
            catch (InvalidOperationException)
            {
                return(NotFound());
            }
        }
コード例 #19
0
        public async Task <IActionResult> AddGatewayDeviceCommand([FromRoute] HexId gatewayId, [FromRoute] string deviceType, [FromRoute] HexId deviceId, [FromBody] Command command)
        {
            if (command == null)
            {
                return(BadRequest());
            }

            // TODO add device type dependent validation
            if (context.Gateways.FirstOrDefault(g => g.AgentId == gatewayId.Value) == null)
            {
                return(NotFound());
            }

            try
            {
                await helper.AddGatewayDeviceCommand(command, gatewayId, deviceId, deviceType); // TODO change to add(Channel|peripheral|connector) command

                return(CreatedAtAction(nameof(Get), new { gatewayId, commandId = command.Id }, command));
            }
            catch (CommandQueues.InvalidGateway e)
            {
                return(StatusCode(StatusCodes.Status410Gone, $"Failed to add command, because {e.Message}. Try restarting gateway."));
            }
        }
コード例 #20
0
 public async Task AddRelayCommand(Command command, HexId gatewayId, HexId relayId)
 {
     await AddCommand(command, gatewayId, relayId);
 }
コード例 #21
0
        /// <summary>
        /// Converts the JSON response to a list of Installable DBL Resources.
        /// </summary>
        /// <param name="baseUri">The base URI.</param>
        /// <param name="response">The response.</param>
        /// <param name="restClientFactory">The rest client factory.</param>
        /// <param name="fileSystemService">The file system service.</param>
        /// <param name="jwtTokenHelper">The JWT token helper.</param>
        /// <param name="createdTimestamp">The created timestamp.</param>
        /// <param name="userSecret">The user secret.</param>
        /// <param name="paratextOptions">The paratext options.</param>
        /// <param name="projectDeleter">The project deleter.</param>
        /// <param name="migrationOperations">The migration operations.</param>
        /// <param name="passwordProvider">The password provider.</param>
        /// <returns>
        /// The Installable Resources.
        /// </returns>
        private static IEnumerable <SFInstallableDblResource> ConvertJsonResponseToInstallableDblResources(
            string baseUri, string response, ISFRestClientFactory restClientFactory,
            IFileSystemService fileSystemService, IJwtTokenHelper jwtTokenHelper, DateTime createdTimestamp,
            UserSecret userSecret, ParatextOptions paratextOptions, IProjectDeleter projectDeleter,
            IMigrationOperations migrationOperations, IZippedResourcePasswordProvider passwordProvider)
        {
            if (!string.IsNullOrWhiteSpace(response))
            {
                JObject jsonResources;
                try
                {
                    jsonResources = JObject.Parse(response);
                }
                catch (JsonReaderException)
                {
                    // Ignore the exception and just return empty result
                    // This is probably caused by partial result from poor connection to DBL
                    yield break;
                }
                foreach (JToken jsonResource in jsonResources["resources"] as JArray ?? new JArray())
                {
                    var name       = (string)jsonResource["name"];
                    var nameCommon = (string)jsonResource["nameCommon"];
                    var fullname   = (string)jsonResource["fullname"];
                    if (string.IsNullOrWhiteSpace(fullname))
                    {
                        fullname = nameCommon;
                    }

                    var        languageName        = (string)jsonResource["languageName"];
                    var        id                  = (string)jsonResource["id"];
                    var        revision            = (string)jsonResource["revision"];
                    var        permissionsChecksum = (string)jsonResource["permissions-checksum"];
                    var        manifestChecksum    = (string)jsonResource["p8z-manifest-checksum"];
                    var        languageIdLdml      = (string)jsonResource["languageLDMLId"];
                    var        languageIdCode      = (string)jsonResource["languageCode"];
                    LanguageId languageId          =
                        migrationOperations.DetermineBestLangIdToUseForResource(languageIdLdml, languageIdCode);
                    if (string.IsNullOrEmpty(languageId.Id))
                    {
                        languageId = LanguageIdHelper.FromCommonLanguageName(languageName);
                    }
                    else
                    {
                        languageId = LanguageId.FromEthnologueCode(languageId.Id);
                    }

                    string url      = BuildDblResourceEntriesUrl(baseUri, id);
                    var    resource = new SFInstallableDblResource(userSecret, paratextOptions, restClientFactory,
                                                                   fileSystemService, jwtTokenHelper, projectDeleter, migrationOperations, passwordProvider)
                    {
                        DisplayName         = name,
                        Name                = name,
                        FullName            = fullname,
                        LanguageID          = languageId,
                        DblSourceUrl        = url,
                        DBLEntryUid         = HexId.FromStr(id),
                        DBLRevision         = int.Parse(revision),
                        PermissionsChecksum = permissionsChecksum,
                        ManifestChecksum    = manifestChecksum,
                        CreatedTimestamp    = createdTimestamp,
                    };

                    resource.LanguageName = MacroLanguageHelper.GetMacroLanguage(resource.LanguageID) ?? languageName;

                    yield return(resource);
                }
            }
        }
コード例 #22
0
 public async Task AddRelayDeviceCommand(Command command, HexId gatewayId, HexId relayId, HexId deviceId, string deviceType)
 {
     await AddCommand(command, gatewayId, relayId : relayId, deviceId : deviceId, deviceType : deviceType);
 }
コード例 #23
0
 public SharedProject CreateSharedProject(string projId, string proj, SharedRepositorySource source,
                                          IEnumerable <SharedRepository> sourceRepositories)
 {
     return(SharingLogic.CreateSharedProject(HexId.FromStr(projId), proj, source, sourceRepositories));
 }