Ejemplo n.º 1
0
        private IEnumerable <ChannelInformation> GetChannelAvailabilityInfo(ChannelInfo[] channelInfoList, int channelStartId, int channelEndId, double powerDBmTransitionPoint)
        {
            List <ChannelInformation> channels = new List <ChannelInformation>();

            bool anyFreeChannels = channelInfoList != null && channelInfoList.Any();

            //// TODO: Little bit of refactoring required below. First get all the channels details and then Free Channels, then create a list of ChannelInformation list.
            //// As of now, still there is no support for GetAllChannels from the region management api.
            for (int channelId = channelStartId; channelId <= channelEndId; channelId++)
            {
                ChannelInformation channelInformation = new ChannelInformation();
                ChannelInfo        channel            = anyFreeChannels ? channelInfoList.FirstOrDefault(channelInfo => channelInfo.ChannelId == channelId) : null;

                if (channel == null)
                {
                    // TODO: channel should be obtained from the GetAllChannels method from the region management api, which is not implemented yet.
                    channel = new ChannelInfo {
                        ChannelId = channelId
                    };
                    channelInformation.OperationMode = (int)ChannelOperationMode.None;
                }
                else
                {
                    channelInformation.OperationMode = (int)CommonUtility.GetChannelOperationMode(channel.MaxPowerDBm, powerDBmTransitionPoint);
                }

                channelInformation.Channel = channel;

                channels.Add(channelInformation);
            }

            return(channels);
        }
Ejemplo n.º 2
0
        private static void ConfigureServices()
        {
            var builder = new ContainerBuilder();

            var configRoot = new ConfigurationBuilder()
                             .SetBasePath(Environment.CurrentDirectory)
                             .AddJsonFile("appConfig.json")
                             .AddJsonFile("AlphaVantageAPI.key")
                             .Build();

            builder.Register(c => configRoot.Get <Configuration>())
            .AsSelf()
            .SingleInstance();

            var channelInfo = new ChannelInformation()
                              .AddChannel <ConsoleConfig>("Logger:Channels:Console")
                              .AddChannel <FileConfig>("Logger:Channels:File");

            builder.RegisterJ4JLogging <J4JLoggerConfiguration>(
                new ChannelFactory(configRoot, channelInfo, "Logger"));

            builder.RegisterType <DataRetriever>()
            .AsSelf()
            .SingleInstance();

            _svcProvider = new AutofacServiceProvider(builder.Build());
        }
        private async Task <IClientChannel> GetChannelAsync(CancellationToken cancellationToken, string operationName)
        {
            var channelCreated = false;
            var clientChannel  = _clientChannel;

            while (ShouldCreateChannel(clientChannel))
            {
                cancellationToken.ThrowIfCancellationRequested();

                await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    clientChannel = _clientChannel;
                    if (ShouldCreateChannel(clientChannel))
                    {
                        _cts?.Cancel();
                        _cts?.Dispose();

                        clientChannel = _clientChannel = await _builder
                                                         .BuildAndEstablishAsync(cancellationToken)
                                                         .ConfigureAwait(false);

                        _cts = new CancellationTokenSource();
                        _finishedSessionTask = clientChannel.ReceiveFinishedSessionAsync(_cts.Token);
                        channelCreated       = true;
                        break;
                    }
                }
                catch (OperationCanceledException) when(cancellationToken.IsCancellationRequested)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    var failedChannelInformation = new FailedChannelInformation(
                        null, SessionState.New, null, null, false, ex, operationName);

                    var handlers = ChannelCreationFailedHandlers.ToList();
                    if (!await InvokeHandlersAsync(handlers, failedChannelInformation, cancellationToken).ConfigureAwait(false))
                    {
                        throw;
                    }
                }
                finally
                {
                    _semaphore.Release();
                }
            }

            if (channelCreated && clientChannel != null)
            {
                var channelInformation = new ChannelInformation(clientChannel.SessionId, clientChannel.State, clientChannel.LocalNode, clientChannel.RemoteNode);
                var handlers           = ChannelCreatedHandlers.ToList();
                await InvokeHandlersAsync(handlers, channelInformation, cancellationToken).ConfigureAwait(false);
            }

            return(clientChannel);
        }
Ejemplo n.º 4
0
 private Task ChannelCreatedAsync(ChannelInformation channelInformation)
 {
     _logger.Information("Channel '{SessionId}' created - Local node {LocalNode} - Remote node: {RemoteNode}",
                         channelInformation.SessionId,
                         channelInformation.LocalNode,
                         channelInformation.RemoteNode);
     return(Task.CompletedTask);
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Finds the channel and sends the information
        /// </summary>
        private async Task GetChannelInformation(MqClient client, TmqMessage message)
        {
            if (_server.AdminAuthorization == null)
            {
                if (message.ResponseRequired)
                {
                    await client.SendAsync(MessageBuilder.ResponseStatus(message, KnownContentTypes.Unauthorized));
                }

                return;
            }

            Channel channel = _server.FindChannel(message.Target);

            if (channel == null)
            {
                await client.SendAsync(MessageBuilder.ResponseStatus(message, KnownContentTypes.NotFound));

                return;
            }

            bool grant = await _server.AdminAuthorization.CanReceiveChannelInfo(client, channel);

            if (!grant)
            {
                if (message.ResponseRequired)
                {
                    await client.SendAsync(MessageBuilder.ResponseStatus(message, KnownContentTypes.Unauthorized));
                }

                return;
            }

            ChannelInformation information = new ChannelInformation
            {
                Name   = channel.Name,
                Queues = channel.QueuesClone.Select(x => x.Id).ToArray(),
                AllowMultipleQueues = channel.Options.AllowMultipleQueues,
                AllowedQueues       = channel.Options.AllowedQueues,
                OnlyFirstAcquirer   = channel.Options.SendOnlyFirstAcquirer,
                RequestAcknowledge  = channel.Options.RequestAcknowledge,
                AcknowledgeTimeout  = Convert.ToInt32(channel.Options.AcknowledgeTimeout.TotalMilliseconds),
                MessageTimeout      = Convert.ToInt32(channel.Options.MessageTimeout.TotalMilliseconds),
                WaitForAcknowledge  = channel.Options.WaitForAcknowledge,
                HideClientNames     = channel.Options.HideClientNames,
                QueueLimit          = channel.Options.QueueLimit,
                ClientLimit         = channel.Options.ClientLimit,
                DestroyWhenEmpty    = channel.Options.DestroyWhenEmpty,
                ActiveClients       = channel.ClientsCount()
            };

            TmqMessage response = message.CreateResponse();

            message.ContentType = KnownContentTypes.ChannelInformation;
            await response.SetJsonContent(information);

            await client.SendAsync(response);
        }
Ejemplo n.º 6
0
 private Task ChannelDiscardedAsync(ChannelInformation channelInformation)
 {
     Trace.TraceInformation("Channel '{0}' discarded", channelInformation.SessionId);
     if (_isDisconnecting)
     {
         return(Task.CompletedTask);
     }
     return(Task.Delay(ChannelDiscardedDelay));
 }
Ejemplo n.º 7
0
        private async void HandleChangeTitleCmd(object sender, OnChatCommandReceivedArgs e)
        {
            if (!(sender is TwitchClient senderClient))
            {
                return;
            }

            if (!Extensions.IsHost(senderClient.TwitchUsername))
            {
                return;
            }

            string newTitle = e.Command.ArgumentsAsString;

            if (newTitle == null || newTitle.Length <= 0)
            {
                return;
            }

            GetUsersResponse resp = await LeTwitchBot.BotAPI.Helix.Users.GetUsersAsync(null, new List <string> {
                senderClient.TwitchUsername
            });

            if (resp.Users.Length <= 0)
            {
                return;
            }
            User user = resp.Users[0];

            if (!user.DisplayName.ToLower().Equals(LeTwitchBot.HostChannelName.ToLower()))
            {
                return;
            }

            GetChannelInformationResponse existingInfo = await LeTwitchBot.BotAPI.Helix.Channels.GetChannelInformationAsync(user.Id);

            if (existingInfo.Data.Length <= 0)
            {
                return;
            }
            ChannelInformation info = existingInfo.Data[0];


            ModifyChannelInformationRequest changeReq = new ModifyChannelInformationRequest();

            changeReq.BroadcasterLanguage = info.BroadcasterLanguage;
            changeReq.Title  = newTitle;
            changeReq.GameId = info.GameId;

            await LeTwitchBot.BotAPI.Helix.Channels.ModifyChannelInformationAsync(user.Id, changeReq, LeTwitchBot.Secrets.HostChannelUserToken);


            LeTwitchBot.TwitchClient.SendHostChannelMessage($"Broadcaster {user.DisplayName} has changed the title of the stream to '{newTitle}' CoolCat CoolCat CoolCat CoolCat");
        }
Ejemplo n.º 8
0
 private async Task DiscardChannelUnsynchronizedAsync(IChannel clientChannel, CancellationToken cancellationToken)
 {
     if (ReferenceEquals(clientChannel, _clientChannel))
     {
         _clientChannel = null;
         clientChannel.DisposeIfDisposable();
         var channelInformation = new ChannelInformation(clientChannel.SessionId, clientChannel.State, clientChannel.LocalNode, clientChannel.RemoteNode);
         var handlers           = ChannelDiscardedHandlers.ToList();
         await InvokeHandlersAsync(handlers, channelInformation, cancellationToken).ConfigureAwait(false);
     }
 }
Ejemplo n.º 9
0
        private Task ChannelDiscardedAsync(ChannelInformation channelInformation)
        {
            _logger.Information("Channel '{SessionId}' discarded - Local node: {LocalNode} - Remote node: {RemoteNode}",
                                channelInformation.SessionId,
                                channelInformation.LocalNode,
                                channelInformation.RemoteNode);

            if (_isStopping)
            {
                return(Task.CompletedTask);
            }
            return(Task.Delay(ChannelDiscardedDelay));
        }
Ejemplo n.º 10
0
    void Awake()
    {
        if (channelInfo == null)
        {
            channelInfo = this;
        }
        else
        {
            Destroy(this);
        }

        LoadValues();
    }
Ejemplo n.º 11
0
        private void OnRegisterServer(InPacket packet)
        {
            var    serverType = (ServerType)packet.Decode <byte>();
            string serverName;

            ServerType = serverType;

            switch (serverType)
            {
            case ServerType.Login:
                var loginInformation = new LoginInformation();

                loginInformation.Decode(packet);
                ServerID   = loginInformation.ID;
                serverName = loginInformation.Name;
                break;

            case ServerType.Game:
                var channelInformation = new ChannelInformation();

                channelInformation.Decode(packet);
                _wvsCenter.WorldInformation.Channels.Add(channelInformation);
                ServerID   = channelInformation.ID;
                serverName = channelInformation.Name;
                break;

            default:
                using (var p = new OutPacket(InteropSendOperations.ServerRegisterResult))
                {
                    p.Encode <bool>(true);
                    SendPacket(p);
                }

                return;
            }

            using (var p = new OutPacket(InteropSendOperations.ServerRegisterResult))
            {
                p.Encode <bool>(false);
                _wvsCenter.WorldInformation.Encode(p);
                SendPacket(p);
            }

            using (var p = new OutPacket(InteropSendOperations.ServerInformation))
            {
                _wvsCenter.WorldInformation.Encode(p);
                _wvsCenter.InteropServer.BroadcastPacket(p, new EveryOneBut(Channel.Id));
            }

            Logger.Info($"Registered {Enum.GetName(typeof(ServerType), serverType)} server, {serverName}");
        }
Ejemplo n.º 12
0
        private void OnCheckSPWRequest(InPacket packet, bool vac)
        {
            var spw         = packet.Decode <string>();
            var characterID = packet.Decode <int>();

            packet.Decode <string>(); // sMacAddress
            packet.Decode <string>(); // sMacAddressWithHDDSerial

            if (string.IsNullOrEmpty(Account.SPW))
            {
                return;
            }
            if (!BCrypt.Net.BCrypt.Verify(spw, Account.SPW))
            {
                using (var p = new OutPacket(LoginSendOperations.CheckSPWResult))
                {
                    p.Encode <bool>(false); // Unused byte
                    SendPacket(p);
                }

                return;
            }

            if (vac)
            {
                var character = Account.Data
                                .SelectMany(a => a.Characters)
                                .Single(c => c.ID == characterID);
                _selectedWorld = _wvsLogin.InteropClients
                                 .Select(c => c.Socket.WorldInformation)
                                 .SingleOrDefault(w => w.ID == character.Data.WorldID);
                _selectedChannel = _selectedWorld.Channels.First();
            }

            var world = _wvsLogin.InteropClients.Single(c => c.Socket.WorldInformation.ID == _selectedWorld.ID);

            using (var p = new OutPacket(InteropRecvOperations.MigrationRequest))
            {
                p.Encode <byte>((byte)ServerType.Game);
                p.Encode <byte>(_selectedChannel.ID);
                p.Encode <string>(SessionKey);
                p.Encode <int>(characterID);
                world.Socket.SendPacket(p);
            }
        }
Ejemplo n.º 13
0
        private IEnumerable <ChannelInformation> GetChannelInfoList(double latitude, double longitude, string incumbentType, string countryRegion, int channelStartId, int channelEndId, double powerDBmTransitionPoint)
        {
            ChannelInfo[]             channelInfoList = null;
            List <ChannelInformation> channels        = new List <ChannelInformation>();

            try
            {
                channelInfoList = this.whitespacesManager.GetChannelList(incumbentType, latitude, longitude, countryRegion);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.ToString());
            }

            bool anyFreeChannels = channelInfoList != null && channelInfoList.Any();

            //// TODO: Little bit of refactoring required below. First get all the channels details and then Free Channels, then create a list of ChannelInformation list.
            //// As of now, still there is no support for GetAllChannels from the region management api.
            for (int channelId = channelStartId; channelId <= channelEndId; channelId++)
            {
                ChannelInformation channelInformation = new ChannelInformation();
                ChannelInfo        channel            = anyFreeChannels ? channelInfoList.FirstOrDefault(channelInfo => channelInfo.ChannelId == channelId) : null;

                if (channel == null)
                {
                    // TODO: channel should be obtained from the GetAllChannels method from the region management api, which is not implemented yet.
                    channel = new ChannelInfo {
                        ChannelId = channelId
                    };
                    channelInformation.OperationMode = (int)ChannelOperationMode.None;
                }
                else
                {
                    channelInformation.OperationMode = (int)CommonUtility.GetChannelOperationMode(channel.MaxPowerDBm, powerDBmTransitionPoint);
                }

                channelInformation.Channel = channel;

                channels.Add(channelInformation);
            }

            return(channels);
        }
Ejemplo n.º 14
0
        private async void HandleSetGame(object sender, OnChatCommandReceivedArgs e)
        {
            if (!(sender is TwitchClient senderClient))
            {
                return;
            }

            if (!Extensions.IsHost(senderClient.TwitchUsername))
            {
                return;
            }

            string newGame = e.Command.ArgumentsAsString;

            if (newGame == null || newGame.Length <= 0)
            {
                return;
            }

            GetUsersResponse resp = await LeTwitchBot.BotAPI.Helix.Users.GetUsersAsync(null, new List <string> {
                senderClient.TwitchUsername
            });

            if (resp.Users.Length <= 0)
            {
                return;
            }
            User user = resp.Users[0];

            if (!user.DisplayName.ToLower().Equals(LeTwitchBot.HostChannelName.ToLower()))
            {
                return;
            }

            GetChannelInformationResponse existingInfo = await LeTwitchBot.BotAPI.Helix.Channels.GetChannelInformationAsync(user.Id);

            if (existingInfo.Data.Length <= 0)
            {
                return;
            }
            ChannelInformation info = existingInfo.Data[0];

            GetGamesResponse gameResponse = await LeTwitchBot.BotAPI.Helix.Games.GetGamesAsync(null, new List <string> {
                newGame
            });

            if (gameResponse.Games.Length <= 0)
            {
                LeTwitchBot.TwitchClient.SendHostChannelMessage($"Couldn't locate {newGame} :( :( :( :( ");
                return;
            }

            Game tehGame = gameResponse.Games[0];


            ModifyChannelInformationRequest changeReq = new ModifyChannelInformationRequest();

            changeReq.BroadcasterLanguage = info.BroadcasterLanguage;
            changeReq.Title  = info.Title;
            changeReq.GameId = tehGame.Id;

            await LeTwitchBot.BotAPI.Helix.Channels.ModifyChannelInformationAsync(user.Id, changeReq, LeTwitchBot.Secrets.HostChannelUserToken);


            LeTwitchBot.TwitchClient.SendHostChannelMessage($"Broadcaster {user.DisplayName} will now be playin' {tehGame.Name} Kappa Kappa Kappa Kappa");
        }
Ejemplo n.º 15
0
        private void OnSelectWorld(InPacket packet)
        {
            packet.Decode <byte>();

            var worldID   = packet.Decode <byte>();
            var channelID = packet.Decode <byte>() + 1;

            using (var p = new OutPacket(LoginSendOperations.SelectWorldResult))
            {
                byte result = 0x0;
                var  world  = _wvsLogin.InteropClients
                              .Select(c => c.Socket.WorldInformation)
                              .SingleOrDefault(w => w.ID == worldID);
                var channel = world?.Channels.SingleOrDefault(c => c.ID == channelID);

                if (world == null)
                {
                    result = 0x1;
                }
                if (channel == null)
                {
                    result = 0x1;
                }

                p.Encode <byte>(result);

                if (result == 0)
                {
                    _selectedWorld   = world;
                    _selectedChannel = channel;

                    using (var db = _container.GetInstance <DataContext>())
                    {
                        var data = Account.Data.SingleOrDefault(d => d.WorldID == worldID);

                        if (data == null)
                        {
                            data = new AccountData
                            {
                                WorldID   = worldID,
                                SlotCount = 3
                            };

                            Account.Data.Add(data);
                            db.Update(Account);
                            db.SaveChanges();
                        }

                        var characters = data.Characters;

                        p.Encode <byte>((byte)characters.Count);
                        characters.ForEach(c =>
                        {
                            c.EncodeStats(p);
                            c.EncodeLook(p);

                            p.Encode <bool>(false);
                            p.Encode <bool>(false);
                        });

                        p.Encode <bool>(!string.IsNullOrEmpty(Account.SPW)); // bLoginOpt TODO: proper bLoginOpt stuff
                        p.Encode <int>(data.SlotCount);                      // nSlotCount
                        p.Encode <int>(0);                                   // nBuyCharCount
                    }
                }

                SendPacket(p);
            }
        }
Ejemplo n.º 16
0
        private static async Task InvokeHandlersAsync(IEnumerable <Func <ChannelInformation, Task> > handlers, ChannelInformation channelInformation, CancellationToken cancellationToken)
        {
            var exceptions = new List <Exception>();

            foreach (var handler in handlers)
            {
                cancellationToken.ThrowIfCancellationRequested();
                try
                {
                    await handler(channelInformation).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }
            ThrowIfAny(exceptions);
        }
Ejemplo n.º 17
0
 private Task ChannelCreatedAsync(ChannelInformation channelInformation)
 {
     Trace.TraceInformation("Channel '{0}' created", channelInformation.SessionId);
     return(Task.CompletedTask);
 }
Ejemplo n.º 18
0
        public async Task Run()
        {
            var options = _container.GetInstance <WvsGameOptions>();
            var info    = options.GameInfo;

            ChannelInformation = new ChannelInformation
            {
                ID           = info.ID,
                WorldID      = info.WorldID,
                Name         = info.Name,
                UserNo       = 0,
                AdultChannel = info.AdultChannel
            };

            CommandRegistry = _container.GetInstance <CommandRegistry>();

            ItemNames  = _container.GetInstance <ItemNameManager>();
            FieldNames = _container.GetInstance <FieldNameManager>();

            Logger.Info("Loading template names..");
            await Task.WhenAll(
                ItemNames.LoadAll(),
                FieldNames.LoadAll()
                );

            Logger.Info("Finished loading template names");

            ItemOptions = _container.GetInstance <EagerTemplateManager <ItemOptionTemplate> >();
            SetItemInfo = _container.GetInstance <EagerTemplateManager <SetItemInfoTemplate> >();
            await Task.WhenAll(
                Task.Run(async() =>
            {
                Logger.Info("Loading item options..");
                await ItemOptions.LoadAll();
                Logger.Info("Finished loading item options");
            }),
                Task.Run(async() =>
            {
                Logger.Info("Loading set item info..");
                await SetItemInfo.LoadAll();
                Logger.Info("Finished loading set item info");
            })
                );

            SkillTemplates = _container.GetInstance <LazyTemplateManager <SkillTemplate> >();
            ItemTemplates  = _container.GetInstance <LazyTemplateManager <ItemTemplate> >();
            FieldTemplates = _container.GetInstance <LazyTemplateManager <FieldTemplate> >();
            NpcTemplates   = _container.GetInstance <LazyTemplateManager <NPCTemplate> >();
            MobTemplates   = _container.GetInstance <LazyTemplateManager <MobTemplate> >();
            FieldFactory   = new FieldFactory(FieldTemplates, NpcTemplates, MobTemplates);

            using (var db = _container.GetInstance <DataContext>())
            {
                Logger.Info("Loading npc shops..");
                NPCShops = db.NPCShops
                           .Include(s => s.Items)
                           .ToDictionary(s => s.TemplateID, s => new NPCShopDlg(s));
                Logger.Info("Finished loading npc shops");
            }

            UserData.RegisterType <FieldUserSpeaker>();
            UserData.RegisterType <FieldNPCSpeaker>();
            NPCConversationManager = _container.GetInstance <ConversationManager <FieldUser, FieldNPC> >();

            InteropClient = new Client <CenterServerSocket>(
                options.InteropClientOptions,
                _container.GetInstance <CenterServerSocketFactory>()
                );

            GameServer = new Server <GameClientSocket>(
                options.GameServerOptions,
                _container.GetInstance <GameClientSocketFactory>()
                );

            await InteropClient.Run();

            Logger.Info($"Connected to interoperability server on {InteropClient.Channel.RemoteAddress}");

            await GameServer.Run();

            Logger.Info($"Bounded {ChannelInformation.Name} on {GameServer.Channel.LocalAddress}");

            while (InteropClient.Socket == null)
            {
                ;
            }

            using (var p = new OutPacket(InteropRecvOperations.ServerRegister))
            {
                p.Encode <byte>((byte)ServerType.Game);
                ChannelInformation.Encode(p);

                await InteropClient.Socket.SendPacket(p);
            }
        }