예제 #1
0
        public SendResponse Dispatch(INoticeMessage message, string senderName)
        {
            var response = new SendResponse(message, senderName, SendResult.OK);

            if (!logOnly)
            {
                var sender = context.NotifyService.GetSender(senderName);
                if (sender != null)
                {
                    response = sender.DirectSend(message);
                }
                else
                {
                    response = new SendResponse(message, senderName, SendResult.Impossible);
                }

                LogResponce(message, response, sender != null ? sender.SenderName : string.Empty);
            }
            LogMessage(message, senderName);
            return(response);
        }
예제 #2
0
        /// <summary>
        /// Send the specified email.
        /// </summary>
        /// <returns>A response with any errors and a success boolean.</returns>
        /// <param name="email">Email.</param>
        /// <param name="token">Cancellation Token.</param>
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var response = new SendResponse();
            var message  = CreateMailMessage(email);

            if (token?.IsCancellationRequested ?? false)
            {
                response.ErrorMessages.Add("Message was cancelled by cancellation token.");
                return(response);
            }

            try
            {
                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync(
                        _smtpClientOptions.Server,
                        _smtpClientOptions.Port,
                        _smtpClientOptions.SocketOptions,
                        token.GetValueOrDefault());

                    // Note: only needed if the SMTP server requires authentication
                    if (!string.IsNullOrEmpty(_smtpClientOptions.UserName))
                    {
                        await client.AuthenticateAsync(_smtpClientOptions.UserName, _smtpClientOptions.Password,
                                                       token.GetValueOrDefault());
                    }

                    await client.SendAsync(message, token.GetValueOrDefault());

                    await client.DisconnectAsync(true, token.GetValueOrDefault());
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessages.Add(ex.Message);
            }

            return(response);
        }
예제 #3
0
        public Task <SendResponse> SendAsync(Email email, CancellationToken?token = null)
        {
            var client = new RestClient($"https://api.mailgun.net/v3/{_domainName}");

            client.Authenticator = new HttpBasicAuthenticator("api", _apiKey);

            var request = new RestRequest("messages", Method.POST);

            request.AddParameter("from", $"{email.Data.FromAddress.Name} <{email.Data.FromAddress.EmailAddress}>");
            email.Data.ToAddresses.ForEach(x => {
                request.AddParameter("to", $"{x.Name} <{x.EmailAddress}>");
            });
            email.Data.CcAddresses.ForEach(x => {
                request.AddParameter("cc", $"{x.Name} <{x.EmailAddress}>");
            });
            email.Data.BccAddresses.ForEach(x => {
                request.AddParameter("bcc", $"{x.Name} <{x.EmailAddress}>");
            });
            request.AddParameter("subject", email.Data.Subject);

            request.AddParameter(email.Data.IsHtml ? "html" : "text", email.Data.Body);

            return(Task.Run(() =>
            {
                var t = new TaskCompletionSource <SendResponse>();

                var handle = client.ExecuteAsync <MailgunResponse>(request, response =>
                {
                    var result = new SendResponse();
                    if (string.IsNullOrEmpty(response.Data.Id))
                    {
                        result.ErrorMessages.Add(response.Data.Message);
                    }
                    t.TrySetResult(result);
                });

                return t.Task;
            }));
        }
예제 #4
0
        public SendResponse Dispatch(INoticeMessage message, string senderName)
        {
            var response = new SendResponse(message, senderName, SendResult.OK);

            if (!logOnly)
            {
                if (context.SenderHolder.GetSender(senderName) != null)
                {
                    var request = new DispatchRequest(message, context.SenderHolder.GetSender(senderName), (n, r) => response = r)
                    {
                        SendAttemptInterval = sendAttemptInterval,
                    };
                    DispatchExecutor(request);
                }
                else
                {
                    response = new SendResponse(message, senderName, SendResult.Impossible);
                }
            }
            LogMessage(message, senderName);
            return(response);
        }
예제 #5
0
        public override SendResponse ProcessMessage(INoticeMessage message)
        {
            if (message.Recipient.Addresses == null || message.Recipient.Addresses.Length == 0)
            {
                return(new SendResponse(message, senderName, SendResult.IncorrectRecipient));
            }

            var responce = new SendResponse(message, senderName, default(SendResult));

            try
            {
                var m      = CreateNotifyMessage(message);
                var result = sender.Send(m);

                switch (result)
                {
                case NoticeSendResult.TryOnceAgain:
                    responce.Result = SendResult.Inprogress;
                    break;

                case NoticeSendResult.MessageIncorrect:
                    responce.Result = SendResult.IncorrectRecipient;
                    break;

                case NoticeSendResult.SendingImpossible:
                    responce.Result = SendResult.Impossible;
                    break;

                default:
                    responce.Result = SendResult.OK;
                    break;
                }
                return(responce);
            }
            catch (Exception e)
            {
                return(new SendResponse(message, senderName, e));
            }
        }
예제 #6
0
        public async Task <SendResponse> SendEmail(EmailContent content)
        {
            if (content == null || _credentials == null)
            {
                return(SendResponse.SendFailed("Email failed to send."));
            }

            try
            {
                var email      = ConstructEmail(content);
                var smtpClient = await ConstructClient();

                await smtpClient.SendAsync(email);

                await smtpClient.DisconnectAsync(true);

                return(SendResponse.SendSuccess("Email sent successfully."));
            }
            catch (Exception ex)
            {
                return(SendResponse.SendFailed($"Email failed to send. {ex}"));
            }
        }
예제 #7
0
 public async Task <JsonResult> LogoutOther(User lout)
 {
     try
     {
         DataTable dt = _userLogic.logout_signalr(lout);
         if (dt.Rows.Count > 0 && dt.Columns.Contains("connection_id"))
         {
             SendResponse sendResponse = new SendResponse()
             {
                 Action  = "Logout",
                 Message = "Logout Your device"
             };
             for (int i = 0; i < dt.Rows.Count; i++)
             {
                 _hub.Clients.Client(dt.Rows[i]["connection_id"].ToString()).SendAsync("logoutAllDevices", sendResponse);
             }
         }
         return(new JsonResult(dt));
     }
     catch (Exception ee)
     {
         return(await _userLogic.SendRespose("False", ee.Message).ConfigureAwait(false));
     }
 }
예제 #8
0
        public static SendResponse SendPinna(string requestUri, string method, string userAgent, CookieContainer cookieContainer,
                                             byte[] data, string host, string accept, string referer = "", string contentType = "", string xml = "")
        {
            ServicePointManager.ServerCertificateValidationCallback =
                delegate
            {
                return(true);
            };

            HttpWebRequest  request;
            HttpWebResponse response     = null;
            SendResponse    sendResponse = new SendResponse();

            try
            {
                request = WebRequest.Create(requestUri) as HttpWebRequest;

                request.Method    = method;
                request.UserAgent = userAgent;
                request.Host      = host;
                //request.Proxy = null;
                //request.Proxy = new WebProxy("203.113.17.59", 808);
                //request.Proxy.Credentials = new NetworkCredential("b88", "abcd1234");
                request.Accept          = accept;
                request.ProtocolVersion = HttpVersion.Version10;
                request.KeepAlive       = true;
                request.Timeout         = 10000;
                request.CookieContainer = cookieContainer;
                if (!String.IsNullOrEmpty(xml))
                {
                    request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                    request.Headers.Add("Cache-Control", "no-cache");
                }
                request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip, deflate");

                //request.ServicePoint.Expect100Continue = false;
                //request.ServicePoint.ConnectionLimit = 24;

                if (!string.IsNullOrEmpty(contentType))
                {
                    request.ContentType = contentType;
                }

                if (!string.IsNullOrEmpty(referer))
                {
                    request.Referer = referer;
                }

                request.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);

                if (data != null)
                {
                    // Set the content length in the request headers
                    request.ContentLength = data.Length;
                    // Write data
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                // Get response
                response = request.GetResponse() as HttpWebResponse;

                if (request.HaveResponse == true && response != null)
                {
                    // Get the response stream
                    sendResponse.SetCookie  = response.Headers.Get("Set-Cookie");
                    sendResponse.ReponseUri = response.ResponseUri.ToString();

                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        sendResponse.StatusCode        = response.StatusCode;
                        sendResponse.StatusDescription = response.StatusDescription;
                        sendResponse.Result            = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        sendResponse.StatusCode        = errorResponse.StatusCode;
                        sendResponse.StatusDescription = errorResponse.StatusDescription;
                    }
                }
            }
            catch (Exception ex)
            {
                sendResponse.StatusCode = HttpStatusCode.NotFound;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(sendResponse);
        }
예제 #9
0
        public static void doService(string method, string query, ServletInfo info,
                                     Map <string, string> requestHeader,
                                     Stream input, Stream output)
        {
            if (info.servlet == null)
            {
                info.servlet = createServlet(info);
            }

            MemoryStream            outputBuffer = new MemoryStream();
            HttpServletResponseImpl resp
                = new HttpServletResponseImpl(outputBuffer);

            HttpServletRequest req;

            if (method == "GET")
            {
                Map <string, string[]> map;
                map = stringToMap(query);
                req = new HttpServletRequestImpl("GET", requestHeader, map, resp, info.webApp);
            }
            else if (method == "POST")
            {
                string contentType = requestHeader.get("CONTENT-TYPE");
                int    contentLength
                    = Int32.Parse(requestHeader.get("CONTENT-LENGTH"));
                if (contentType.ToUpper().StartsWith("MULTIPART/FORM-DATA"))
                {
                    req = MultiPartParser.parse(requestHeader, input,
                                                contentType, contentLength,
                                                resp, info.webApp);
                }
                else
                {
                    Map <string, string[]> map;
                    string line = readToSize(input, contentLength);
                    map = stringToMap(line);
                    req = new HttpServletRequestImpl("POST", requestHeader, map,
                                                     resp, info.webApp);
                }
            }
            else
            {
                throw new Exception("BAD METHOD:" + method);
            }

            info.servlet.service(req, resp);

            if (resp.status == HttpServletResponse.SC_OK)
            {
                ResponseHeaderGenerator hg
                    = new ResponseHeaderGeneratorImpl(resp.cookies);
                SendResponse.sendOkResponseHeader(output, resp.contentType, hg);

                if (resp.printWriter != null)
                {
                    resp.printWriter.Flush();
                }
                byte[] outputBytes = outputBuffer.ToArray();
                foreach (byte b in outputBytes)
                {
                    output.WriteByte(b);
                }
            }
            else if (resp.status == HttpServletResponse.SC_FOUND)
            {
                string redirectLocation;
                if (resp.redirectLocation.StartsWith("/"))
                {
                    string host = requestHeader.get("HOST");
                    redirectLocation = "http://"
                                       + ((host != null) ? host : Constants.SERVER_NAME)
                                       + resp.redirectLocation;
                }
                else
                {
                    redirectLocation = resp.redirectLocation;
                }
                SendResponse.sendFoundResponse(output, redirectLocation);
            }
        }
예제 #10
0
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var sendGridClient = new SendGridClient(_apiKey);

            var mailMessage = new SendGridMessage();

            mailMessage.SetSandBoxMode(_sandBoxMode);

            mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress));

            if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList());
            }

            if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
            {
                mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList());
            }

            mailMessage.SetSubject(email.Data.Subject);

            if (email.Data.IsHtml)
            {
                mailMessage.HtmlContent = email.Data.Body;
            }
            else
            {
                mailMessage.PlainTextContent = email.Data.Body;
            }

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                mailMessage.PlainTextContent = email.Data.PlaintextAlternativeBody;
            }

            if (email.Data.Attachments.Any())
            {
                foreach (var attachment in email.Data.Attachments)
                {
                    var sendGridAttachment = await ConvertAttachment(attachment);

                    mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content,
                                              sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId);
                }
            }

            var sendGridResponse = await sendGridClient.SendEmailAsync(mailMessage, token.GetValueOrDefault());

            var sendResponse = new SendResponse();

            if (IsHttpSuccess((int)sendGridResponse.StatusCode))
            {
                return(sendResponse);
            }

            sendResponse.ErrorMessages.Add($"{sendGridResponse.StatusCode}");
            var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body);

            if (messageBodyDictionary.ContainsKey("errors"))
            {
                var errors = messageBodyDictionary["errors"];

                foreach (var error in errors)
                {
                    sendResponse.ErrorMessages.Add($"{error}");
                }
            }

            return(sendResponse);
        }
예제 #11
0
        public bool LoginProxy(string url, string userName, string password)
        {
            UrlHost        = string.Empty;
            Host           = string.Empty;
            LoginUrl       = url;
            UserName       = userName.ToUpper();
            Password       = password;
            ParamContainer = new Dictionary <string, ParamRequest>();

            try
            {
                Uri uri = new Uri(url);

                NetTcpBinding b = new NetTcpBinding();
                b.Security.Mode = SecurityMode.None;

                EndpointAddress vEndPoint         = new EndpointAddress(ProxyEndpoint);
                ChannelFactory <IBcSupService> cf = new ChannelFactory <IBcSupService>
                                                        (b, vEndPoint);

                IBcSupService serviceProxy = cf.CreateChannel();
                serviceProxy.Ping();

                var processLoginMsg = serviceProxy.Login(url, userName, password);

                if (processLoginMsg == null || processLoginMsg.Result.Contains("Incorrect username"))
                {
                    throw new Exception(string.Format("Incorrect username: [{0}] and password: [{1}]",
                                                      userName, password));
                }

                var    validateIndex    = processLoginMsg.Result.IndexOf("location='");
                var    validateIndexEnd = processLoginMsg.Result.IndexOf("';", validateIndex);
                string validateUrl      = processLoginMsg.Result.Substring(validateIndex + 10, validateIndexEnd - (validateIndex + 10));

                Logger.Info(UserName + " >> Validate Url::::" + validateUrl);
                Uri uriValidate = new Uri(validateUrl);
                if (validateUrl.Contains("www"))
                {
                    return(false);
                }

                var cookieValidate = BindCookieContainer(uriValidate, processLoginMsg.SetCookie);

                var validateMsg = SendIbet302(validateUrl, "GET", userAgent, cookieValidate, null, url + "ProcessLogin.aspx",
                                              uriValidate.Host, accept, null);

                UrlHost = uri.Scheme + Uri.SchemeDelimiter + uriValidate.Host;
                Uri urimain = new Uri(UrlHost);
                Host = urimain.Host;

                var cookieMain = BindCookieContainer(urimain, validateMsg.SetCookie, cookieValidate);

                //2 lan get main roi get top roi get left
                //var mainMsg1 = SendIbet302(UrlHost + validateMsg.Location,
                //    "GET", userAgent, cookieMain, null, validateUrl, Host, accept, null);
                var mainMsg1 = SendIbet302(validateMsg.ReponseUri,
                                           "GET", userAgent, cookieMain, null, validateUrl, Host, accept, "text/html");

                CookieContainer = BindCookieContainer(urimain, mainMsg1.SetCookie, cookieMain);

                var mainMsg2 = SendIbet302(mainMsg1.ReponseUri,
                                           "GET", userAgent, CookieContainer, null, mainMsg1.ReponseUri,
                                           Host, accept, "text/html");
                CookieContainer = BindCookieContainer(urimain, mainMsg2.SetCookie, CookieContainer);

                if (mainMsg2.Result.Contains("frmChangePW") || mainMsg2.Result.Contains("Change_Password"))
                {
                    var changePass = SendIbet302(UrlHost + "/Change_Password.aspx?expiry=yes",
                                                 "GET", userAgent, CookieContainer, null, mainMsg1.ReponseUri,
                                                 Host, accept, "text/html");

                    string changePassSubmitParam =
                        "txtOldPW=&txtPW=&txtConPW=&hidSubmit=&hidRemindSubmit=next&hidLowerCaseOldPW=&hidExDate=1";

                    byte[] byteChangePassSubmitParam = Encoding.UTF8.GetBytes(changePassSubmitParam);

                    var changePassSubmit = SendIbet302(UrlHost + "/Change_Password.aspx",
                                                       "POST", userAgent, CookieContainer, byteChangePassSubmitParam,
                                                       UrlHost + "/Change_Password.aspx?expiry=yes",
                                                       Host, accept, "application/x-www-form-urlencoded");
                }

                var topMenuMsg = SendIbet302(UrlHost + "/topmenu.aspx",
                                             "GET", userAgent, CookieContainer, null, mainMsg2.ReponseUri,
                                             Host, accept, "text/html");
                ConvertServerTime(topMenuMsg.Result);

                CookieContainer = BindCookieContainer(urimain, topMenuMsg.SetCookie, CookieContainer);

                SendResponse leftMsg = SendIbet302(UrlHost + "/LeftAllInOne.aspx",
                                                   "GET", userAgent, CookieContainer, null, mainMsg2.ReponseUri,
                                                   Host, accept, "text/html");

                if (string.IsNullOrEmpty(leftMsg.Result))
                {
                    Logger.Info("GET LEFT MESSAGE LAN 2!");
                    leftMsg = SendIbet302(UrlHost + "/LeftAllInOne.aspx",
                                          "GET", userAgent, CookieContainer, null, mainMsg2.ReponseUri,
                                          Host, accept, "text/html");
                }

                CookieContainer = BindCookieContainer(urimain, leftMsg.SetCookie, CookieContainer);

                int    indexNameK     = leftMsg.Result.IndexOf("name=\"k");
                int    endIndexNameK  = leftMsg.Result.IndexOf(" ", indexNameK);
                int    indexValueK    = leftMsg.Result.IndexOf("value=\"v", indexNameK);
                int    endIndexValueK = leftMsg.Result.IndexOf(" ", indexValueK);
                string kName          = leftMsg.Result.Substring(indexNameK + 6, endIndexNameK - (indexNameK + 7)).Trim();
                string kValue         =
                    leftMsg.Result.Substring(indexValueK + 7, endIndexValueK - (indexValueK + 8)).Trim();
                ParamContainer["K"] = new ParamRequest(kName, kValue);

                var newMarketMsg = SendIbet302(UrlHost + "/UnderOver.aspx?Market=t&DispVer=new",
                                               "GET", userAgent, CookieContainer, null, leftMsg.ReponseUri,
                                               Host, accept, "text/html");
                CookieContainer = BindCookieContainer(urimain, newMarketMsg.SetCookie, CookieContainer);

                //CookieContainer = BindCookieContainer(urimain, setCookie, CookieContainer);

                UpdateException(this);

                ////Begin check login
                objCheckLoginTimer = new System.Threading.Timer(CheckLoginCallback, null, 0,
                                                                SystemConfig.TIME_CHECK_LOGIN_IBET);

                AccountStatus = eAccountStatus.Online;
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Error("Loi dang nhap", ex);

                UrlHost        = string.Empty;
                Host           = string.Empty;
                AvailabeCredit = 0;
                CashBalance    = 0;
                Status         = eServiceStatus.Unknown;
                AccountStatus  = eAccountStatus.Offline;

                if (objCheckLoginTimer != null)
                {
                    objCheckLoginTimer.Dispose();
                }

                return(false);
            }
        }
예제 #12
0
 internal static void RaiseSendResponse(string info)
 {
     SendResponse?.Invoke(null, new CustomEventArgs(info));
 }
예제 #13
0
 private void OnSendResponse(Response response)
 {
     response.Stopwatch.Stop();
     SendResponse?.Invoke(response);
 }
예제 #14
0
        public bool LoginNomal(string url, string userName, string password)
        {
            UrlHost        = string.Empty;
            Host           = string.Empty;
            LoginUrl       = url;
            UserName       = userName.ToUpper();
            Password       = password;
            ParamContainer = new Dictionary <string, ParamRequest>();

            try
            {
                Uri    uri  = new Uri(url);
                string host = uri.Host;

                var getMain          = SendIbet302(url + "login888.aspx", "GET", userAgent, null, null, url, host, accept, null);
                var docrootLeftInOne = new HtmlAgilityPack.HtmlDocument();
                docrootLeftInOne.LoadHtml(getMain.Result);
                var codeLogin = docrootLeftInOne.DocumentNode.SelectSingleNode("//input[@type='text' and @name='txtCode']")
                                .Attributes["value"].Value;
                var          hashpass        = GetHashPass(userName, password, codeLogin);
                string       loginParam      = string.Format(@"selLang=en&txtID={0}&txtPW={1}&txtCode={2}&hidubmit=&IEVerison
=0&detecResTime=138&IsSSL=0&PF=Default", userName, hashpass, codeLogin);
                var          cookieContainer = BindCookieContainer(uri, getMain.SetCookie);
                byte[]       byteLoginParam  = Encoding.UTF8.GetBytes(loginParam);
                SendResponse processLoginMsg = SendIbet302(url + "ProcessLogin.aspx", "POST", userAgent, cookieContainer, byteLoginParam, url, host, accept,
                                                           "application/x-www-form-urlencoded");

                if (processLoginMsg.Result.Contains("www"))
                {
                    processLoginMsg = SendIbet302(url + "ProcessLogin.aspx", "POST", userAgent, cookieContainer, byteLoginParam, url, host, accept,
                                                  "application/x-www-form-urlencoded");
                }
                //Logger.Info("Process Msg: " + processLoginMsg.Result);
                if (processLoginMsg.Result.Contains("Incorrect username"))
                {
                    throw new Exception(string.Format("Incorrect username: [{0}] and password: [{1}]",
                                                      userName, password));
                }

                var    validateIndex    = processLoginMsg.Result.IndexOf("location='");
                var    validateIndexEnd = processLoginMsg.Result.IndexOf("';", validateIndex);
                string validateUrl      = processLoginMsg.Result.Substring(validateIndex + 10, validateIndexEnd - (validateIndex + 10));

                Logger.Info(UserName + " >> Validate Url::::" + validateUrl);
                Uri uriValidate = new Uri(validateUrl);
                if (validateUrl.Contains("www"))
                {
                    return(false);
                }

                var cookieValidate = BindCookieContainer(uriValidate, processLoginMsg.SetCookie);

                var validateMsg = SendIbet302(validateUrl, "GET", userAgent, cookieValidate, null, url + "ProcessLogin.aspx",
                                              uriValidate.Host, accept, null);

                UrlHost = uri.Scheme + Uri.SchemeDelimiter + uriValidate.Host;
                Uri urimain = new Uri(UrlHost);
                Host = urimain.Host;

                var cookieMain = BindCookieContainer(urimain, validateMsg.SetCookie, cookieValidate);

                var mainMsg1 = SendIbet302(validateMsg.ReponseUri,
                                           "GET", userAgent, cookieMain, null, validateUrl, Host, accept, "text/html");

                CookieContainer = BindCookieContainer(urimain, mainMsg1.SetCookie, cookieMain);

                var mainMsg2 = SendIbet302(mainMsg1.ReponseUri,
                                           "GET", userAgent, CookieContainer, null, mainMsg1.ReponseUri,
                                           Host, accept, "text/html");
                CookieContainer = BindCookieContainer(urimain, mainMsg2.SetCookie, CookieContainer);

                if (mainMsg2.Result.Contains("frmChangePW") || mainMsg2.Result.Contains("Change_Password"))
                {
                    var changePass = SendIbet302(UrlHost + "/Change_Password.aspx?expiry=yes",
                                                 "GET", userAgent, CookieContainer, null, mainMsg1.ReponseUri,
                                                 Host, accept, "text/html");

                    string changePassSubmitParam =
                        "txtOldPW=&txtPW=&txtConPW=&hidSubmit=&hidRemindSubmit=next&hidLowerCaseOldPW=&hidExDate=1";

                    byte[] byteChangePassSubmitParam = Encoding.UTF8.GetBytes(changePassSubmitParam);

                    var changePassSubmit = SendIbet302(UrlHost + "/Change_Password.aspx",
                                                       "POST", userAgent, CookieContainer, byteChangePassSubmitParam,
                                                       UrlHost + "/Change_Password.aspx?expiry=yes",
                                                       Host, accept, "application/x-www-form-urlencoded");
                }

                var topMenuMsg = SendIbet302(UrlHost + "/topmenu.aspx",
                                             "GET", userAgent, CookieContainer, null, mainMsg2.ReponseUri,
                                             Host, accept, "text/html");
                ConvertServerTime(topMenuMsg.Result);

                CookieContainer = BindCookieContainer(urimain, topMenuMsg.SetCookie, CookieContainer);

                SendResponse leftMsg = SendIbet302(UrlHost + "/LeftAllInOne.aspx",
                                                   "GET", userAgent, CookieContainer, null, mainMsg2.ReponseUri,
                                                   Host, accept, "text/html");

                if (string.IsNullOrEmpty(leftMsg.Result))
                {
                    Logger.Info("GET LEFT MESSAGE LAN 2!");
                    leftMsg = SendIbet302(UrlHost + "/LeftAllInOne.aspx",
                                          "GET", userAgent, CookieContainer, null, mainMsg2.ReponseUri,
                                          Host, accept, "text/html");
                }

                CookieContainer = BindCookieContainer(urimain, leftMsg.SetCookie, CookieContainer);

                int    indexNameK     = leftMsg.Result.IndexOf("name=\"k");
                int    endIndexNameK  = leftMsg.Result.IndexOf(" ", indexNameK);
                int    indexValueK    = leftMsg.Result.IndexOf("value=\"v", indexNameK);
                int    endIndexValueK = leftMsg.Result.IndexOf(" ", indexValueK);
                string kName          = leftMsg.Result.Substring(indexNameK + 6, endIndexNameK - (indexNameK + 7)).Trim();
                string kValue         =
                    leftMsg.Result.Substring(indexValueK + 7, endIndexValueK - (indexValueK + 8)).Trim();
                ParamContainer["K"] = new ParamRequest(kName, kValue);

                var newMarketMsg = SendIbet302(UrlHost + "/UnderOver.aspx?Market=t&DispVer=new",
                                               "GET", userAgent, CookieContainer, null, leftMsg.ReponseUri,
                                               Host, accept, "text/html");
                CookieContainer = BindCookieContainer(urimain, newMarketMsg.SetCookie, CookieContainer);

                //CookieContainer = BindCookieContainer(urimain, setCookie, CookieContainer);

                UpdateException(this);

                ////Begin check login
                objCheckLoginTimer = new System.Threading.Timer(CheckLoginCallback, null, 0,
                                                                SystemConfig.TIME_CHECK_LOGIN_IBET);

                AccountStatus = eAccountStatus.Online;
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Error("Loi dang nhap", ex);

                UrlHost        = string.Empty;
                Host           = string.Empty;
                AvailabeCredit = 0;
                CashBalance    = 0;
                Status         = eServiceStatus.Unknown;
                AccountStatus  = eAccountStatus.Offline;

                if (objCheckLoginTimer != null)
                {
                    objCheckLoginTimer.Dispose();
                }

                return(false);
            }
        }
예제 #15
0
        public async Task SaveWithServerAsync_NewTextSend_Success(SutProvider <SendService> sutProvider, string userId, SendResponse response, Send send)
        {
            send.Id = null;
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IApiService>().PostSendAsync(Arg.Any <SendRequest>()).Returns(response);

            var fileContentBytes = new EncByteArray(Encoding.UTF8.GetBytes("This is the file content"));

            await sutProvider.Sut.SaveWithServerAsync(send, fileContentBytes);

            Predicate <SendRequest> sendRequestPredicate = r =>
            {
                // Note Send -> SendRequest tested in SendRequestTests
                TestHelper.AssertPropertyEqual(new SendRequest(send, fileContentBytes.Buffer?.LongLength), r);
                return(true);
            };

            switch (send.Type)
            {
            case SendType.Text:
                await sutProvider.GetDependency <IApiService>().Received(1)
                .PostSendAsync(Arg.Is <SendRequest>(r => sendRequestPredicate(r)));

                break;

            case SendType.File:
            default:
                throw new Exception("Untested send type");
            }
        }
예제 #16
0
 /// <summary>
 /// Sends a message.
 /// </summary>
 /// <returns> SendResponse object</returns>
 /// <param name="request"> SendRequest object</param>
 /// <param name='jsonRpcCallId'>
 /// The json rpc call identifier. This is a string generated by the client, which can be used to correlate the response to the request. Max length is 256 characters. A JSON-RPC id must be generated on a per call invocation basis. The Rogerthat platform uses the id of the call to store the call result for a certain amount of time so that if something fails during the communication, the same call (having the same JSON-RPC id) can be resent to the Rogerthat service, allowing to fetch the result, without actually executing the call again. This avoids annoying problems such as duplicate delivery of messages.
 /// 
 /// You should use a different JSON-RPC id for every call you make.
 /// 
 /// In case of an intermittent failure such as a network connectivity problem, you can retry the same call using the same JSON-RPC id, without running the risk of duplicate execution of your call (e.g. duplicate message delivery).
 /// </param>
 public SendResponse Send(SendRequest request, string jsonRpcCallId)
 {
     SendResponse result = new SendResponse();
     WireRequest (0, jsonRpcCallId, "messaging.send", (writer) => {
         request.Write(writer, false);
     }, (reader) => {
         result.Read(reader);
     }
     );
     return result;
 }
예제 #17
0
        public unsafe SendResponse SendIbet(string requestUri, string method, string userAgent, CookieContainer cookieContainer,
                                            byte[] data, string host, string accept, string referer = "", string contentType = "")
        {
            //ServicePointManager.ServerCertificateValidationCallback =
            //    delegate
            //    {
            //        return true;
            //    };

            HttpWebRequest  request;
            HttpWebResponse response     = null;
            SendResponse    sendResponse = new SendResponse();

            try
            {
                request = WebRequest.Create(requestUri) as HttpWebRequest;

                request.ServicePoint.BindIPEndPointDelegate = delegate(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
                {
                    if (remoteEndPoint.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {
                        if (string.IsNullOrEmpty(RealIpAddress))
                        {
                            return(new IPEndPoint(IPAddress.Any, 0));
                        }
                        else
                        {
                            return(new IPEndPoint(IPAddress.Parse(RealIpAddress), 0));
                        }
                    }
                    else
                    {
                        return(new IPEndPoint(IPAddress.IPv6Any, 0));
                    }
                };

                request.Method    = method;
                request.UserAgent = userAgent;
                request.Host      = host;
                request.Proxy     = null;
                request.UnsafeAuthenticatedConnectionSharing = true;
                request.Accept          = accept;
                request.ProtocolVersion = HttpVersion.Version11;
                request.Timeout         = 10000;
                request.CookieContainer = cookieContainer;

                request.AllowAutoRedirect = false;
                request.ServicePoint.Expect100Continue = false;

                request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");

                if (!string.IsNullOrEmpty(contentType))
                {
                    request.ContentType = contentType;
                }

                if (!string.IsNullOrEmpty(referer))
                {
                    request.Referer = referer;
                }

                if (string.IsNullOrEmpty(IpFake))
                {
                    request.KeepAlive = true;
                    request.Headers.Add("Accept-Encoding", "gzip, deflate");
                    ServicePoint servicePoaint = request.ServicePoint;
                    PropertyInfo property      = servicePoaint.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
                    property.SetValue(servicePoaint, (byte)0, null);
                }
                else
                {
                    request.Headers.Add("X-Forwarded-For", IpFake);
                    request.Headers.Add("Accept-Encoding", "gzip, deflate,sdch");
                }

                request.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);

                if (data != null)
                {
                    // Set the content length in the request headers
                    request.ContentLength = data.Length;
                    // Write data
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                // Get response
                response = request.GetResponse() as HttpWebResponse;

                if (request.HaveResponse == true && response != null)
                {
                    // Get the response stream
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        sendResponse.StatusCode        = response.StatusCode;
                        sendResponse.StatusDescription = response.StatusDescription;
                        sendResponse.Result            = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        sendResponse.StatusCode        = errorResponse.StatusCode;
                        sendResponse.StatusDescription = errorResponse.StatusDescription;
                    }
                }
            }
            catch (Exception ex)
            {
                sendResponse.StatusCode = HttpStatusCode.NotFound;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(sendResponse);
        }
예제 #18
0
        public async Task SaveWithServerAsync_PutSend_Success(SutProvider <SendService> sutProvider, string userId, SendResponse response, Send send)
        {
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IApiService>().PutSendAsync(send.Id, Arg.Any <SendRequest>()).Returns(response);

            await sutProvider.Sut.SaveWithServerAsync(send, null);

            Predicate <SendRequest> sendRequestPredicate = r =>
            {
                // Note Send -> SendRequest tested in SendRequestTests
                TestHelper.AssertPropertyEqual(new SendRequest(send, null), r);
                return(true);
            };

            await sutProvider.GetDependency <IApiService>().Received(1)
            .PutSendAsync(send.Id, Arg.Is <SendRequest>(r => sendRequestPredicate(r)));
        }
예제 #19
0
 public void ExceptionCannotBeNull()
 {
     Assert.Throws <ArgumentNullException>(() => SendResponse.FromException(null));
 }
예제 #20
0
 public void MessageIdCannotBeEmpty()
 {
     Assert.Throws <ArgumentException>(() => SendResponse.FromMessageId(string.Empty));
 }
예제 #21
0
 public void MessageIdCannotBeNull()
 {
     Assert.Throws <ArgumentException>(() => SendResponse.FromMessageId(null));
 }
예제 #22
0
        public static SendResponse Send302(string requestUri, string method, string userAgent, CookieContainer cookieContainer,
                                           byte[] data, string referal, string host, string accept, string contentType = "")
        {
            ServicePointManager.ServerCertificateValidationCallback =
                delegate
            {
                return(true);
            };

            HttpWebRequest  request;
            HttpWebResponse response     = null;
            SendResponse    sendResponse = new SendResponse();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(MyCertValidationCb);
                request           = WebRequest.Create(requestUri) as HttpWebRequest;
                request.Proxy     = null;
                request.Method    = method;
                request.UserAgent = userAgent;

                if (cookieContainer != null)
                {
                    request.CookieContainer = cookieContainer;
                }
                request.AllowAutoRedirect = false;
                request.KeepAlive         = true;
                request.Referer           = referal;
                request.Host    = host;
                request.Accept  = accept;
                request.Timeout = 10000;
                request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                request.AutomaticDecompression = (System.Net.DecompressionMethods.GZip |
                                                  System.Net.DecompressionMethods.Deflate);

                if (!string.IsNullOrEmpty(contentType))
                {
                    request.ContentType = contentType;
                }

                if (data != null)
                {
                    // Set the content length in the request headers
                    request.ContentLength = data.Length;
                    // Write data
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                // Get response
                response = request.GetResponse() as HttpWebResponse;

                if (request.HaveResponse && response != null)
                {
                    sendResponse.Location   = response.Headers.Get("Location");
                    sendResponse.SetCookie  = response.Headers.Get("Set-Cookie");
                    sendResponse.ReponseUri = response.ResponseUri.ToString();

                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        sendResponse.StatusCode        = response.StatusCode;
                        sendResponse.StatusDescription = response.StatusDescription;
                        sendResponse.Result            = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        sendResponse.StatusCode        = errorResponse.StatusCode;
                        sendResponse.StatusDescription = errorResponse.StatusDescription;
                    }
                }
            }
            catch (Exception ex)
            {
                sendResponse.StatusCode = HttpStatusCode.NotFound;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(sendResponse);
        }
예제 #23
0
        /// <summary>
        /// User for Sbobet
        /// </summary>

        public SendResponse SendSbo(string requestUri, string method, string userAgent, CookieContainer cookieContainer,
                                    Dictionary <string, string> headerParams, bool isDecompression, byte[] data, string referer, string host, string accept = "", string contentType = "")
        {
            //ServicePointManager.ServerCertificateValidationCallback =
            //    delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            //    {
            //        return true;
            //    };

            HttpWebRequest  request;
            HttpWebResponse response     = null;
            SendResponse    sendResponse = new SendResponse();

            try
            {
                request = WebRequest.Create(requestUri) as HttpWebRequest;

                request.Method    = method;
                request.UserAgent = userAgent;

                request.CookieContainer = cookieContainer;

                request.Host      = host;
                request.Proxy     = null;
                request.KeepAlive = true;

                if (!string.IsNullOrEmpty(accept))
                {
                    request.Accept = accept;
                }
                //request.Accept = "text/plain, */*; q=0.01";
                if (!string.IsNullOrEmpty(contentType))
                {
                    request.ContentType = contentType;
                }

                if (!string.IsNullOrEmpty(referer))
                {
                    request.Referer = referer;
                }

                foreach (var headerParam in headerParams)
                {
                    request.Headers.Add(headerParam.Key, headerParam.Value);
                }

                if (isDecompression)
                {
                    request.AutomaticDecompression = (System.Net.DecompressionMethods.GZip |
                                                      System.Net.DecompressionMethods.Deflate);
                }

                if (data != null)
                {
                    // Set the content length in the request headers
                    request.ContentLength = data.Length;
                    // Write data
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                // Get response
                response = request.GetResponse() as HttpWebResponse;

                if (request.HaveResponse && response != null)
                {
                    // Get the response stream
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        sendResponse.StatusCode        = response.StatusCode;
                        sendResponse.StatusDescription = response.StatusDescription;
                        sendResponse.Result            = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException wex)
            {
                // This exception will be raised if the server didn't return 200 - OK
                // Try to retrieve more information about the network error
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        sendResponse.StatusCode        = errorResponse.StatusCode;
                        sendResponse.StatusDescription = errorResponse.StatusDescription;
                    }
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(sendResponse);
        }
예제 #24
0
        private SendResponse ProcessResponse(HttpResponseMessage httpResponseMessage, ActivityPackage activityPackage)
        {
            var sendResponse = new SendResponse
            {
                WillRetry = false,
                JsonDict = Util.ParseJsonResponse(httpResponseMessage),
            };

            if (httpResponseMessage.StatusCode == HttpStatusCode.InternalServerError   // 500
                || httpResponseMessage.StatusCode == HttpStatusCode.NotImplemented)    // 501
            {
                Logger.Error("{0}. (Status code: {1}).",
                    activityPackage.FailureMessage(),
                    (int)httpResponseMessage.StatusCode);
            }
            else if (!httpResponseMessage.IsSuccessStatusCode)
            {
                sendResponse.WillRetry = true;

                Logger.Error("{0}. (Status code: {1}). Will retry later.",
                    activityPackage.FailureMessage(),
                    (int)httpResponseMessage.StatusCode);
            }

            return sendResponse;
        }
예제 #25
0
        //public static SendResponse Send(string requestUri, string method, string userAgent, CookieContainer cookieContainer,
        //    Dictionary<string, string> headerParams, bool isDecompression, byte[] data)
        //{
        //    ServicePointManager.ServerCertificateValidationCallback =
        //        delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        //        {
        //            return true;
        //        };

        //    HttpWebRequest request;
        //    HttpWebResponse response = null;
        //    SendResponse sendResponse = new SendResponse();
        //    try
        //    {
        //        request = WebRequest.Create(requestUri) as HttpWebRequest;
        //        //request.ProtocolVersion
        //        request.Method = method;
        //        request.UserAgent = userAgent;

        //        request.CookieContainer = cookieContainer;

        //        foreach (var headerParam in headerParams)
        //        {
        //            request.Headers.Add(headerParam.Key, headerParam.Value);
        //        }

        //        if (isDecompression)
        //        {
        //            request.AutomaticDecompression = (System.Net.DecompressionMethods.GZip |
        //                                              System.Net.DecompressionMethods.Deflate);

        //        }

        //        if (data != null)
        //        {
        //            // Set the content length in the request headers
        //            request.ContentLength = data.Length;
        //            // Write data
        //            using (Stream stream = request.GetRequestStream())
        //            {
        //                stream.Write(data, 0, data.Length);
        //            }
        //        }

        //        // Get response
        //        response = request.GetResponse() as HttpWebResponse;

        //        if (request.HaveResponse == true && response != null)
        //        {
        //            // Get the response stream
        //            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        //            {
        //                sendResponse.StatusCode = response.StatusCode;
        //                sendResponse.StatusDescription = response.StatusDescription;
        //                sendResponse.Result = reader.ReadToEnd();
        //            }
        //        }
        //    }
        //    catch (WebException wex)
        //    {
        //        // This exception will be raised if the server didn't return 200 - OK
        //        // Try to retrieve more information about the network error
        //        if (wex.Response != null)
        //        {
        //            using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
        //            {
        //                sendResponse.StatusCode = errorResponse.StatusCode;
        //                sendResponse.StatusDescription = errorResponse.StatusDescription;
        //            }
        //        }
        //    }
        //    finally
        //    {
        //        if (response != null)
        //        {
        //            response.Close();
        //        }
        //    }

        //    return sendResponse;
        //}

        public SendResponse SendIbet(string requestUri, string method, string userAgent, CookieContainer cookieContainer,
                                     bool isDecompression, byte[] data, string host, string referer = "", string contentType = "")
        {
            ServicePointManager.ServerCertificateValidationCallback =
                delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            };

            HttpWebRequest  request;
            HttpWebResponse response     = null;
            SendResponse    sendResponse = new SendResponse();

            try
            {
                request = WebRequest.Create(requestUri) as HttpWebRequest;

                request.Method    = method;
                request.UserAgent = userAgent;

                request.CookieContainer = cookieContainer;
                request.Host            = host;
                request.Proxy           = null;

                request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip, deflate");
                //request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                //request.ServicePoint.Expect100Continue = false;
                request.KeepAlive       = true;
                request.ProtocolVersion = HttpVersion.Version10;
                //request.ServicePoint.ConnectionLimit = 24;

                if (!string.IsNullOrEmpty(contentType))
                {
                    request.ContentType = contentType;
                }

                if (!string.IsNullOrEmpty(referer))
                {
                    request.Referer = referer;
                }

                //foreach (var headerParam in headerParams)
                //{
                //    request.Headers.Add(headerParam.Key, headerParam.Value);
                //}

                if (isDecompression)
                {
                    request.AutomaticDecompression = (System.Net.DecompressionMethods.GZip |
                                                      System.Net.DecompressionMethods.Deflate);
                }

                if (data != null)
                {
                    // Set the content length in the request headers
                    request.ContentLength = data.Length;
                    // Write data
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                // Get response
                response = request.GetResponse() as HttpWebResponse;

                if (request.HaveResponse == true && response != null)
                {
                    // Get the response stream
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        sendResponse.StatusCode        = response.StatusCode;
                        sendResponse.StatusDescription = response.StatusDescription;
                        sendResponse.Result            = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException wex)
            {
                // This exception will be raised if the server didn't return 200 - OK
                // Try to retrieve more information about the network error
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        sendResponse.StatusCode        = errorResponse.StatusCode;
                        sendResponse.StatusDescription = errorResponse.StatusDescription;
                    }
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(sendResponse);
        }
예제 #26
0
        public async Task SaveWithServerAsync_NewFileSend_LegacyFallback_Success(SutProvider <SendService> sutProvider, string userId, Send send, SendResponse response)
        {
            send.Id = null;
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            var error = new ErrorResponse(null, System.Net.HttpStatusCode.NotFound);

            sutProvider.GetDependency <IApiService>().PostFileTypeSendAsync(Arg.Any <SendRequest>()).Throws(new ApiException(error));
            sutProvider.GetDependency <IApiService>().PostSendFileAsync(Arg.Any <MultipartFormDataContent>()).Returns(response);

            var fileContentBytes = new EncByteArray(Encoding.UTF8.GetBytes("This is the file content"));

            await sutProvider.Sut.SaveWithServerAsync(send, fileContentBytes);

            await sutProvider.GetDependency <IApiService>().Received(1).PostSendFileAsync(Arg.Any <MultipartFormDataContent>());
        }
예제 #27
0
        private SendResponse ProcessException(WebException webException, ActivityPackage activityPackage)
        {
            using (var response = webException.Response as HttpWebResponse)
            {
                int? statusCode = (response == null) ? null : (int?)response.StatusCode;

                var sendResponse = new SendResponse
                {
                    WillRetry = true,
                    JsonDict = Util.ParseJsonExceptionResponse(response)
                };

                Logger.Error("{0}. ({1}, Status code: {2}). Will retry later.",
                    activityPackage.FailureMessage(),
                    Util.ExtractExceptionMessage(webException),
                    statusCode);

                return sendResponse;
            }
        }
예제 #28
0
        public async Task RemovePasswordWithServerAsync_Success(SutProvider <SendService> sutProvider, SendResponse response, string sendId)
        {
            sutProvider.GetDependency <IApiService>().PutSendRemovePasswordAsync(sendId).Returns(response);

            await sutProvider.Sut.RemovePasswordWithServerAsync(sendId);

            await sutProvider.GetDependency <IApiService>().Received(1).PutSendRemovePasswordAsync(sendId);

            await sutProvider.GetDependency <IStorageService>().ReceivedWithAnyArgs(1).SaveAsync <Dictionary <string, SendData> >(default, default);
예제 #29
0
        public async Task SaveWithServerAsync_NewFileSend_Success(SutProvider <SendService> sutProvider, string userId, SendResponse response, Send send)
        {
            send.Id = null;
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IApiService>().PostSendAsync(Arg.Any <SendRequest>()).Returns(response);
            sutProvider.GetDependency <IApiService>().PostSendFileAsync(Arg.Any <MultipartFormDataContent>()).Returns(response);

            var fileContentBytes = Encoding.UTF8.GetBytes("This is the file content");

            await sutProvider.Sut.SaveWithServerAsync(send, fileContentBytes);

            Predicate <MultipartFormDataContent> formDataPredicate = fd =>
            {
                Assert.Equal(2, fd.Count()); // expect a request and file content

                var expectedRequest = JsonConvert.SerializeObject(new SendRequest(send, fileContentBytes?.LongLength));
                var actualRequest   = fd.First().ReadAsStringAsync().GetAwaiter().GetResult();
                Assert.Equal(expectedRequest, actualRequest);

                var actualFileContent = fd.Skip(1).First().ReadAsByteArrayAsync().GetAwaiter().GetResult();
                Assert.Equal(fileContentBytes, actualFileContent);
                return(true);
            };

            switch (send.Type)
            {
            case SendType.File:
                await sutProvider.GetDependency <IApiService>().Received(1)
                .PostSendFileAsync(Arg.Is <MultipartFormDataContent>(f => formDataPredicate(f)));

                break;

            case SendType.Text:
            default:
                throw new Exception("Untested send type");
            }
        }
예제 #30
0
        public ResponseCommand Execute(object data, User user, ILoggerService logger)
        {
            var response = new ResponseCommand();

            if (!(data is Shared.Models.Messages.Send))
            {
                response.Data     = 5;
                response.TypeData = "error";
                return(response);
            }

            var msg = (Shared.Models.Messages.Send)data;

            if (msg.ChatId > 0)
            {
                //Отправка сообщения пользователю.

                using (var db = new ServerData())
                {
                    try
                    {
                        //Проверка есть ли такой пользователь вообще.

                        if (db.Users.Any(u => u.UserId == msg.ChatId))
                        {
                            //Пользователь есть
                            var usr = db.Users.Single(u => u.UserId == msg.ChatId);

                            //Проверяем есть ли чат с этим пользователем.
                            if (db.UsersChats.Any(c => c.Owner == user.UserId && c.ChatId == usr.UserId))
                            {
                                //ничего не делаем
                            }
                            else
                            {
                                //Создавать чат для отправителя.

                                var usrChat = new UsersChat();
                                usrChat.Messages    = "";
                                usrChat.Owner       = user.UserId;
                                usrChat.ChatId      = usr.UserId;
                                usrChat.LastMessage = 0;
                                usrChat.LocalId     = db.UsersChats.Count() + 1;
                                db.UsersChats.Add(usrChat);

                                db.SaveChanges();


                                //Создание чата для принимающего.

                                var usrChat2 = new UsersChat();
                                usrChat2.Messages    = "";
                                usrChat2.Owner       = usr.UserId;
                                usrChat2.LastMessage = 0;
                                usrChat2.ChatId      = user.UserId;
                                usrChat2.LocalId     = db.UsersChats.Count() + 1;
                                db.UsersChats.Add(usrChat2);
                            }


                            //Отправляем ему сообщение

                            var msgObj = new Database.Message()
                            {
                                MsgId      = db.Messages.Count() + 1,
                                ChatId     = 0,
                                RecieverId = usr.UserId,
                                SenderId   = user.UserId,
                                Text       = msg.Text,
                                Time       = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds
                            };

                            //Добавление сообщения в бд
                            db.Messages.Add(msgObj);

                            //Добавление id сообщения в список.

                            var chats1 = db.UsersChats.Single(c => c.Owner == user.UserId && c.ChatId == usr.UserId);
                            chats1.Messages   += $",{msgObj}";
                            chats1.LastMessage = msgObj.Time;

                            var chats2 = db.UsersChats.Single(c => c.Owner == usr.UserId && c.ChatId == user.UserId);
                            chats2.Messages   += $",{msgObj}";
                            chats2.LastMessage = msgObj.Time;


                            db.SaveChanges();
                            var rsp = new SendResponse();
                            rsp.MsgId = msgObj.MsgId;

                            response.Data     = rsp;
                            response.TypeData = "msg.snd";
                            return(response);
                            //Todo: сделать оповещение юзера.
                        }
                        else
                        {
                            //Пользователя с таким Id не существует.
                            response.Data     = 8;
                            response.TypeData = "error";
                            return(response);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error("Произошла ошибка при отправке сообщения", e);
                        response.Data     = e.Message;
                        response.TypeData = "exception";
                        return(response);
                    }
                }
            }
            else
            {
                return(null);
            }
        }
예제 #31
0
        public async Task <SendResponse> SendAsync(Email email, CancellationToken?token = null)
        {
            var client = new HttpClient()
            {
                BaseAddress = new Uri($"https://api.mailgun.net/v3/{_domainName}/")
            };

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                       Convert.ToBase64String(Encoding.ASCII.GetBytes($"api:{_apiKey}")));

            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("from", $"{email.Data.FromAddress.Name} <{email.Data.FromAddress.EmailAddress}>"));
            email.Data.ToAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("to", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.CcAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("cc", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.BccAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("bcc", $"{x.Name} <{x.EmailAddress}>"));
            });
            parameters.Add(new KeyValuePair <string, string>("subject", email.Data.Subject));

            parameters.Add(new KeyValuePair <string, string>(email.Data.IsHtml ? "html" : "text", email.Data.Body));

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                parameters.Add(new KeyValuePair <string, string>("text", email.Data.PlaintextAlternativeBody));
            }

            var files = new List <HttpFile>();

            email.Data.Attachments.ForEach(x =>
            {
                string param;

                if (x.IsInline)
                {
                    param = "inline";
                }
                else
                {
                    param = "attachment";
                }

                files.Add(new HttpFile()
                {
                    ParameterName = param,
                    Data          = x.Data,
                    Filename      = x.Filename,
                    ContentType   = x.ContentType
                });
            });

            var response = await client.PostMultipart <MailgunResponse>("messages", parameters, files);

            var result = new SendResponse();

            if (!response.Success)
            {
                result.ErrorMessages.AddRange(response.Errors.Select(x => x.ErrorMessage));
                return(result);
            }

            return(result);
        }
예제 #32
0
        public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null)
        {
            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("from", $"{email.Data.FromAddress.Name} <{email.Data.FromAddress.EmailAddress}>"));
            email.Data.ToAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("to", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.CcAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("cc", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.BccAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("bcc", $"{x.Name} <{x.EmailAddress}>"));
            });
            email.Data.ReplyToAddresses.ForEach(x => {
                parameters.Add(new KeyValuePair <string, string>("h:Reply-To", $"{x.Name} <{x.EmailAddress}>"));
            });
            parameters.Add(new KeyValuePair <string, string>("subject", email.Data.Subject));

            parameters.Add(new KeyValuePair <string, string>(email.Data.IsHtml ? "html" : "text", email.Data.Body));

            if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody))
            {
                parameters.Add(new KeyValuePair <string, string>("text", email.Data.PlaintextAlternativeBody));
            }

            email.Data.Tags.ForEach(x =>
            {
                parameters.Add(new KeyValuePair <string, string>("o:tag", x));
            });

            var files = new List <HttpFile>();

            email.Data.Attachments.ForEach(x =>
            {
                string param;

                if (x.IsInline)
                {
                    param = "inline";
                }
                else
                {
                    param = "attachment";
                }

                files.Add(new HttpFile()
                {
                    ParameterName = param,
                    Data          = x.Data,
                    Filename      = x.Filename,
                    ContentType   = x.ContentType
                });
            });

            var response = await _httpClient.PostMultipart <MailgunResponse>("messages", parameters, files).ConfigureAwait(false);

            var result = new SendResponse();

            if (!response.Success)
            {
                result.ErrorMessages.AddRange(response.Errors.Select(x => x.ErrorMessage));
                return(result);
            }

            return(result);
        }
        public async Task <SendResponse> Send([FromBody] SendPayload sendPayload)
        {
            _logger.LogInformation($"Recieved sendPayload SandboxMode = { sendPayload.SandboxMode }, with { sendPayload.Messages.Count } messages");

            SendResponse result = new SendResponse {
                Messages = new List <MessageSendDetails>()
            };

            string baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

            var hubUrl = baseUrl.TrimEnd('/') + EmailsHub.HubUrl;

            var hubConnection = new HubConnectionBuilder()
                                .WithUrl(hubUrl)
                                .Build();

            await hubConnection.StartAsync();

            foreach (var email in sendPayload.Messages)
            {
                _logger.LogInformation($"Recieved email: Subject: \"{ email.Subject }\", " +
                                       $"From { email.From.Email } ({ email.From.Name }), " +
                                       $"To: { string.Join(", ", email.To.Select(recipient => $"{ recipient.Email } ({ recipient.Name })")) }, " +
                                       $"Text: { email.TextPart }, " +
                                       $"HTML: { email.HTMLPart }, " +
                                       $"With { email.InlinedAttachments?.Count ?? 0 } inlined and { email.Attachments?.Count ?? 0 } not inlined attachments, " +
                                       $"CustomId: { email.CustomId }, " +
                                       $"Payload: { email.EventPayload }");

                await hubConnection.SendAsync("EmailRecieved", email);

                var messageDetail = new MessageSendDetails
                {
                    Status = "success",
                    To     = new List <SendDetails>()
                };

                foreach (var recipient in email.To)
                {
                    var emailGuid = Guid.NewGuid().ToString();
                    var messageId = new Random().Next(int.MaxValue);

                    var eventTime = DateTimeOffset.Now.ToUnixTimeSeconds();

                    var sendDetails = new SendDetails
                    {
                        Email       = recipient.Email,
                        MessageID   = messageId,
                        MessageUUID = emailGuid,
                        MessageHref = "https://some.url.must.be.here.at.production.that.contains/MessageUUID"
                    };

                    await _eventsRecieverEndpoint.SendEvent <MailSentEvent>(new MailSentEvent
                    {
                        Time             = eventTime,
                        EmailAddress     = recipient.Email,
                        MessageGuid      = emailGuid,
                        MessageId        = messageId,
                        CustomId         = email.CustomId ?? "",
                        Payload          = email.EventPayload,
                        MailjetMessageId = messageId.ToString(),
                        CustomCampaign   = "",
                        SmtpReply        = "sent (250 2.0.0 OK 4242424242 fa5si855896wjc.199 - gsmtp)"
                    });

                    messageDetail.To.Add(sendDetails);
                }

                result.Messages.Add(messageDetail);
            }

            return(result);
        }