public async Task <MessengerResponse> SendAsync(MessengerMessage message, MessengerUser recipient, String accessToken)
        {
            var url     = String.Format(UrlTemplate, accessToken);
            var request = new MessengerSendMessageRequest {
                Recipient = recipient, Message = message
            };

            var content = new StringContent(serializer.Serialize(request));

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                var response = await client.PostAsync(url, content);

                var result = new MessengerResponse
                {
                    Succeed     = response.IsSuccessStatusCode,
                    RawResponse = await response.Content.ReadAsStringAsync()
                };

                return(result);
            }
            catch (Exception exc)
            {
                throw new MessengerException(exc);
            }
        }
Exemplo n.º 2
0
        public void Handle(Player player, Request request)
        {
            int friendsAccepted = request.ReadInt();
            var messenger       = player.Messenger;

            for (int i = 0; i < friendsAccepted; i++)
            {
                int userId = request.ReadInt();

                if (!messenger.HasRequest(userId))
                {
                    continue;
                }

                if (messenger.Friends.Count >= messenger.MaxFriendsAllowed)
                {
                    continue;
                }

                var playerData = PlayerManager.Instance.GetDataById(userId);

                if (playerData == null)
                {
                    continue;
                }

                var targetMessenger = Messenger.GetMessengerData(userId);
                var targetFriend    = new MessengerUser(playerData);

                targetMessenger.Friends.Add(messenger.MessengerUser);
                messenger.Friends.Add(targetFriend);

                targetMessenger.RemoveRequest(player.Details.Id);
                messenger.RemoveRequest(userId);

                var targetPlayer = PlayerManager.Instance.GetPlayerById(userId);

                if (targetPlayer != null)
                {
                    targetPlayer.Messenger.QueueUpdate(MessengerUpdateType.AddFriend, messenger.MessengerUser);
                    targetPlayer.Messenger.ForceUpdate();
                }

                MessengerDao.DeleteRequests(player.Details.Id, userId);
                MessengerDao.SaveFriend(new MessengerFriendData
                {
                    FriendId = userId,
                    UserId   = player.Details.Id
                });
                MessengerDao.SaveFriend(new MessengerFriendData
                {
                    UserId   = userId,
                    FriendId = player.Details.Id
                });

                messenger.QueueUpdate(MessengerUpdateType.AddFriend, targetFriend);
            }

            messenger.ForceUpdate();
        }
Exemplo n.º 3
0
        public IActionResult UploadImage(MessengerUser user, string userid)
        {
            user = _context.User.FirstOrDefault(o => o.Id == userid);
            if (user.Id != null)
            {
                foreach (var file in Request.Form.Files)
                {
                    var img = new Image {
                        UserID = user.Id, ImageTitle = file.FileName
                    };

                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        img.ImageData = ms.ToArray();
                        ms.Close();
                        ms.Dispose();
                    }

                    _context.SaveImage(img);
                }

                TempData["message"] = "Image(s) stored in  database!";
            }
            else
            {
                TempData["message"] = "Cannot add images to a non existent product!";
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <param name="sender">The messenger user.</param>
        /// <returns>A task.</returns>
        public async Task <User> GetUserAsync(MessengerUser sender)
        {
            var user = await this.Processor.UserRepository.GetAsync(sender.Id);

            if (user == null)
            {
                var profileResponse = await new MessengerProfileProvider(
                    new JsonMessengerSerializer()).GetUserProfileAsync(sender.Id);
                var profile = profileResponse.Result;

                if (!string.IsNullOrEmpty(profile.FirstName))
                {
                    user = new User
                    {
                        FirstName = profile.FirstName,
                        UserId    = sender.Id
                    };

                    user = await this.Processor.UserRepository.InsertAsync(user);

                    await this.SendTextAsync(sender, $"Hi {profile.FirstName}", 500);

                    if (profile.Gender == "female")
                    {
                        await this.SendTextAsync(sender, $"finally a girl ☺, boys pictures are so boring :/");
                    }
                }
            }
            else
            {
                user = await this.Processor.UserRepository.UpdateAsync(user);
            }

            return(user);
        }
Exemplo n.º 5
0
        private static void TriggerAlerts(string source, string target, Models.Rate rate90, Models.Rate rate4, Models.Rate rateRsi, Models.Rate last)
        {
            MessengerMessageSender  sender     = new MessengerMessageSender(new JsonMessengerSerializer());
            ConfigurationRepository repository = new ConfigurationRepository();

            //if (rateRsi.Value < 30)
            {
                var configs = repository.Get().Result;
                foreach (var config in configs)
                {
                    if (config.Source == source && config.Target == target)
                    {
                        var userId    = config.FacebookId;
                        var recipient = new MessengerUser();
                        recipient.Id = userId;
                        var configId = config.Id.ToString();
                        var response = new MessengerMessage();
                        response.Attachment         = new MessengerAttachment();
                        response.Attachment.Type    = "template";
                        response.Attachment.Payload = new MessengerPayload();
                        response.Attachment.Payload.TemplateType = "button";
                        response.Attachment.Payload.Text         = $"hi, we have found a good rate for your transfer: {source} to {target} is now {last.Value}. Tap the button below to do the transfer";
                        response.Attachment.Payload.Buttons      = new List <MessengerButton>();
                        var linkButton = new MessengerButton();
                        linkButton.Url   = $"https://transfer-buddy.herokuapp.com/Transfers/Create?configId={config.Id}";
                        linkButton.Title = "Transfer";
                        linkButton.Type  = "web_url";
                        response.Attachment.Payload.Buttons.Add(linkButton);
                        sender.SendAsync(response, recipient, "EAAaZCDGRPBJ4BAMVFRSRvqM8ytvC6ZAZCryE6xw5GImYZByvVpkIDhSpltas8CuclkcqZClTneXVzwMQqTeZCS5Gs3lf0sCLpiy977fg6bkGuNEESUysoPKKeJNGuW9WDZARKRw45J14A9BcustEzBsIvmbrUZCtVgZAohzKtG0w5DgZDZD").Wait();
                    }
                }
            }
        }
Exemplo n.º 6
0
 public MessagesDeliveredEventArgs(MessengerUser user, IReadOnlyList <MessengerMessage> messages, MessengerThread thread, DateTime at)
 {
     User     = user;
     Messages = messages;
     Thread   = thread;
     At       = at;
 }
Exemplo n.º 7
0
        public async Task <MessengerResponse> SendAsync(MessengerMessage message, MessengerUser recipient, String accessToken)
        {
            var url     = String.Format(UrlTemplate, accessToken);
            var request = new MessengerSendMessageRequest {
                Recipient = recipient, Message = message
            };
            var strings = serializer.Serialize(request);

#if DEBUG
            System.Console.WriteLine(strings);
#endif

            /*if (message.Attachments != null && message.Attachments.Count > 0)
             *  throw new Exception(strings);*/

            var content = new StringContent(strings);

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                var response = await client.PostAsync(url, content);

                var result = new MessengerResponse
                {
                    Succeed     = response.IsSuccessStatusCode,
                    RawResponse = await response.Content.ReadAsStringAsync()
                };

                return(result);
            }
            catch (Exception exc)
            {
                throw new MessengerException(exc);
            }
        }
 public MessageUnsentEventArgs(MessengerUser user, MessengerMessage message, MessengerThread thread, DateTime at)
 {
     User    = user;
     Message = message;
     Thread  = thread;
     At      = at;
 }
Exemplo n.º 9
0
        /// <summary>
        /// Sends text to the user.
        /// </summary>
        /// <param name="recipient">The messenger user.</param>
        /// <param name="text">The text.</param>
        /// <returns>A task.</returns>
        public async Task SendTextAsync(MessengerUser recipient, string text)
        {
            var response = new MessengerMessage {
                Text = text
            };

            await this.Processor.MessageSender.SendAsync(response, recipient);
        }
Exemplo n.º 10
0
        public Task <MessengerResponse> SendAsync(MessengerMessage message, MessengerUser recipient, String accessToken)
        {
            var request = new MessengerSendMessageRequest {
                Recipient = recipient, Message = message
            };

            return(SendMessage(request, accessToken));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Sends a picture to the user.
        /// </summary>
        /// <param name="recipient">The messenger user.</param>
        /// <param name="url">The picture url.</param>
        /// <returns>A task.</returns>
        public async Task SendPictureAsync(MessengerUser recipient, string url)
        {
            var response = new MessengerMessage();

            response.Attachment             = new MessengerAttachment();
            response.Attachment.Type        = "image";
            response.Attachment.Payload     = new MessengerPayload();
            response.Attachment.Payload.Url = url;
            await this.Processor.MessageSender.SendAsync(response, recipient);
        }
Exemplo n.º 12
0
        public async Task <bool> SendEncryptedTextAsync(MessengerUser user, string text)
        {
            var encrypted = await gpg.EncryptAsync(text, user.Id);

            if (string.IsNullOrEmpty(encrypted))
            {
                return(false);
            }
            return(await messenger.SendTextAsync(user, encrypted));
        }
Exemplo n.º 13
0
        public async Task <string> GetPublicKeyAsync(MessengerUser user)
        {
            const string pattern  = "-----BEGIN PGP PUBLIC KEY BLOCK-----";
            var          messages = await messenger.SearchThreadAsync(user, pattern, 50);

            return(messages
                   .Where(m => m.AuthorId == user.Id)
                   .OrderByDescending(m => m.Timestamp)
                   .Select(m => pgpHelper.GetPublicKeyBlock(m.Text))
                   .FirstOrDefault(s => !string.IsNullOrEmpty(s)));
        }
Exemplo n.º 14
0
        private async Task <GpgKey> GetKeyAsync(MessengerUser user, bool secret = false)
        {
            var keys = secret ? PrivateKeys : PublicKeys;

            if (keys == null)
            {
                await RefreshKeys(secret);
            }
            keys = secret ? PrivateKeys : PublicKeys;

            return(keys.FirstOrDefault(k => k.UserId == user.Id));
        }
Exemplo n.º 15
0
 private void Serialise(MessengerUser user)
 {
     m_Data.Add(user.PlayerData.Id);
     m_Data.Add(user.PlayerData.Name);
     m_Data.Add(user.PlayerData.Motto);
     m_Data.Add(user.IsOnline);
     m_Data.Add(false);
     m_Data.Add(string.Empty);
     m_Data.Add(0);
     m_Data.Add(user.PlayerData.Figure);
     m_Data.Add(user.PlayerData.LastOnline.ToString("MM-dd-yyyy HH:mm:ss"));
 }
Exemplo n.º 16
0
        public async Task <IActionResult> AddQuote(MessengerUser user, string text)
        {
            if (ModelState.IsValid)
            {
                user       = _context.User.First(u => u.UserName == User.Identity.Name);
                user.Quote = text;
                await _context.SaveChangesAsync();

                return(RedirectToAction("Profile"));
            }
            return(Error());
        }
Exemplo n.º 17
0
        public IActionResult Create(TransferConfig config)
        {
            CreateTransfer(config).Wait();

            MessengerMessage message = new MessengerMessage();

            message.Text = "the transfer was completed successfully :)";
            MessengerUser user = new MessengerUser();

            user.Id = config.FacebookId;

            var result = messengerService.MessageSender.SendAsync(message, user).Result;

            return(RedirectToAction("TransferSuccess"));
        }
Exemplo n.º 18
0
        public string GetCurrentUser()
        {
            using (var context = serviceProvider.GetService <SlideInfoDbContext>())
            {
                var currentUser   = context.AppUsers.FirstOrDefault(u => u.UserName == userManager.GetUserName(User));
                var messengerUser = new MessengerUser
                {
                    Id       = currentUser?.Id,
                    FullName = currentUser?.FullName,
                    Email    = currentUser?.Email
                };

                return(JsonConvert.SerializeObject(messengerUser));
            }
        }
Exemplo n.º 19
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new MessengerUser {
                    UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 20
0
        private MessengerUser GetUser(FB_User author)
        {
            if (author == null)
            {
                return(null);
            }

            var user = GetUser(author.uid);

            if (user == null)
            {
                user = new MessengerUser(author);
                users.Add(user);
            }

            return(user);
        }
Exemplo n.º 21
0
        public async Task <bool> ImportPublicKeyAsync(MessengerUser user)
        {
            var publicKey = await GetPublicKeyAsync(user);

            if (string.IsNullOrEmpty(publicKey))
            {
                return(false);
            }
            var result = await gpg.ImportKeyAsync(publicKey);

            if (!result)
            {
                return(false);
            }

            await RefreshKeys();

            return(true);
        }
Exemplo n.º 22
0
        public async override Task OnConnectedAsync()
        {
            await Clients.Caller.SendAsync("GetUsers", OnlineUsers);

            var user = _userManager.GetUserAsync(Context.User).Result;

            if (OnlineUsers.FirstOrDefault(x => x.userName == user.UserName) != null)
            {
                return;
            }

            var newMessengerUser = new MessengerUser {
                connectionId = Context.ConnectionId, userName = user.UserName
            };

            await SendNewConnectedUser(newMessengerUser);

            OnlineUsers.Add(newMessengerUser);
        }
Exemplo n.º 23
0
        public async Task <bool> LoginAsync()
        {
            session = await messenger.TryLogin();

            if (session == null)
            {
                var(email, password) = await OnUserLoginRequestedAsync();

                session = await messenger.DoLogin(email, password);
            }

            if (!await CheckConnectionStateAsync())
            {
                return(false);
            }

            await messenger.StartListening();

            Self = new MessengerUser(await messenger.fetchProfile());
            await UpdateUsersAsync();

            return(true);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Seds a button to the user.
        /// </summary>
        /// <param name="recipient">The messenger user.</param>
        /// <param name="text">The text.</param>
        /// <param name="buttons">The buttons.</param>
        /// <returns>A task.</returns>
        public async Task SendTextWithButtonsAsync(MessengerUser recipient, string text, IEnumerable <MessengerButtonBase> buttons)
        {
            var response = new MessengerMessage();

            response.Attachment         = new MessengerAttachment();
            response.Attachment.Type    = "template";
            response.Attachment.Payload = new MessengerPayload();
            response.Attachment.Payload.TemplateType = "button";
            response.Attachment.Payload.Text         = text;
            response.Attachment.Payload.Buttons      = new List <MessengerButton>();

            foreach (var button in buttons)
            {
                var payloadButton = new MessengerButton();

                if (button is MessengerLinkButton)
                {
                    var linkButton = button as MessengerLinkButton;
                    payloadButton.Url   = linkButton.Url;
                    payloadButton.Title = linkButton.Title;
                    payloadButton.Type  = linkButton.Type;
                }

                if (button is MessengerChatButton)
                {
                    var chatButton = button as MessengerChatButton;
                    payloadButton.Payload = chatButton.Payload;
                    payloadButton.Title   = chatButton.Title;
                    payloadButton.Type    = chatButton.Type;
                }

                response.Attachment.Payload.Buttons.Add(payloadButton);
            }

            await this.Processor.MessageSender.SendAsync(response, recipient);
        }
Exemplo n.º 25
0
 public EncryptedMessageReceivedEventArgs(string decryptedText, MessengerUser user, MessengerMessage message, MessengerMessage replyTo = null)
     : base(user, message, replyTo)
 {
     DecryptedText = decryptedText;
 }
 public MessageReceivedEventArgs(MessengerUser user, MessengerMessage message, MessengerMessage replyTo = null)
 {
     User    = user;
     Message = message;
     ReplyTo = replyTo;
 }
Exemplo n.º 27
0
        public Task <MessengerResponse> SetSenderActionAsync(MessengerSenderAction senderAction, MessengerUser recipient, string accessToken)
        {
            var request = new MessengerSenderActionRequest {
                Recipient = recipient, SenderAction = senderAction
            };

            return(SendMessage(request, accessToken));
        }
Exemplo n.º 28
0
 public Task <MessengerResponse> SetSenderActionAsync(MessengerSenderAction senderAction, MessengerUser recipient)
 {
     return(SetSenderActionAsync(senderAction, recipient, MessengerConfig.AccessToken));
 }
Exemplo n.º 29
0
 public Task <MessengerResponse> SendAsync(MessengerMessage message, MessengerUser recipient)
 {
     return(SendAsync(message, recipient, MessengerConfig.AccessToken));
 }
Exemplo n.º 30
0
 public async Task <string> LoadPublicKeyAsync(MessengerUser user)
 {
     return(await gpg.ExportKeyAsync(user.Id));
 }