Exemplo n.º 1
0
 public void NullBody()
 {
     var response = new TextResponse(null);
     response.ContentType.Should().Be("text/plain");
     response.StatusCode.Should().Be(HttpStatusCode.OK);
     response.Body.AsString().Should().BeNull();
 }
Exemplo n.º 2
0
 public void Defaults()
 {
     var response = new TextResponse("Test");
     response.ContentType.Should().Be("text/plain");
     response.StatusCode.Should().Be(HttpStatusCode.OK);
     response.Body.AsString().Should().Be("Test");
 }
Exemplo n.º 3
0
 public void SetEncoding()
 {
     var response = new TextResponse("Test", encoding: Encoding.ASCII);
     response.ContentType.Should().Be("text/plain");
     response.StatusCode.Should().Be(HttpStatusCode.OK);
     response.Body.AsString().Should().Be("Test");
 }
Exemplo n.º 4
0
 public void SetContentType()
 {
     var response = new TextResponse("Test", contentType: "text/javascript");
     response.ContentType.Should().Be("text/javascript");
     response.StatusCode.Should().Be(HttpStatusCode.OK);
     response.Body.AsString().Should().Be("Test");
 }
Exemplo n.º 5
0
        //Отправляем текстовое сообщение от клиента всем остальным
        private void SendTextMessage(RemoteClient client, TextMessage textMessage)
        {
            //Формируем объект хранящиу в себе имя отправителя и текст сообщения
            var response = new TextResponse(client.UserView.Name, textMessage.Content);

            //Проходимся цоклом по
            foreach (var targetClient in
                     //Тем подключенным клиентам
                     clients
                     //Которые авторизованы в системе и их имя не совпадает с именем отпраителя
                     .Where(U => U.UserView?.Name != client.UserView.Name))
            {
                //Каждому подходящему под выборку клиента отправляем сообщение
                targetClient.Send(response);
            }
        }
        private void EmitCancelReject(GenericOrderItem item, int error_id, string message)
        {
            TextResponse r = new TextResponse()
            {
                Error    = CTPAPI.FromCTP(error_id),
                ErrorID  = error_id,
                ErrorMsg = message,
            };

            foreach (var leg in item.GetLegs())
            {
                r.OpenClose    = leg.OpenClose;
                leg.Order.Text = r.ToString();
                EmitCancelReject(leg.Order, leg.Order.OrdStatus, r.ToString());
            }
        }
Exemplo n.º 7
0
        public void Should_override_content_type()
        {
            // Given
            const string text = "sample text";

            var response =
                new TextResponse(text, "text/cache-manifest");

            var outputStream = new MemoryStream();

            // When
            response.Contents.Invoke(outputStream);

            // Then
            response.ContentType.ShouldEqual("text/cache-manifest; charset=utf-8");
        }
        public void Should_set_content_type_to_text_plain()
        {
            // Given
            string text =
                "sample text";

            var response =
                new TextResponse(text);

            var outputStream = new MemoryStream();

            // When
            response.Contents.Invoke(outputStream);

            // Then
            response.ContentType.ShouldEqual("text/plain");
        }
        public void Should_be_0_when_text_is_empty_and_body_invoked()
        {
            // Given
            string text
                = string.Empty;

            var response =
                new TextResponse(text);

            var outputStream = new MemoryStream();

            // When
            response.Contents.Invoke(outputStream);

            // then
            outputStream.ToArray().Length.ShouldEqual(0);
        }
        public void Should_copy_text_when_body_invoked()
        {
            // Given
            var text
                = "sample text";

            var response =
                new TextResponse(text);

            var outputStream = new MemoryStream();

            // When
            response.Contents.Invoke(outputStream);

            // Then
            outputStream.ToArray().ShouldEqualSequence(Encoding.UTF8.GetBytes(text));
        }
Exemplo n.º 11
0
        internal static async Task <Response> ProcessRequest(Func <Task <Response> > action)
        {
            var result = new Response {
                StatusCode = HttpStatusCode.OK
            };

            try
            {
                result = await action();
            }
            catch (Exception ex)
            {
                result = new TextResponse(HttpStatusCode.BadRequest, ex.ToString());
            }

            return(result);
        }
Exemplo n.º 12
0
        // [SuperAdminClaim]
        public static Task <IHttpResponse> ResponseAsync(
            [QueryParameter(Name = EastFive.Api.Azure.AzureApplication.QueryRequestIdentfier)]
            IRef <Authorization> authorizationRef,
            TextResponse onCompleted)
        {
            var accountRequest = new AccountRequest()
            {
                accountRequestRef = Ref <AccountRequest> .NewRef(),
                authorization     = authorizationRef,
            };

            return(accountRequest.StorageCreateAsync(
                       discard =>
            {
                return onCompleted("Your account has been requested. Thank you.");
            }));
        }
Exemplo n.º 13
0
        public void Should_include_webname_for_custom_encoding()
        {
            // Given
            string text =
                "sample text";

            var response =
                new TextResponse(text, encoding: Encoding.Unicode);

            var outputStream = new MemoryStream();

            // When
            response.Contents.Invoke(outputStream);

            // Then
            response.ContentType.ShouldEqual("text/plain; charset=utf-16");
        }
Exemplo n.º 14
0
        private void LoginUser(ITelegramUserMessage message,
                               IChatStateHandlerContext context)
        {
            IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager();
            IUserManager    userManager    = ModulesManager.GetModulesManager().GetUserManager();

            bool success = userManager.LoginUser(message.ChatId, message.Message);

            if (success)
            {
                messageManager.SendTextMessage(message.ChatId, TextResponse.Get(ResponseType.SuccessAuthorisation));
                context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized);
            }
            else
            {
                messageManager.SendTextMessage(message.ChatId, TextResponse.Get(ResponseType.FailAuthorisation));
            }
        }
Exemplo n.º 15
0
        void Fix(string uri, int count, int row)
        {
            TextResponse.Clear();

            try
            {
                string response = NetHelp.WebClientGet(uri);

                string reg = @"[<].*?[>]";

                response = Regex.Replace(response, reg, "");

                TextResponse.Text = Regex.Replace(response, @"(?s)\n\s*\n", "\n");
            }
            catch (Exception e)
            {
                TextResponse.Text = e.ToString(); return;
            }

            List <string> lines = new List <string>();

            StringBuilder text = new StringBuilder();

            lines = TextResponse.Lines.ToList();

            lines.RemoveRange(0, count);

            int i = 0;

            foreach (var item in lines)
            {
                i += 1;

                text.AppendLine(item);

                if (i % row == 0)
                {
                    text.AppendLine();
                }
            }

            TextResponse.Text = text.ToString();
        }
Exemplo n.º 16
0
        private TextResponse ProcessLog(NotificationLog log, string requestUrlBase)
        {
            var response = new TextResponse(JsonConvert.SerializeObject(log.NotificationList.ToArray()));
            var sb       = new StringBuilder();

            ResponseHelper.Header.Link.AppendValue(
                sb,
                $"{requestUrlBase}/{log.NotificationLogId}",
                neurUL.Common.Constants.Response.Header.Link.Relation.Self
                );

            if (log.HasFirstNotificationLog)
            {
                ResponseHelper.Header.Link.AppendValue(
                    sb,
                    $"{requestUrlBase}/{log.FirstNotificationLogId}",
                    neurUL.Common.Constants.Response.Header.Link.Relation.First
                    );
            }

            if (log.HasPreviousNotificationLog)
            {
                ResponseHelper.Header.Link.AppendValue(
                    sb,
                    $"{requestUrlBase}/{log.PreviousNotificationLogId}",
                    neurUL.Common.Constants.Response.Header.Link.Relation.Previous
                    );
            }

            if (log.HasNextNotificationLog)
            {
                ResponseHelper.Header.Link.AppendValue(
                    sb,
                    $"{requestUrlBase}/{log.NextNotificationLogId}",
                    neurUL.Common.Constants.Response.Header.Link.Relation.Next
                    );
            }

            response.Headers.Add(neurUL.Common.Constants.Response.Header.Link.Key, sb.ToString());
            response.Headers.Add(neurUL.Common.Constants.Response.Header.TotalCount.Key, log.TotalCount.ToString());
            return(response);
        }
Exemplo n.º 17
0
        private Response CreateUser(dynamic pars)
        {
            TextResponse response;

            using (var reader = new StreamReader(Request.Body))
            {
                var user = JsonConvert.DeserializeObject <User>(reader.ReadToEnd());
                try
                {
                    var result = UserRepository.CreateUser(user, CurrentUser.UserName);
                    return(new TextResponse(HttpStatusCode.Accepted, result.ToString()));
                }
                catch (Exception ex)
                {
                    response = new TextResponse(HttpStatusCode.Conflict, ex.Message);
                }
            }

            return(response);
        }
Exemplo n.º 18
0
        public string GetRspForSearch(HttpSessionStateBase session, HttpRequestBase request, LibrarySearchOption option)
        {
            WeixinResponse rsp = null;
            object         error;
            var            libStopwatch = Stopwatch.StartNew();
            var            result       = Library.GetInstance().SearchBooksFor(session, option, out error);

            if (error == null)
            {
                libStopwatch.Stop();
                rsp = LibrarySearchResponse.Create(request, result);
                ApplicationLogger.GetLogger().Info(String.Format("(" + session.SessionID + ")"
                                                                 + "search library with " + option.Keyword + " consume " + libStopwatch.ElapsedMilliseconds));
            }
            else
            {
                rsp = new TextResponse(option.User, String.Format("查询出错: {0}", error));
            }
            return(rsp.ToString());
        }
Exemplo n.º 19
0
        /*--------------------------------------------------------------------------------------------*/
        private Response GetResponse(ApiEntry pEntry)
        {
            IApiResponse   apiResp = pEntry.Function(NewReq());
            HttpStatusCode status  = (HttpStatusCode)(int)apiResp.Status;
            var            cookies = new List <INancyCookie>();

            foreach (Cookie c in apiResp.Cookies)
            {
                var nc = new NancyCookie(c.Name, c.Value, c.HttpOnly, c.Secure);
                nc.Domain  = c.Domain;
                nc.Expires = c.Expires;
                nc.Path    = c.Path;
                cookies.Add(nc);
            }

            ////

            if (apiResp.RedirectUrl != null)
            {
                var r = new RedirectResponse(apiResp.RedirectUrl);

                foreach (INancyCookie c in cookies)
                {
                    r.Cookies.Add(c);
                }

                return(r);
            }

            if (apiResp.Html != null)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(apiResp.Html);
                return(new HtmlResponse(status, (s => s.Write(bytes, 0, bytes.Length)),
                                        apiResp.Headers, cookies));
            }

            var tr = new TextResponse(status, apiResp.Json, Encoding.UTF8, apiResp.Headers, cookies);

            tr.ContentType = "application/json";
            return(tr);
        }
Exemplo n.º 20
0
        public AbstractResponse GetResponse(ReplyInfo reply, string openId)
        {
            AbstractResponse result;

            if (reply.MessageType == MessageType.Text)
            {
                TextReplyInfo info     = reply as TextReplyInfo;
                TextResponse  response = new TextResponse
                {
                    CreateTime = System.DateTime.Now,
                    Content    = info.Text
                };
                if (reply.Keys == "登录")
                {
                    string str = string.Format("http://{0}/Vshop/Login.aspx?SessionId={1}", System.Web.HttpContext.Current.Request.Url.Host, openId);
                    response.Content = response.Content.Replace("$login$", string.Format("<a href=\"{0}\">一键登录</a>", str));
                }
                result = response;
            }
            else
            {
                NewsResponse response2 = new NewsResponse
                {
                    CreateTime = System.DateTime.Now,
                    Articles   = new System.Collections.Generic.List <Article>()
                };
                foreach (NewsMsgInfo info2 in (reply as NewsReplyInfo).NewsMsg)
                {
                    Article item = new Article
                    {
                        Description = info2.Description,
                        PicUrl      = string.Format("http://{0}{1}", System.Web.HttpContext.Current.Request.Url.Host, info2.PicUrl),
                        Title       = info2.Title,
                        Url         = string.IsNullOrEmpty(info2.Url) ? string.Format("http://{0}/Vshop/ImageTextDetails.aspx?messageId={1}", System.Web.HttpContext.Current.Request.Url.Host, info2.Id) : info2.Url
                    };
                    response2.Articles.Add(item);
                }
                result = response2;
            }
            return(result);
        }
Exemplo n.º 21
0
        private async Task HandleTextResponse(CommandContext context, TextResponse textResponse)
        {
            string resultMsg = "";

            if (textResponse.ShouldMentionSender)
            {
                resultMsg = $"{context.User.Mention}: ";
            }

            if (textResponse.PersonToMention != 0)
            {
                IUser user = await context.Channel.GetUserAsync(textResponse.PersonToMention);

                resultMsg = $"{user.Mention} " + resultMsg;
            }

            resultMsg += $"{textResponse.Text}";
            var wordMsg = await context.Channel.SendMessageAsync(resultMsg);

            await AttemptToDeleteWordMessage(wordMsg.Id, wordMsg.Channel.Id);
        }
Exemplo n.º 22
0
        public void OnRequestCallback()
        {
            var invoked = false;

            var fakeResponse = new TextResponse("OK");
            var fakeRequest  = new Request("GET", new Uri("http://foobar/baz"), 0, null, null);

            var processor = new ShimProcessor("/baz", fakeResponse, (route, request) =>
            {
                // Inspect callback data
                route.Method.Should().Be("GET");
                route.Path.Should().Be("/baz");
                request.Should().Be(fakeRequest);

                invoked = true;
            });

            processor.HandleRequest(fakeRequest)
            .Should().Be(fakeResponse);

            invoked.Should().BeTrue();
        }
Exemplo n.º 23
0
        void FixEx(string uri, int count, int row)
        {
            TextResponse.Clear();

            try
            {
                string response = NetHelp.WebClientGet(uri);

                TextResponse.Text = MyRegex.Span(response);
            }
            catch (Exception e)
            {
                TextResponse.Text = e.ToString(); return;
            }

            List <string> lines = new List <string>();

            StringBuilder text = new StringBuilder();

            lines = TextResponse.Lines.ToList();

            lines.RemoveRange(0, count);

            int i = 0;

            foreach (var item in lines)
            {
                i += 1;

                text.AppendLine(item);

                if (i % row == 0)
                {
                    text.AppendLine();
                }
            }

            TextResponse.Text = text.ToString();
        }
Exemplo n.º 24
0
        public AuthorModule(IAuthorApplicationService authorApplicationService) : base("/identityaccess/authors")
        {
            this.Get(string.Empty, async(parameters) =>
            {
                var result = new Response {
                    StatusCode = HttpStatusCode.OK
                };

                if (this.Request.Query["userid"].HasValue)
                {
                    var author = await authorApplicationService.GetAuthorByUserId(this.Request.Query["userid"].ToString());
                    result     = new TextResponse(JsonConvert.SerializeObject(author));
                }
                else
                {
                    result = new TextResponse(HttpStatusCode.BadRequest, "UserId is invalid or missing.");
                }

                return(result);
            }
                     );
        }
Exemplo n.º 25
0
        private void GetStash(long chatId, IChatStateHandlerContext context)
        {
            IDatabaseManager databaseManager = ModulesManager.GetDatabaseManager();
            IMessageManager  messageManager  = ModulesManager.GetMessageManager();

            IUser user = databaseManager.GetUser(chatId);

            if (user != null && user.IsAuthorized)
            {
                ICollection <IStashMessage> messagesFromStash = databaseManager.GetMessagesFromStash(chatId);
                if (messagesFromStash.Count == 0)
                {
                    messageManager.SendTextMessageAsync(chatId, TextResponse.Get(ResponseType.EmptyStash), null);
                }
                else
                {
                    foreach (IStashMessage stashMessage in messagesFromStash)
                    {
                        stashMessage.Decrypt(user);
                        stashMessage.Send();
                    }
                }
            }
        }
Exemplo n.º 26
0
        private async Task <Response> ProxyRequest(NancyContext context, CancellationToken cancellationToken)
        {
            string path   = context.Request.Path;
            string method = context.Request.Method.ToUpperInvariant();

            if (!path.StartsWith("/nfsw/Engine.svc"))
            {
                throw new ProxyException("Invalid request path: " + path);
            }

            path = path.Substring("/nfsw/Engine.svc".Length);

            Url resolvedUrl = new Url(ServerProxy.Instance.GetServerUrl()).AppendPathSegment(path);

            foreach (var queryParamName in context.Request.Query)
            {
                resolvedUrl = resolvedUrl.SetQueryParam(queryParamName, context.Request.Query[queryParamName],
                                                        NullValueHandling.Ignore);
            }

            IFlurlRequest request = resolvedUrl.AllowAnyHttpStatus();

            foreach (var header in context.Request.Headers)
            {
                request = request.WithHeader(header.Key,
                                             header.Key == "Host" ? resolvedUrl.ToUri().Host : header.Value.First());
            }

            var requestBody = context.Request.Method != "GET" ? context.Request.Body.AsString(Encoding.UTF8) : "";

            CommunicationLog.RecordEntry(ServerProxy.Instance.GetServerName(), "SERVER",
                                         CommunicationLogEntryType.Request,
                                         new CommunicationLogRequest(requestBody, resolvedUrl.ToString(), method));

            HttpResponseMessage responseMessage;

            var POSTContent = String.Empty;

            var queryParams = new Dictionary <string, object>();

            foreach (var param in context.Request.Query)
            {
                var value = context.Request.Query[param];
                queryParams[param] = value;
            }

            var GETContent = string.Join(";", queryParams.Select(x => x.Key + "=" + x.Value).ToArray());

            // ReSharper disable once LocalizableElement
            //Console.WriteLine($"[LOG] [{method}] ProxyHandler: {path}");

            switch (method)
            {
            case "GET":
                responseMessage = await request.GetAsync(cancellationToken);

                break;

            case "POST":
                responseMessage = await request.PostAsync(new CapturedStringContent(requestBody, Encoding.UTF8),
                                                          cancellationToken);

                POSTContent = context.Request.Body.AsString();
                break;

            case "PUT":
                responseMessage = await request.PutAsync(new CapturedStringContent(requestBody, Encoding.UTF8),
                                                         cancellationToken);

                break;

            case "DELETE":
                responseMessage = await request.DeleteAsync(cancellationToken);

                break;

            default:
                throw new ProxyException("Cannot handle request method: " + method);
            }

            var responseBody = await responseMessage.Content.ReadAsStringAsync();

            if (path == "/User/GetPermanentSession")
            {
                responseBody = Self.CleanFromUnknownChars(responseBody);
            }

            int statusCode = (int)responseMessage.StatusCode;

            try
            {
                DiscordGamePresence.HandleGameState(path, responseBody, POSTContent, GETContent);
            }
            catch (Exception e)
            {
                Log.Error($"DISCORD RPC ERROR [handling {context.Request.Path}]");
                Log.Error($"\tMESSAGE: {e.Message}");
                Log.Error($"\t{e.StackTrace}");
                await Self.SubmitError(e);
            }

            TextResponse textResponse = new TextResponse(responseBody,
                                                         responseMessage.Content.Headers.ContentType?.MediaType ?? "application/xml;charset=UTF-8")
            {
                StatusCode = (HttpStatusCode)statusCode
            };

            queryParams.Clear();

            CommunicationLog.RecordEntry(ServerProxy.Instance.GetServerName(), "SERVER",
                                         CommunicationLogEntryType.Response, new CommunicationLogResponse(
                                             responseBody, resolvedUrl.ToString(), method));

            return(textResponse);
        }
Exemplo n.º 27
0
        protected void Application_Start(object sender, EventArgs e)
        {
            LogUtils.Current.InjectLogModule <DbLog>();
            Alan.Log.LogContainerImplement.LogUtils.Current.InjectLogModule(new Alan.Log.ILogImplement.LogAutoSeperateFiles(100 * 1024, System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/wechat.log")));

            WeChat.Core.Utils.FluentConfig.Get()
            .Inject(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Config-Clever.json"))     //注入JSON文件的形式传入配置信息
            .Inject(middleware =>
            {
                //记录请求数据
                LogUtils.Current.LogWithId(category: "/Message/Request/Data", note: middleware.Input.RawRequest);
            })
            .InjectEnd(middleware =>
            {
                if (!middleware.SetedResponse)
                {
                    middleware.SetResponseModel(new TextResponse()
                    {
                        Content = "未匹配规则",
                        MsgType = Configurations.Current.MessageType.Text
                    });
                }
                //记录输出数据
                LogUtils.Current.LogWithId(category: "/Message/Response/Data", note: middleware.GetResponse());
            })
            .InjectEvent(where : evt => evt.Event == "subscribe", setResponse: evt => new TextResponse()
            {
                Content = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/directives.txt"))
            })
            //只有文本消息的内容是 "我的信息" 的时候才执行这个过滤器
            .InjectTxt(req => req.Content == "我的信息", req =>
            {
                //获取微信用户信息
                var user = WeChat.Core.Api.WeChatUserInfo.Get(req.FromUserName);

                return(new TextResponse()
                {
                    Content = String.Format("你的名字是 {0}.", user.NickName),
                    MsgType = WeChat.Core.Utils.Configurations.Current.MessageType.Text
                });
            })
            //下载图片
            .InjectImg(req => true, req =>
            {
                var items = HttpUtils.Get(req.PicUrl, null, null).DownloadFile();
                System.IO.File.WriteAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/" + items.Item1), items.Item2);
                return(new TextResponse
                {
                    Content = "download file ",
                    MsgType = Configurations.Current.MessageType.Text
                });
            })
            .InjectVoice(filter: (req, middle) =>
            {
                try
                {
                    var txt = String.IsNullOrWhiteSpace(req.Recognition) ? "empty" : req.Recognition;
                    var rep = new TextResponse
                    {
                        Content = txt,
                        MsgType = Configurations.Current.MessageType.Text
                    };
                    middle.SetResponseModel(rep);
                }
                catch (Exception ex)
                {
                    LogUtils.Current.LogError(id: Guid.NewGuid().ToString(), date: DateTime.Now, message: ex.Message,
                                              note: ex.StackTrace, position: ex.Source);
                }
            })

            #region cnbeta
            .InjectTxt(where : req => req.Content == "cnbeta", setResponse: req =>
            {
                var url           = "http://www.cnbeta.com";
                WebRequest webReq = WebRequest.Create(url);

                var allLinks = new List <Tuple <string, string> >();

                using (var reader = new StreamReader(webReq.GetResponse().GetResponseStream()))
                {
                    HtmlDocument doc = new HtmlDocument();
                    var html         = reader.ReadToEnd();
                    doc.LoadHtml(html);

                    var articles =
                        doc.DocumentNode.SelectNodes("//div[@class]")
                        .FirstOrDefault(l => l.Attributes["class"].Value == "alllist");

                    if (articles == null)
                    {
                        return new TextResponse()
                        {
                            Content = "Not found articles",
                            MsgType = Configurations.Current.MessageType.Text
                        }
                    }
                    ;

                    allLinks = articles.SelectNodes("//a[@href]")
                               .Select(art => Tuple.Create(art.InnerText, art.Attributes["href"].Value))
                               .ToList();
                }



                var links = from ele in allLinks
                            let matches = Regex.Match(ele.Item2, @"/articles/(\d+)\.htm")
                                          where matches.Success && matches.Groups.Count == 2 && !String.IsNullOrWhiteSpace(ele.Item1)
                                          select String.Format("{0} {1}", matches.Groups[1].Value, ele.Item1);

                var txt = String.Join(Environment.NewLine, links).Trim();
                txt     = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(txt).Take(2000).ToArray());

                var rep = new TextResponse()
                {
                    Content = txt,
                    MsgType = Configurations.Current.MessageType.Text
                };

                return(rep);
            })
            .InjectTxt(where : req => Regex.IsMatch(req.Content, @"cnbeta \d+"), setResponse: req =>
            {
                var url           = String.Format("http://www.cnbeta.com/articles/{0}.htm", req.Content.Split(' ')[1]);
                HtmlDocument doc  = new HtmlDocument();
                WebRequest webReq = WebRequest.Create(url);
                var reader        = new StreamReader(webReq.GetResponse().GetResponseStream());
                var html          = reader.ReadToEnd();
                doc.LoadHtml(html);

                var articleContent =
                    doc.DocumentNode.SelectNodes("//section[@class]")
                    .FirstOrDefault(ele => ele.Attributes["class"].Value == "article_content");
                var textContent =
                    (articleContent == null ? "not found" : articleContent.InnerText)
                    .Replace(Environment.NewLine, "")
                    .Trim();

                var txtBytes = System.Text.Encoding.UTF8.GetBytes(textContent);
                textContent  = System.Text.Encoding.UTF8.GetString(txtBytes.Take(2000).ToArray());
                var rep      = new TextResponse()
                {
                    Content = textContent,
                    MsgType = Configurations.Current.MessageType.Text
                };

                return(rep);
            })
            #endregion

            .InjectTxt((req, middleware) => !middleware.SetedResponse, (req, middleware) => new TextResponse
            {
                Content = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/directives.txt")),
                MsgType = Configurations.Current.MessageType.Text
            });
        }
Exemplo n.º 28
0
 //При получении сообщения от пользователя цвет сервый
 //А строка имеет формат имя : текст
 public Message(TextResponse response)
 {
     Color   = ConsoleColor.Gray;
     Content = $"{response.Sender} : {response.Content}";
 }
Exemplo n.º 29
0
        public void StartStateMessage(long chatId)
        {
            IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager();

            messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.RegistrationReady));
        }
Exemplo n.º 30
0
 protected virtual async void SetContent(TextResponse response, HttpResponseMessage httpResponse)
 {
     response.Content = await httpResponse.Content.ReadAsStringAsync().ForAwait();
 }
Exemplo n.º 31
0
 //Публичный метод для добавления в формe сообщение от третьего лица
 //Просто вызываем AddMessage с экземпляром класса Message, основанном на TextResponse
 public void AddMessage(TextResponse response) => AddMessage(new Message(response));
Exemplo n.º 32
0
        public void Handle(long chatId)
        {
            IMessageManager messageManager = ModulesManager.GetMessageManager();

            messageManager.SendTextMessageAsync(chatId, TextResponse.Get(ResponseType.FullStashError), null);
        }
Exemplo n.º 33
0
        public AbstractResponse GetResponse(Hidistro.Entities.VShop.ReplyInfo reply, string openId)
        {
            string log = string.Concat(new string[]
            {
                reply.MessageType.ToString(),
                "||",
                reply.MessageType.ToString(),
                "||",
                reply.MessageTypeName
            });

            Globals.Debuglog(log, "_DebuglogYY.txt");
            if (reply.MessageType == MessageType.Text)
            {
                TextReplyInfo textReplyInfo = reply as TextReplyInfo;
                TextResponse  textResponse  = new TextResponse();
                textResponse.CreateTime = System.DateTime.Now;
                textResponse.Content    = Globals.FormatWXReplyContent(textReplyInfo.Text);
                if (reply.Keys == "登录")
                {
                    string arg = Globals.GetWebUrlStart() + "/Vshop/MemberCenter.aspx";
                    textResponse.Content = textResponse.Content.Replace("$login$", string.Format("<a href=\"{0}\">一键登录</a>", arg));
                }
                return(textResponse);
            }
            NewsResponse newsResponse = new NewsResponse();

            newsResponse.CreateTime = System.DateTime.Now;
            newsResponse.Articles   = new System.Collections.Generic.List <Article>();
            if (reply.ArticleID > 0)
            {
                ArticleInfo articleInfo = ArticleHelper.GetArticleInfo(reply.ArticleID);
                if (articleInfo.ArticleType == ArticleType.News)
                {
                    Article item = new Article
                    {
                        Description = articleInfo.Memo,
                        PicUrl      = this.FormatImgUrl(articleInfo.ImageUrl),
                        Title       = articleInfo.Title,
                        Url         = (string.IsNullOrEmpty(articleInfo.Url) ? string.Format("http://{0}/Vshop/ArticleDetail.aspx?sid={1}", System.Web.HttpContext.Current.Request.Url.Host, articleInfo.ArticleId) : articleInfo.Url)
                    };
                    newsResponse.Articles.Add(item);
                    return(newsResponse);
                }
                if (articleInfo.ArticleType != ArticleType.List)
                {
                    return(newsResponse);
                }
                Article item2 = new Article
                {
                    Description = articleInfo.Memo,
                    PicUrl      = this.FormatImgUrl(articleInfo.ImageUrl),
                    Title       = articleInfo.Title,
                    Url         = (string.IsNullOrEmpty(articleInfo.Url) ? string.Format("http://{0}/Vshop/ArticleDetail.aspx?sid={1}", System.Web.HttpContext.Current.Request.Url.Host, articleInfo.ArticleId) : articleInfo.Url)
                };
                newsResponse.Articles.Add(item2);
                using (System.Collections.Generic.IEnumerator <ArticleItemsInfo> enumerator = articleInfo.ItemsInfo.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        ArticleItemsInfo current = enumerator.Current;
                        item2 = new Article
                        {
                            Description = "",
                            PicUrl      = this.FormatImgUrl(current.ImageUrl),
                            Title       = current.Title,
                            Url         = (string.IsNullOrEmpty(current.Url) ? string.Format("http://{0}/Vshop/ArticleDetail.aspx?iid={1}", System.Web.HttpContext.Current.Request.Url.Host, current.Id) : current.Url)
                        };
                        newsResponse.Articles.Add(item2);
                    }
                    return(newsResponse);
                }
            }
            foreach (NewsMsgInfo current2 in (reply as NewsReplyInfo).NewsMsg)
            {
                Article item3 = new Article
                {
                    Description = current2.Description,
                    PicUrl      = string.Format("http://{0}{1}", System.Web.HttpContext.Current.Request.Url.Host, current2.PicUrl),
                    Title       = current2.Title,
                    Url         = (string.IsNullOrEmpty(current2.Url) ? string.Format("http://{0}/Vshop/ImageTextDetails.aspx?messageId={1}", System.Web.HttpContext.Current.Request.Url.Host, current2.Id) : current2.Url)
                };
                newsResponse.Articles.Add(item3);
            }
            return(newsResponse);
        }
Exemplo n.º 34
0
        public override AbstractResponse OnEvent_ClickRequest(ClickEventRequest clickEventRequest)
        {
            string userOpenId = clickEventRequest.FromUserName;

            WeiXinHelper.UpdateRencentOpenID(userOpenId);
            AbstractResponse result;

            try
            {
                int menuId = System.Convert.ToInt32(clickEventRequest.EventKey);
                Hidistro.Entities.VShop.MenuInfo menu = VShopHelper.GetMenu(menuId);
                if (menu == null)
                {
                    result = null;
                }
                else
                {
                    if (menu.BindType == BindType.StoreCard)
                    {
                        try
                        {
                            SiteSettings siteSettings = SettingsManager.GetMasterSettings(false);
                            string       access_token = TokenApi.GetToken(siteSettings.WeixinAppId, siteSettings.WeixinAppSecret);
                            access_token = JsonConvert.DeserializeObject <Token>(access_token).access_token;
                            MemberInfo member = MemberProcessor.GetOpenIdMember(userOpenId, "wx");
                            if (member == null)
                            {
                                this.CreatMember(userOpenId, 0, access_token);
                                member = MemberProcessor.GetOpenIdMember(userOpenId, "wx");
                            }
                            string           userHead        = member.UserHead;
                            string           storeLogo       = siteSettings.DistributorLogoPic;
                            string           webStart        = Globals.GetWebUrlStart();
                            string           imageUrl        = "/Storage/master/DistributorCards/MemberCard" + member.UserId + ".jpg";
                            string           mediaid         = string.Empty;
                            int              ReferralId      = 0;
                            string           storeName       = siteSettings.SiteName;
                            string           NotSuccessMsg   = string.Empty;
                            DistributorsInfo distributorInfo = DistributorsBrower.GetDistributorInfo(member.UserId);
                            if (distributorInfo != null)
                            {
                                ReferralId = member.UserId;
                                if (siteSettings.IsShowDistributorSelfStoreName)
                                {
                                    storeName = distributorInfo.StoreName;
                                    storeLogo = distributorInfo.Logo;
                                }
                                imageUrl = "/Storage/master/DistributorCards/StoreCard" + ReferralId + ".jpg";
                            }
                            else if (!siteSettings.IsShowSiteStoreCard)
                            {
                                string content = "您还不是分销商,不能为您生成推广图片,立即<a href='" + webStart + "/Vshop/DistributorCenter.aspx'>申请分销商</a>";
                                if (!string.IsNullOrEmpty(siteSettings.ToRegistDistributorTips))
                                {
                                    content = System.Text.RegularExpressions.Regex.Replace(siteSettings.ToRegistDistributorTips, "{{申请分销商}}", "<a href='" + webStart + "/Vshop/DistributorCenter.aspx'>申请分销商</a>");
                                }
                                result = new TextResponse
                                {
                                    CreateTime   = System.DateTime.Now,
                                    ToUserName   = userOpenId,
                                    FromUserName = clickEventRequest.ToUserName,
                                    Content      = content
                                };
                                return(result);
                            }
                            string postData = string.Empty;
                            string creatingStoreCardTips = siteSettings.CreatingStoreCardTips;
                            if (!string.IsNullOrEmpty(creatingStoreCardTips))
                            {
                                postData = string.Concat(new string[]
                                {
                                    "{\"touser\":\"",
                                    userOpenId,
                                    "\",\"msgtype\":\"text\",\"text\":{\"content\":\"",
                                    Globals.String2Json(creatingStoreCardTips),
                                    "\"}}"
                                });
                                NewsApi.KFSend(access_token, postData);
                            }
                            string filePath = System.Web.HttpContext.Current.Request.MapPath(imageUrl);
                            Task.Factory.StartNew(delegate
                            {
                                try
                                {
                                    System.IO.File.Exists(filePath);
                                    string setJson = System.IO.File.ReadAllText(System.Web.HttpRuntime.AppDomainAppPath + "/Storage/Utility/StoreCardSet.js");
                                    string codeUrl = webStart + "/Follow.aspx?ReferralId=" + ReferralId.ToString();
                                    ScanInfos scanInfosByUserId = ScanHelp.GetScanInfosByUserId(ReferralId, 0, "WX");
                                    if (scanInfosByUserId == null)
                                    {
                                        ScanHelp.CreatNewScan(ReferralId, "WX", 0);
                                        scanInfosByUserId = ScanHelp.GetScanInfosByUserId(ReferralId, 0, "WX");
                                    }
                                    if (scanInfosByUserId != null && !string.IsNullOrEmpty(scanInfosByUserId.CodeUrl))
                                    {
                                        codeUrl = BarCodeApi.GetQRImageUrlByTicket(scanInfosByUserId.CodeUrl);
                                    }
                                    else
                                    {
                                        string token_Message = TokenApi.GetToken_Message(siteSettings.WeixinAppId, siteSettings.WeixinAppSecret);
                                        if (TokenApi.CheckIsRightToken(token_Message))
                                        {
                                            string text = BarCodeApi.CreateTicket(token_Message, scanInfosByUserId.Sceneid, "QR_LIMIT_SCENE", "2592000");
                                            if (!string.IsNullOrEmpty(text))
                                            {
                                                codeUrl = BarCodeApi.GetQRImageUrlByTicket(text);
                                                scanInfosByUserId.CodeUrl        = text;
                                                scanInfosByUserId.CreateTime     = System.DateTime.Now;
                                                scanInfosByUserId.LastActiveTime = System.DateTime.Now;
                                                ScanHelp.updateScanInfosCodeUrl(scanInfosByUserId);
                                            }
                                        }
                                    }
                                    StoreCardCreater storeCardCreater = new StoreCardCreater(setJson, userHead, storeLogo, codeUrl, member.UserName, storeName, ReferralId, member.UserId);
                                    if (storeCardCreater.ReadJson() && storeCardCreater.CreadCard(out NotSuccessMsg))
                                    {
                                        if (ReferralId > 0)
                                        {
                                            DistributorsBrower.UpdateStoreCard(ReferralId, NotSuccessMsg);
                                        }
                                        string media_IDByPath = NewsApi.GetMedia_IDByPath(access_token, webStart + imageUrl);
                                        mediaid = NewsApi.GetJsonValue(media_IDByPath, "media_id");
                                    }
                                    else
                                    {
                                        Globals.Debuglog(NotSuccessMsg, "_DebugCreateStoreCardlog.txt");
                                    }
                                    postData = string.Concat(new string[]
                                    {
                                        "{\"touser\":\"",
                                        userOpenId,
                                        "\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"",
                                        mediaid,
                                        "\"}}"
                                    });
                                    NewsApi.KFSend(access_token, postData);
                                }
                                catch (System.Exception ex3)
                                {
                                    postData = string.Concat(new string[]
                                    {
                                        "{\"touser\":\"",
                                        userOpenId,
                                        "\",\"msgtype\":\"text\",\"text\":{\"content\":\"生成图片失败,",
                                        Globals.String2Json(ex3.ToString()),
                                        "\"}}"
                                    });
                                    NewsApi.KFSend(access_token, postData);
                                }
                            });
                            result = null;
                            return(result);
                        }
                        catch (System.Exception ex)
                        {
                            result = new TextResponse
                            {
                                CreateTime   = System.DateTime.Now,
                                ToUserName   = userOpenId,
                                FromUserName = clickEventRequest.ToUserName,
                                Content      = "问题:" + ex.ToString()
                            };
                            return(result);
                        }
                    }
                    Hidistro.Entities.VShop.ReplyInfo reply = ReplyHelper.GetReply(menu.ReplyId);
                    if (reply == null)
                    {
                        result = null;
                    }
                    else
                    {
                        if (reply.MessageType != MessageType.Image)
                        {
                            AbstractResponse keyResponse = this.GetKeyResponse(reply.Keys, clickEventRequest);
                            if (keyResponse != null)
                            {
                                result = keyResponse;
                                return(result);
                            }
                        }
                        AbstractResponse response = this.GetResponse(reply, clickEventRequest.FromUserName);
                        if (response == null)
                        {
                            this.GotoManyCustomerService(clickEventRequest);
                        }
                        response.ToUserName   = clickEventRequest.FromUserName;
                        response.FromUserName = clickEventRequest.ToUserName;
                        result = response;
                    }
                }
            }
            catch (System.Exception ex2)
            {
                result = new TextResponse
                {
                    CreateTime   = System.DateTime.Now,
                    ToUserName   = clickEventRequest.FromUserName,
                    FromUserName = clickEventRequest.ToUserName,
                    Content      = "问题:" + ex2.ToString()
                };
            }
            return(result);
        }
Exemplo n.º 35
0
 public static ContentResponseAssertions Should(this TextResponse response)
 {
     return(new ContentResponseAssertions(response));
 }
Exemplo n.º 36
0
 public virtual void Materialize(TextResponse response, HttpResponseMessage httpResponse)
 {
     SetContent(response, httpResponse);
 }