Наследование: System.Web.Services.WebService
Пример #1
0
        public ChatView(CoreUI ui, ChatService chat, uint project)
        {
            InitializeComponent();

            UI = ui;
            Chat = chat;
            ProjectID = project;

            Chat.Refresh += new RefreshHandler(Chat_Refresh);

            GuiUtils.SetupToolstrip(toolStrip1, new OpusColorTable());
            GuiUtils.FixMonoDropDownOpening(RoomsButton, RoomsButton_DropDownOpening);

            RoomsButton.Visible  = true;
            RoomSeparator.Visible = true;

            LocalButton.Visible = (Chat.Core.Trust != null);
            LiveButton.Visible = (Chat.Core.Trust != null);

            CustomButton.Visible  = false;

            JoinButton.Visible   = false;
            LeaveButton.Visible  = false;
            InviteButton.Visible = false;
        }
Пример #2
0
 public MainWindow()
 {
     InitializeComponent();
     ChatService chat = new ChatService("testUser", "testRoom");
     chat.connectServer();
     chat.sendText("Hello every one");
 }
Пример #3
0
 private void getChat(object sender, ChatService.GetChatCompletedEventArgs e)
 {
     if (e.Error == null)
     {
         ChatBox.ItemsSource = e.Result;
     }
 }
        public DotNetChatViewModel(ChatService chatService)
        {
            _chatService = chatService;
            _members = new ObservableCollection<MemberViewModel>();
            _chatEntries = new ObservableCollection<ChatEntryViewModel>();

            SendMessageCommand = new ViewModelCommand(SendMessageExecute);
        }
Пример #5
0
        public ChatUI(CoreUI ui, OpService service)
        {
            UI = ui;
            Core = ui.Core;
            Chat = service as ChatService;

            Chat.NewInvite += Chat_NewInvite;
        }
Пример #6
0
 public static void PrintMessages(ChatService.Message[] messages)
 {
     Console.Clear();
     for (int index = 0; index < messages.Length; index++ )
     {
         Console.WriteLine(messages[index].User + ": " + messages[index].Content);
     }
     Console.WriteLine("*** type your'e message ***");
 }
Пример #7
0
 public ClientServiceImpl(String hostIP, ChatService chatService)
 {
     this.hostIP = hostIP;
     this.chatService = chatService;
     this.chatService.setClientService(this);
     mConfig = new NetPeerConfiguration(Program.tag);
     Thread worker = new Thread(new ThreadStart(Initialize));
     worker.Start();
     while (!worker.IsAlive);
     this.chatService.start();
 }
Пример #8
0
        public InviteForm(CoreUI ui, ChatService chat, ulong user, ChatRoom room)
        {
            InitializeComponent();

            UI = ui;
            Core = ui.Core;
            Chat = chat;
            Room = room;

            IntroLabel.Text = IntroLabel.Text.Replace("<name>", Core.GetName(user));

            NameLabel.Text = room.Title;

            TypeLabel.Text = room.Kind.ToString();
        }
Пример #9
0
        public void GetChatHistory()
        {
            int agentId = 1;
            int count = 2;
            DateTime date = new DateTime(2000, 1, 1);
            Mock<IServerEventsProcessor> controllerFactoryMock = new Mock<IServerEventsProcessor>();
            Mock<IChatProcessor> chatControllerMock = new Mock<IChatProcessor>();
            Mock<IOperatorChatHistoryRecord> chatRecordMock = new Mock<IOperatorChatHistoryRecord>();
            List<IOperatorChatHistoryRecord> expectedResult = new List<IOperatorChatHistoryRecord> {chatRecordMock.Object};
            controllerFactoryMock.Setup(factory => factory.ChatProcessor).Returns(chatControllerMock.Object);
            chatControllerMock.Setup(controller => controller.GetChatHistory(agentId, date, count))
                .Returns(expectedResult);

            ChatService chatService = new ChatService(controllerFactoryMock.Object);
            IEnumerable<IOperatorChatHistoryRecord> res = chatService.GetChatHistory(agentId, date, count);
            Assert.AreEqual(res, expectedResult);
        }
Пример #10
0
    static void Main(string[] args)
    {
      // WARNING: This is not the best implementation but for my purposes a singleton should be fine. Check out these links
      // for an explanation. I did this simply so I wouldn't have to store the MySQL credentials in plain text.
      // http://stackoverflow.com/questions/14206267/how-do-i-pass-parameters-to-a-servicehost
      // http://stackoverflow.com/questions/2454850/how-do-i-pass-values-to-the-constructor-on-my-wcf-service/2455039#2455039
      Console.WriteLine("Enter MySQL Username: "******"Enter MySQL Password: "******"ChatServiceHost started @ " + DateTime.Now);
        Console.WriteLine("Press enter to terminate...");
        Console.Read();
      }
    }
Пример #11
0
    private void setCookie(string chatId)
    {
        if (Request.Cookies["chatId"] != null)
        {
            Response.Cookies["chatId"].Value = chatId;
        }
        else
        {
            HttpCookie cookie = new HttpCookie("chatId", chatId);
            Response.Cookies.Add(cookie);
        }

        string lastCheck = ChatService.GetChatById(chatId).CreateTime.Ticks.ToString();

        if (Request.Cookies[chatId + "_lastCheck"] != null)
        {
            Response.Cookies[chatId + "_lastCheck"].Value = lastCheck;
        }
        else
        {
            HttpCookie cookie = new HttpCookie(chatId + "_lastCheck", lastCheck);
            Response.Cookies.Add(cookie);
        }
    }
Пример #12
0
            public void RemovesUserFromRoom()
            {
                var repository = new InMemoryRepository();
                var user       = new ChatUser
                {
                    Name = "foo"
                };

                repository.Add(user);
                var room = new ChatRoom
                {
                    Name = "Room"
                };

                room.Users.Add(user);
                user.Rooms.Add(room);

                var service = new ChatService(repository, new Mock <ICryptoService>().Object);

                service.LeaveRoom(user, room);

                Assert.False(user.Rooms.Contains(room));
                Assert.False(room.Users.Contains(user));
            }
Пример #13
0
            public void MakesUserOwnerIfUserAlreadyAllowed()
            {
                var repository = new InMemoryRepository();
                var user       = new ChatUser
                {
                    Name = "foo"
                };
                var user2 = new ChatUser
                {
                    Name = "foo2"
                };

                repository.Add(user);
                repository.Add(user2);
                var room = new ChatRoom
                {
                    Name    = "Room",
                    Private = true,
                    Creator = user
                };

                room.Owners.Add(user);
                user.OwnedRooms.Add(room);
                user.Rooms.Add(room);
                room.Users.Add(user);

                user2.AllowedRooms.Add(room);
                room.AllowedUsers.Add(user2);

                var service = new ChatService(repository, new Mock <ICryptoService>().Object);

                service.AddOwner(user, user2, room);

                Assert.True(room.Owners.Contains(user2));
                Assert.True(user2.OwnedRooms.Contains(room));
            }
Пример #14
0
            public void ThrowsIfKickSelf()
            {
                var repository = new InMemoryRepository();
                var user       = new ChatUser
                {
                    Name = "foo"
                };

                repository.Add(user);
                var room = new ChatRoom
                {
                    Name    = "Room",
                    Creator = user
                };

                room.Owners.Add(user);
                user.OwnedRooms.Add(room);
                user.Rooms.Add(room);
                room.Users.Add(user);

                var service = new ChatService(repository, new Mock <ICryptoService>().Object);

                Assert.Throws <InvalidOperationException>(() => service.KickUser(user, user, room));
            }
Пример #15
0
        public static async Task Main(string[] args)
        {
            name    = "console " + random.Next(0, 10000);
            service = new ChatService();
            service.OnReceivedMessage += Service_OnReceivedMessage;
            Console.WriteLine("Enter IP:");
            var ip = Console.ReadLine();

            service.Init(ip, ip != "localhost");

            await service.ConnectAsync();

            Console.WriteLine("You are connected...");

            await JoinRoom();

            var keepGoing = true;

            do
            {
                var text = Console.ReadLine();
                if (text == "exit")
                {
                    keepGoing = false;
                }
                else if (text == "leave")
                {
                    await service.LeaveChannelAsync(room, name);
                    await JoinRoom();
                }
                else
                {
                    await service.SendMessageAsync(room, name, text);
                }
            }while (keepGoing);
        }
Пример #16
0
        public ActionResult CheckMessages(Guid id)
        {
            long lastId = 0;

            if (Request.Cookies["lcsk_id"] != null)
            {
                lastId = long.Parse(Request.Cookies["lcsk_id"].Value);
            }

            Debug.WriteLine(string.Format("{0}\t{1}\t{2}", DateTime.Now, "CheckMessages", lastId));

            if (ChatService.HasNewMessage(id, lastId))
            {
                var msgs = ChatService.GetMessages(id, lastId);
                lastId = msgs.Max(x => x.MessageId);

                HttpCookie ck = new HttpCookie("lcsk_id");
                ck.Value = lastId.ToString();
                Response.Cookies.Add(ck);

                return(PartialView("ChatLine", msgs));
            }
            return(null);
        }
Пример #17
0
        public void TestAddingThreadToChat()
        {
            var role = new Role(new[] { Permission.CreateChat, Permission.DeleteThread });
            var user = new User("TestUser", role);

            user.Login();
            var chatDao     = new ChatDao();
            var httpContext = new HttpContext();
            var chatService = new ChatService(httpContext, chatDao, new UserDao());
            var chatId      = chatService.NewChat(user);

            const string title   = "A new thread";
            const string message = "Let's discuss things...";

            chatService.AddThread(chatId, user, user.Username, title, message);

            var chat = chatDao.GetChatById(chatId);

            Assert.That(chat.CreatedBy, Is.EqualTo(user.Username));
            Assert.That(chat.Threads.First().Username, Is.EqualTo(user.Username));
            Assert.That(chat.Threads.First().Title, Is.EqualTo(title));
            Assert.That(chat.Threads.First().Message, Is.EqualTo(message));
            Assert.That(httpContext.Path, Is.EqualTo($"/{chatId}/threads/"));
        }
Пример #18
0
            public void UnallowsAndRemovesUserFromRoom()
            {
                var repository = new InMemoryRepository();
                var user       = new ChatUser
                {
                    Name = "foo"
                };
                var user2 = new ChatUser
                {
                    Name = "foo2"
                };

                repository.Add(user);
                repository.Add(user2);
                var room = new ChatRoom
                {
                    Name    = "Room",
                    Private = true
                };

                room.AllowedUsers.Add(user2);
                room.Owners.Add(user);
                room.Users.Add(user);
                user.OwnedRooms.Add(room);
                user.Rooms.Add(room);
                user2.AllowedRooms.Add(room);

                var service = new ChatService(repository, new Mock <ICryptoService>().Object);

                service.UnallowUser(user, user2, room);

                Assert.False(room.Users.Contains(user2));
                Assert.False(user2.Rooms.Contains(room));
                Assert.False(room.AllowedUsers.Contains(user2));
                Assert.False(user2.AllowedRooms.Contains(room));
            }
Пример #19
0
            public void AddsUserToRoomIfAllowedAndRoomIsPrivate()
            {
                var repository = new InMemoryRepository();
                var user       = new ChatUser
                {
                    Name = "foo"
                };

                repository.Add(user);
                var room = new ChatRoom
                {
                    Name    = "Room",
                    Private = true
                };

                room.AllowedUsers.Add(user);
                user.AllowedRooms.Add(room);
                var service = new ChatService(repository, new Mock <ICryptoService>().Object);

                service.JoinRoom(user, room, null);

                Assert.True(user.Rooms.Contains(room));
                Assert.True(room.Users.Contains(user));
            }
Пример #20
0
 public ChatDetailsController(ChatService eventService)
 {
     _eventService = eventService;
 }
Пример #21
0
 public ChatModule(ChatService service)
 {
     _service = service;
     _service.SetParentModule(this);
 }
Пример #22
0
 public Stargate(BuildOptions buildOptions, MacroData macroData, ActiveUnitData activeUnitData, AttackData attackData, ChatService chatService, ChronoData chronoData, ICounterTransitioner counterTransitioner, UnitCountService unitCountService, MicroTaskData microTaskData)
     : base(buildOptions, macroData, activeUnitData, attackData, chatService, chronoData, counterTransitioner, unitCountService, microTaskData)
 {
 }
Пример #23
0
 public ChatKonverzacija(ChatService _chatservis, string _GrupaPrimatelj)
 {
     BindingContext = viewModel = new ChatKonverzacijaViewModel(_chatservis, _GrupaPrimatelj);
     InitializeComponent();
 }
        public IEnumerable <string> Get(UserContactViewModel userContact)
        {
            var s = new ChatService();

            return(s.LoadMessages(userContact.Username, userContact.OtherUsernameEmail));
        }
Пример #25
0
        public ChatManager(HttpClient httpClient, ChatHistory chatHistory, SharkyOptions sharkyOptions, IChatDataService chatDataService, IEnemyPlayerService enemyPlayerManager, IEnemyNameService enemyNameService, ChatService chatService, ActiveChatData activeChatData)
        {
            HttpClient         = httpClient;
            ChatHistory        = chatHistory;
            SharkyOptions      = sharkyOptions;
            ChatDataService    = chatDataService;
            EnemyPlayerManager = enemyPlayerManager;
            EnemyNameService   = enemyNameService;
            ChatService        = chatService;
            ActiveChatData     = activeChatData;

            ApiEnabled = false;

            LastResponseTimes   = new Dictionary <TypeEnum, int>();
            ChatTypeFrequencies = new Dictionary <TypeEnum, int>();
            foreach (var chatType in Enum.GetValues(typeof(TypeEnum)).Cast <TypeEnum>())
            {
                ChatTypeFrequencies[chatType] = 3;
            }
        }
Пример #26
0
        /// <summary>
        /// Used to reserve a nick name.
        /// /nick nickname - sets the user's name to nick name or creates a user with that name
        /// /nick nickname password - sets a password for the specified nick name (if the current user has that nick name)
        /// /nick nickname password newpassword - updates the password for the specified nick name (if the current user has that nick name)
        /// </summary>
        private void HandleNick(string[] parts)
        {
            if (parts.Length == 1)
            {
                throw new InvalidOperationException("No nick specified!");
            }

            string userName = parts[1];

            if (String.IsNullOrWhiteSpace(userName))
            {
                throw new InvalidOperationException("No nick specified!");
            }

            string password = null;

            if (parts.Length > 2)
            {
                password = parts[2];
            }

            string newPassword = null;

            if (parts.Length > 3)
            {
                newPassword = parts[3];
            }

            // See if there is a current user
            ChatUser user = _repository.GetUserById(_userId);

            if (user == null && String.IsNullOrEmpty(newPassword))
            {
                user = _repository.GetUserByName(userName);

                // There's a user with the name specified
                if (user != null)
                {
                    if (String.IsNullOrEmpty(password))
                    {
                        ChatService.ThrowUserExists(userName);
                    }
                    else
                    {
                        // If there's no user but there's a password then authenticate the user
                        _chatService.AuthenticateUser(userName, password);

                        // Add this client to the list of clients for this user
                        _chatService.AddClient(user, _clientId);

                        // Initialize the returning user
                        _notificationService.LogOn(user, _clientId);
                    }
                }
                else
                {
                    // If there's no user add a new one
                    user = _chatService.AddUser(userName, _clientId, password);

                    // Notify the user that they're good to go!
                    _notificationService.OnUserCreated(user);
                }
            }
            else
            {
                if (String.IsNullOrEmpty(password))
                {
                    string oldUserName = user.Name;

                    // Change the user's name
                    _chatService.ChangeUserName(user, userName);

                    _notificationService.OnUserNameChanged(user, oldUserName, userName);
                }
                else
                {
                    // If the user specified a password, verify they own the nick
                    ChatUser targetUser = _repository.VerifyUser(userName);

                    // Make sure the current user and target user are the same
                    if (user != targetUser)
                    {
                        throw new InvalidOperationException("You can't set/change the password for a nickname you down own.");
                    }

                    if (String.IsNullOrEmpty(newPassword))
                    {
                        if (targetUser.HashedPassword == null)
                        {
                            _chatService.SetUserPassword(user, password);

                            _notificationService.SetPassword();
                        }
                        else
                        {
                            throw new InvalidOperationException("Use /nick [nickname] [oldpassword] [newpassword] to change and existing password.");
                        }
                    }
                    else
                    {
                        _chatService.ChangeUserPassword(user, password, newPassword);

                        _notificationService.ChangePassword();
                    }
                }
            }

            // Commit the changes
            _repository.CommitChanges();
        }
Пример #27
0
 // Dependencies are automatically injected via this constructor.
 // Remember to add an instance of the service.
 // to your IServiceCollection when you initialize your bot!
 public ChatModule(ChatService service)
 {
     m_Service = service;
     m_Service.SetParentModule(this); // Reference to this from the service.
 }
 public ProfileController(ProfileService service, GroupService groupService, UserService userService, ChatService chatService)
 {
     _service      = service;
     _groupService = groupService;
     _userService  = userService;
     _chatService  = chatService;
 }
Пример #29
0
        public RoomItem(ChatService chat, ChatRoom room, EventHandler onClick)
            : base(room.Title, null, onClick)
        {
            Room = room;

            if (!room.Active)
                ForeColor = Color.DimGray;
            else
                Text += " - " + room.GetActiveMembers(chat).ToString();
        }
Пример #30
0
        static async Task Main(string[] args)
        {
            var console  = new ConsoleWrapper();
            var deviceId = UserService.EnsureDeviceId();

            Console.WriteLine(" ");
            Console.Write(new string('=', Console.WindowWidth));
            Console.WriteLine("Chat Demo");
            Console.Write(new string('=', Console.WindowWidth));
            Console.WriteLine(" ");

            Uri url = new Uri("https://chat.devchamp.com");

            if (args.Length == 0 || !Uri.TryCreate(args[0], UriKind.Absolute, out url))
            {
                Console.WriteLine($"No server url supplied, using default {url}.");
            }

            var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return(true); }
            };

            var httpClient = new HttpClient(handler)
            {
                BaseAddress = url
            };

            httpClient.DefaultRequestHeaders.Add("device-id", deviceId);

            var citylineClient = CitylineFactory.Create(new Uri(url, "/api/cityline"), deviceId);

            var userService    = new UserService(console, citylineClient, httpClient);
            var channelService = new ChannelService(console, citylineClient, httpClient);
            var chatService    = new ChatService(console, citylineClient, httpClient, channelService);


            var _ = Task.Run(async() => await citylineClient.StartListening());

            await userService.Initialize();


            var __ = Task.Run(async() => {
                console.ClearLine();
                await citylineClient.GetFrame("sentences");
                await citylineClient.GetFrame("user-account");
                await citylineClient.GetFrame("channels");
                Console.WriteLine("Type /channel for channel-commands. /quit to quit.");
                channelService.Ready();
            });

            // a bug in readlinasync blocks everything, so we must spin up a task to avoid that
            await Task.Run(async() => {
                while (true)
                {
                    var line = await Console.In.ReadLineAsync();
                    await chatService.Parse(line);
                    await channelService.Parse(line);

                    if (line == "/quit")
                    {
                        break;
                    }
                }
            });
        }
Пример #31
0
        /// <summary>
        ///     Starts this instance.
        /// </summary>
        /// <returns>The task.</returns>
        public virtual async Task Start()
        {
            Logger.LogStart(">> Loading vocations");
            VocationXmlReader       vocationXmlReader = new VocationXmlReader();
            IEnumerable <IVocation> vocations         = await vocationXmlReader.LoadAsync(Settings.Default.Vocations_Xml);

            _vocationService = new VocationService(vocations);
            Logger.LogDone();

            Logger.LogStart(">> Loading items");
            ItemReader          itemReader = new ItemReader();
            IEnumerable <IItem> items      = await itemReader.LoadAsync(Settings.Default.Items_Otb);

            _itemService = new ItemService(items);
            ItemXmlReader itemXmlReader = new ItemXmlReader(_itemService);
            await itemXmlReader.LoadAsync(Settings.Default.Items_Xml);

            Logger.LogDone();

            Logger.LogStart(">> Loading spells");
            SpellXmlReader       spellXmlReader = new SpellXmlReader();
            IEnumerable <ISpell> spells         = await spellXmlReader.LoadAsync(Settings.Default.Spells_Xml);

            _spellService = new SpellService(spells);
            Logger.LogDone();

            Logger.LogStart(">> Loading monsters");
            MonsterXmlReader       monsterXmlReader = new MonsterXmlReader(_spellService);
            IEnumerable <IMonster> monsters         = await monsterXmlReader.LoadAsync(Settings.Default.Monsters_Xml);

            _monsterService = new MonsterService(monsters);
            Logger.LogDone();

            Logger.LogStart(">> Loading npcs");
            NpcXmlReader       npcXmlReader = new NpcXmlReader();
            IEnumerable <INpc> npcs         = await npcXmlReader.LoadAsync(Settings.Default.Npcs_Xml);

            _npcService = new NpcService(npcs);
            Logger.LogDone();

            Logger.LogStart(">> Loading map");
            MapReader mapReader = new MapReader(_itemService);
            WorldMap  map       = await mapReader.LoadAsync(Settings.Default.Map_Otb);

            Logger.LogDone();

            Logger.LogStart(">> Loading outfits");
            DrkOutfitReader       outfitReader = new DrkOutfitReader();
            IEnumerable <IOutfit> outfits      = await outfitReader.LoadAsync(Settings.Default.Outfits_Xml);

            _outfitService = new OutfitService(outfits);
            Logger.LogDone();

            Logger.LogStart(">> Loading mounts");
            DrkMountReader       mountReader = new DrkMountReader();
            IEnumerable <IMount> mounts      = await mountReader.LoadAsync(Settings.Default.Mounts_Xml);

            _mountService = new MountService(mounts);
            Logger.LogDone();

            Logger.LogStart(">> Loading channels");
            // TODO: Channels are broken. They should be handled by a category like ChannelType (e.g.: Public, Private, Guild, Party, etc.), then each category has an ID
            // TODO: Eventually loading channels this away should be replaced.
            // TODO Alternatively, we could move the specific implementation of LocalChannel to a scripting language (like Lua)
            // TODO: This could be also converted into a more modular approach (like a CS-Script)
            IDictionary <ChannelType, IChannel> channels = new Dictionary <ChannelType, IChannel>();

            channels.Add(ChannelType.Local, new LocalChannel());
            channels.Add(ChannelType.Loot, new LootChannel());
            channels.Add(ChannelType.Advertising, new AdvertisingChannel());
            channels.Add(ChannelType.AdvertisingRookgaard, new AdvertisingRookgaardChannel());
            channels.Add(ChannelType.English, new EnglishChannel());
            channels.Add(ChannelType.Help, new HelpChannel());
            channels.Add(ChannelType.World, new WorldChannel());
            Logger.LogDone();

            Logger.LogStart(">> Initializing town services");
            _townService = new TownService(map.Towns.Values);
            Logger.LogDone();

            Logger.LogStart(">> Initializing tile services");
            _tileService = new TileService(map.Tiles.Values);
            Logger.LogDone();

            // TODO: Remove this after project is complete
            InitializeTest();

            Logger.LogStart(">> Initializing repositories");
            _accountsRepository = new Repository <IAccount, uint>();

            // TODO: Remove this when repositories are implemented
            _accountsRepository.Create(_characterSpawn.Account);
            Logger.LogDone();

            Logger.LogStart(">> Initializing spawn services");
            SpawnXmlReader            spawnXmlReader = new SpawnXmlReader(_monsterService, _npcService);
            ICollection <SpawnSource> spawnSources   = (await spawnXmlReader.LoadAsync(Settings.Default.Spawns_Xml)).ToList();

            _creatureSpawnService = new CreatureSpawnService(spawnSources);
            RegisterSpawns(spawnSources);
            // TODO: Remove this when player repositories are implemented;
            _creatureSpawnService.RegisterCreature(_characterSpawn);
            Logger.LogDone();

            Logger.LogStart(">> Initializing communication services");
            _chatService    = new ChatService(_accountsRepository.GetAll(), channels);
            _commandService = new CommandService();
            _commandService.Register(new TeleportCommand(_townService, _creatureSpawnService));
            _commandService.Register(new TownListCommand(_townService));
            _commandService.Register(new PositionInfoCommand());
            _commandService.Register(new ChangeSexCommand());
            _commandService.Register(new BroadcastCommand(_creatureSpawnService));
            Logger.LogDone();

            Logger.LogStart(">> Initializing game server");
            _gameConnections = new List <GameConnection>();
            _gameListener    = new TcpListener(IPAddress.Any, Settings.Default.Network_Port_GameServer);
            _gameListener.Start();
            _gameListener.BeginAcceptSocket(OnGameMessageReceived, _gameListener);
            Logger.LogDone();

            Logger.LogStart(">> Initializing login server");
            _loginConnections = new List <LoginConnection>();
            _loginListener    = new TcpListener(IPAddress.Any, Settings.Default.Network_Port_LoginServer);
            _loginListener.Start();
            _loginListener.BeginAcceptSocket(OnLoginMessageReceived, _loginListener);
            Logger.LogDone();

            _onlineTimer = new Stopwatch();
        }
Пример #32
0
 public ChatController(IHubContext <ChatHub> chatHub, ChatService chatService)
 {
     _chatService = chatService;
     _chatHub     = new ChatHubHelper(chatHub);
 }
Пример #33
0
 public ChatController(ChatService ChatService)
 {
     _ChatService = ChatService;
 }
Пример #34
0
 public ChatController(ChatService chatService)
 {
     _chatService = chatService;
 }
Пример #35
0
        private static void RunServer()
        {
            Data.Data.DataPath = "data/";

            Stopwatch sw = Stopwatch.StartNew();

            AppDomain.CurrentDomain.UnhandledException += UnhandledException;

            Console.WriteLine("----===== Tera-Project C# GameServer Emulator =====----\n\n");
            Console.WriteLine("Starting Game Server!\n"
                              + "-------------------------------------------");

            TcpServer = new TcpServer("*", Config.GetServerPort(), Config.GetServerMaxCon());
            Connection.SendAllThread.Start();

            OpCodes.Init();
            Console.WriteLine("OpCodes - Revision 1725 initialized!\n"
                              + "-------------------------------------------\n");

            #region global_components

            //services
            FeedbackService    = new FeedbackService();
            AccountService     = new AccountService();
            PlayerService      = new PlayerService();
            MapService         = new MapService();
            ChatService        = new ChatService();
            VisibleService     = new VisibleService();
            ControllerService  = new ControllerService();
            CraftService       = new CraftService();
            ItemService        = new ItemService();
            AiService          = new AiService();
            GeoService         = new GeoService();
            StatsService       = new StatsService();
            ObserverService    = new ObserverService();
            AreaService        = new AreaService();
            InformerService    = new InformerService();
            TeleportService    = new TeleportService();
            PartyService       = new PartyService();
            SkillsLearnService = new SkillsLearnService();
            CraftLearnService  = new CraftLearnService();
            GuildService       = new GuildService();
            EmotionService     = new EmotionService();
            RelationService    = new RelationService();
            DuelService        = new DuelService();
            StorageService     = new StorageService();
            TradeService       = new TradeService();
            MountService       = new MountService();

            //engines
            ActionEngine = new ActionEngine.ActionEngine();
            AdminEngine  = new AdminEngine.AdminEngine();
            SkillEngine  = new SkillEngine.SkillEngine();
            QuestEngine  = new QuestEngine.QuestEngine();

            #endregion

            GlobalLogic.ServerStart("SERVER=" + Config.GetDatabaseHost() + ";DATABASE=" + Config.GetDatabaseName() + ";UID=" + Config.GetDatabaseUser() + ";PASSWORD="******";PORT=" + Config.GetDatabasePort() + ";charset=utf8");

            Console.WriteLine("-------------------------------------------\n"
                              + "Loading Tcp Service.\n"
                              + "-------------------------------------------");
            TcpServer.BeginListening();

            try
            {
                ServiceApplication = ScsServiceBuilder.CreateService(new ScsTcpEndPoint(23232));
                ServiceApplication.AddService <IInformerService, InformerService>((InformerService)InformerService);
                ServiceApplication.Start();
                Log.Info("InformerService started at *:23232.");

                var webservices = new ServiceManager();
                webservices.Run();
            }
            catch (Exception ex)
            {
                Log.ErrorException("InformerService can not be started.", ex);
            }

            sw.Stop();
            Console.WriteLine("-------------------------------------------");
            Console.WriteLine("           Server start in {0}", (sw.ElapsedMilliseconds / 1000.0).ToString("0.00s"));
            Console.WriteLine("-------------------------------------------");
        }
Пример #36
0
        private void RegisterMessageHandlers()
        {
            // TODO: Remove possibility for circular dependencies in the future
            // by emitting these events so other services can listen for them.

            HubConnection.On("Chat", async(string message, string orgName, string senderConnectionID) => {
                await ChatService.SendMessage(message, orgName, senderConnectionID, HubConnection);
            });
            HubConnection.On("DownloadFile", async(string filePath, string senderConnectionID) =>
            {
                filePath = filePath.Replace("\"", "");
                if (!File.Exists(filePath))
                {
                    await HubConnection.SendAsync("DisplayMessage", "File not found on remote device.", "File not found.", senderConnectionID);
                    return;
                }
                var wr       = WebRequest.CreateHttp($"{ConnectionInfo.Host}/API/FileSharing/");
                var wc       = new WebClient();
                var response = await wc.UploadFileTaskAsync($"{ConnectionInfo.Host}/API/FileSharing/", filePath);
                var fileIDs  = JsonSerializer.Deserialize <string[]>(Encoding.UTF8.GetString(response));
                await HubConnection.SendAsync("DownloadFile", fileIDs[0], senderConnectionID);
            });
            HubConnection.On("ChangeWindowsSession", async(string serviceID, string viewerID, int targetSessionID) =>
            {
                await AppLauncher.RestartScreenCaster(new List <string>()
                {
                    viewerID
                }, serviceID, viewerID, HubConnection, targetSessionID);
            });
            HubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderConnectionID}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await CommandExecutor.ExecuteCommand(mode, command, commandID, senderConnectionID, HubConnection);
            }));
            HubConnection.On("ExecuteCommandFromApi", (async(string mode, string requestID, string command, string commandID, string senderUserName) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderUserName}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await CommandExecutor.ExecuteCommandFromApi(mode, requestID, command, commandID, senderUserName, HubConnection);
            }));
            HubConnection.On("UploadFiles", async(string transferID, List <string> fileIDs, string requesterID) =>
            {
                Logger.Write($"File upload started by {requesterID}.");
                var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName;

                foreach (var fileID in fileIDs)
                {
                    var url      = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}";
                    var wr       = WebRequest.CreateHttp(url);
                    var response = await wr.GetResponseAsync();
                    var cd       = response.Headers["Content-Disposition"];
                    var filename = cd
                                   .Split(";")
                                   .FirstOrDefault(x => x.Trim()
                                                   .StartsWith("filename"))
                                   .Split("=")[1];

                    var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    filename = new string(legalChars.ToArray());

                    using (var rs = response.GetResponseStream())
                    {
                        using (var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create))
                        {
                            rs.CopyTo(fs);
                        }
                    }
                }
                await this.HubConnection.SendAsync("TransferCompleted", transferID, requesterID);
            });
            HubConnection.On("DeployScript", async(string mode, string fileID, string commandResultID, string requesterID) => {
                if (!IsServerVerified)
                {
                    Logger.Write($"Script deploy attempted before server was verified.  Mode: {mode}.  File ID: {fileID}.  Sender: {requesterID}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await ScriptRunner.RunScript(mode, fileID, commandResultID, requesterID, HubConnection);
            });
            HubConnection.On("UninstallClient", () =>
            {
                Uninstaller.UninstallAgent();
            });

            HubConnection.On("RemoteControl", async(string requesterID, string serviceID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.");
                    Uninstaller.UninstallAgent();
                    return;
                }
                await AppLauncher.LaunchRemoteControl(-1, requesterID, serviceID, HubConnection);
            });
            HubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.");
                    Uninstaller.UninstallAgent();
                    return;
                }
                await AppLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, HubConnection);
            });
            HubConnection.On("CtrlAltDel", () =>
            {
                User32.SendSAS(false);
            });

            HubConnection.On("ServerVerificationToken", (string verificationToken) =>
            {
                if (verificationToken == ConnectionInfo.ServerVerificationToken)
                {
                    IsServerVerified = true;
                }
                else
                {
                    Logger.Write($"Server sent an incorrect verification token.  Token Sent: {verificationToken}.");
                    Uninstaller.UninstallAgent();
                    return;
                }
            });
        }
Пример #37
0
        private void RemoveUser(Game game)
        {
            DateTimeOffset         time     = dateTimeNow - _UserLiveTime;
            IEnumerable <GameUser> userList = game.GameUser.Where(p => !string.IsNullOrEmpty(p.Login) && p.Login != "Вестерос" && p.LastUpdate < time);

            //лишаем лордства неактивных
            foreach (GameUser user in userList.ToList())
            {
                //лорды
                if (!string.IsNullOrEmpty(user.HomeType))
                {
                    WCFUser profile = GamePortalServer.GetProfileByLogin(user.Login);
                    //                    bool hasVaule = _DeniedLogin.TryGetValue(user.Login, out int oldLiaveCount);
                    //                    int newLiaveCount = game.OpenTime == null ? GameHost.MaxLiaveCount + 1 : oldLiaveCount + 1;
                    //#if !DEBUG
                    //                    if (!hasVaule) _DeniedLogin.TryAdd(user.Login, newLiaveCount);
                    //                    else _DeniedLogin.TryUpdate(user.Login, newLiaveCount, oldLiaveCount);
                    //#endif
                    if (game.OpenTime != null)
                    {
                        GamePortalServer.StopUserGame(user.Login, game.Id, 0, royalPardon);
                    }
                    else
                    {
                        GameHost.AddUserNotifiFunc(profile, $"dynamic_leftGame1*unknown home");//{user.HomeType}
                    }
                    string whois      = profile == null ? user.Login : profile.Api["FIO"];
                    int    liaveCount = profile.UserGames.Count(p => p.GameId == this.GameId && p.EndTime.HasValue && !p.IsIgnoreHonor);
                    if (liaveCount > GameHost.MaxLiaveCount)
                    {
                        ChatService.AddChat(new Chat()
                        {
                            Creator = "Вестерос", Message = $"dynamic_Exile*homeType_{user.HomeType}*Faceless Men"
                        });                                                                                                                        //{whois}
                    }
                    else if (game.OpenTime != null)
                    {
                        ChatService.AddChat(new Chat()
                        {
                            Creator = "Вестерос", Message = $"dynamic_leftGame*homeType_{user.HomeType}*Faceless Men*{GameHost.MaxLiaveCount - liaveCount + 1}"
                        });                                                                                                                                                                     //{whois}
                    }
                    user.Login = null;

                    //сообщаем что требуется замена
                    if (game.OpenTime != null)
                    {
                        GameHost.AddGameNotifiFunc(game.ToWCFGame());
                    }
                }
                //наблюдателей удаляем
                else
                {
                    game.DbContext.GameUser.Remove(user);
                }
            }

            royalPardon = false;

            //если партию покинули все игроки
            if (game.HomeUsersSL.All(p => p.Login == null))
            {
                game.CloseTime = dateTimeNow;
            }
        }
Пример #38
0
 public ChatHub(ChatService chatService)
 {
     _chatService = chatService;
 }
Пример #39
0
 public ChatHub(ChatService chatService)
 {
 }
Пример #40
0
 public ProtossSharkyBuild(BuildOptions buildOptions, MacroData macroData, ActiveUnitData activeUnitData, AttackData attackData, ChatService chatService, ChronoData chronoData, ICounterTransitioner counterTransitioner, UnitCountService unitCountService, MicroTaskData microTaskData)
     : base(buildOptions, macroData, activeUnitData, attackData, microTaskData, chatService, unitCountService)
 {
     ChronoData          = chronoData;
     CounterTransitioner = counterTransitioner;
 }
Пример #41
0
 public LobbyViewModel()
 {
     Rooms = ChatService.GetRooms();
 }