Пример #1
0
        public void ClearPostCount(object sender, PostEventArgs p)
        {
            var context = sender as Controller;

            if (p.Model != null)
            {
                switch (p.Model.IdType)
                {
                case ItemType.Blog:
                    var cache = _cache.Get <ConcurrentDictionary <int, int> >(PostCountCacheKey);
                    if (cache != null)
                    {
                        int notused;
                        cache.TryRemove(p.Model.ItemId, out notused);
                    }
                    break;

                case ItemType.Topic:
                    var tcache = _cache.Get <ConcurrentDictionary <int, int> >(PostCountCacheKey + "T");
                    if (tcache != null)
                    {
                        int notused;
                        tcache.TryRemove(p.Model.ItemId, out notused);
                    }
                    break;

                default:
                    break;
                }
            }
        }
Пример #2
0
 public AdminFirePostDelegateRequest(string contextInfo, string name, PostEventArgs args, byte[] argData)
 {
     this.contextInfo = contextInfo;
     this.name        = name;
     this.args        = args;
     this.argData     = argData;
 }
Пример #3
0
        protected virtual PostResponse Posting(BoardInfo board, byte[] data, string uri, ref bool retried)
        {
            HttpWebResponse    res = null;
            PostResponseParser parser;

            const int timeout = 30000;
            string    referer = board.Url + "index.html";

            try {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                req.Method            = "POST";
                req.Accept            = "*/*";
                req.ContentType       = "application/x-www-form-urlencoded";
                req.ContentLength     = data.Length;
                req.Referer           = referer;
                req.Timeout           = timeout;
                req.ReadWriteTimeout  = timeout;
                req.UserAgent         = UserAgent;
                req.AllowAutoRedirect = false;
                req.Proxy             = Proxy;

                Stream st = req.GetRequestStream();
                st.Write(data, 0, data.Length);
                st.Close();

                res = (HttpWebResponse)req.GetResponse();

                // レスポンスを解析
                using (TextReader reader = new StreamReader(res.GetResponseStream(), Encoding))
                {
                    parser   = new PostResponseParser(reader.ReadToEnd());
                    response = parser.Response;

                    // <TITLE>302 Found</TITLE>が返ってきたら書き込み成功
//					if (res.StatusCode == HttpStatusCode.Found)
//						response = PostResponse.Success;
                }

                // 投稿イベントを発生させる
                PostEventArgs e = new PostEventArgs(response, parser.Title, parser.PlainText, null, -1);
                OnPosted(this, e);

                // 既にリトライされていたら無限ループ防止のためfalseに設定
                retried = retried ? false : e.Retry;
            }
            catch (Exception ex)
            {
                TwinDll.Output(ex);
                OnError(this, new PostErrorEventArgs(ex));
            }
            finally {
                if (res != null)
                {
                    res.Close();
                }
            }

            return(response);
        }
Пример #4
0
 void ga_RenderPostBody(StringBuilder sb, PostEventArgs e)
 {
     // Embed TrackBack RDF info for this post
     if (EnableTrackbacks && e.RenderLocation == PostRenderLocation.Web && e.Post.EnableComments && e.Post.EnableNewComments)
     {
         sb.Append(TrackBackHandler.GenerateTrackbackRDF(e.Post));
     }
 }
Пример #5
0
        void ga_RssItem(XmlTextWriter writer, PostEventArgs e)
        {
            if (EnableGeoRSS)
            {
                string location = e.Post.Custom(_geoRSSCustomFieldName);
                if (string.IsNullOrEmpty(location))
                {
                    location = GeoRSSLocation;
                }

                writer.WriteElementString("georss:point", location);
            }
        }
Пример #6
0
        protected bool ProcessPost(HttpListenerContext context)
        {
            PostEventArgs <Dictionary <string, object> > eventArgs = new PostEventArgs <Dictionary <string, object> >()
            {
                AskedDate = DateTime.Now, AskedUrl = context.Request.Url
            };
            bool result;

            if (AllowPost)
            {
                result = ProcessPostSql(context, PostQuery(context.Request.QueryString));
            }
            else
            {
                result = Process403(context);
            }
            eventArgs.EndDate = DateTime.Now;
            eventArgs.ResponseHttpStatusCode = (HttpStatusCode)context.Response.StatusCode;
            OnPostAction(eventArgs);
            return(result);
        }
Пример #7
0
        public async Task UpdatePostCountAsync(PostEventArgs p)
        {
            if (p.Model.IdType == ItemType.Blog)
            {
                using (var scope = _scopeFactory.CreateScope())
                {
                    var util   = scope.ServiceProvider.GetService <ContextlessBlogUtil>();
                    var result = await _client.UpdateAsync <BlogIndexed, object>(DocumentPath <BlogIndexed> .Id(p.Model.ItemId), ud => ud.Doc(new { PostCount = util.GetBlogPostCount(p.Model.ItemId) }).Refresh(Elasticsearch.Net.Refresh.True));

                    if (!result.IsValid)
                    {
                        _logger.LogError(result.DebugInformation);
                        var db   = scope.ServiceProvider.GetService <BlogContext>();
                        var blog = await db.Blogs.FindAsync(p.Model.ItemId);

                        if (blog != null)
                        {
                            await AddOrUpdateBlogAsync(new BlogEventArgs(blog));
                        }
                    }
                }
            }
        }
        void ga_RssItem(System.Xml.XmlTextWriter writer, PostEventArgs e)
        {
            if (EnableRssCategories)
            {
                string categories = e.Post.Custom(categoryFieldName);
                if (categories == null || categories.Length == 0)
                {
                    return;
                }
                string[] categoryItems = categories.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string category in categoryItems)
                {
                    string[] categoryParts = category.Split(new string[] { "$" }, StringSplitOptions.RemoveEmptyEntries);
                    writer.WriteStartElement("category");
                    if (categoryParts.Length == 2)
                    {
                        writer.WriteAttributeString("domain", categoryParts[1]);
                    }
                    writer.WriteString(categoryParts[0]);
                    writer.WriteEndElement();
                }
            }
        }
Пример #9
0
 protected virtual void OnPostAction(PostEventArgs <string> e)
 {
     OnPost?.Invoke(this, e);
 }
Пример #10
0
 private static void Bot_PostReceived(PostEventArgs e)
 {
     Console.WriteLine($"\nPOST:\n{e.Body}");
 }
Пример #11
0
 private static void Bot_PostFailed(PostEventArgs e)
 {
     Console.WriteLine($"\nVRONG POST:\n{e.Body}");
 }
Пример #12
0
 public static Job UpdatePostCount(PostEventArgs args)
 => new Job
 {
     JobType = JobType.UpdatePostCount, UpdatePostCountArgs = args
 };
Пример #13
0
 protected virtual void OnPostAction(PostEventArgs <ObjectType> e)
 {
     OnPost?.Invoke(this, e);
 }
Пример #14
0
        /// <summary>
        /// dataをサーバーに送信しレスポンスを得る
        /// </summary>
        /// <param name="data"></param>
        protected virtual PostResponse Posting(BoardInfo board, byte[] data, string uri, ref bool retried)
        {
            if (board == null)
            {
                throw new ArgumentNullException("board");
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            HttpWebResponse    res    = null;
            PostResponseParser parser = null;

            // タイムアウト値
            const int timeout = 15000;             // 15秒

            // 再試行を行うかどうか
            bool is_retry = true;

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                req.Method           = "POST";
                req.ContentType      = "application/x-www-form-urlencoded";
                req.ContentLength    = data.Length;
                req.Referer          = board.Url + "index.html";
                req.UserAgent        = UserAgent;
                req.Timeout          = timeout;
                req.ReadWriteTimeout = timeout;
                req.Proxy            = Proxy;
                //				req.Accept = "text/html, */*";
                //				req.Expect = null;
                //				req.AllowAutoRedirect = false;
                //				req.ProtocolVersion = HttpVersion.Version10;

                // NTwin 2011/05/31
                //req.CookieContainer = GetCookie(board);

                req.CookieContainer = CookieManager.gCookies;

#if DEBUG
                foreach (Cookie c in req.CookieContainer.GetCookies(req.RequestUri))
                {
                    Console.WriteLine("{0}={1}", c.Name, c.Value);
                }
#endif
                SetHttpWebRequest(req);

                Stream st = req.GetRequestStream();
                st.Write(data, 0, data.Length);
                st.Close();

                res = (HttpWebResponse)req.GetResponse();

                // レスポンスを解析するためのパーサを初期化。
                using (TextReader reader = new StreamReader(res.GetResponseStream(), Encoding))
                {
                    parser   = new PostResponseParser(reader.ReadToEnd());
                    response = parser.Response;

                    if (response == PostResponse.Cookie)
                    {
                        foreach (KeyValuePair <string, string> kv in parser.HiddenParams)
                        {
                            if (Regex.IsMatch(kv.Key, "subject|FROM|mail|MESSAGE|bbs|time|key") == false)
                            {
                                TwinDll.AditionalAgreementField = String.Format("&{0}={1}",
                                                                                kv.Key, kv.Value);

                                Console.WriteLine(TwinDll.AditionalAgreementField);
                                break;
                            }
                        }
                    }
                }

                if (res.StatusCode == HttpStatusCode.Found)
                {
                    response = PostResponse.Success;
                }

                /*
                 * board.CookieContainer = new CookieContainer();
                 *
                 * bool ponIsExist = false;
                 *
                 * foreach (Cookie c in req.CookieContainer.GetCookies(req.RequestUri))
                 * {
                 #if DEBUG
                 *      Console.WriteLine("{0}={1}", c.Name, c.Value);
                 #endif
                 *      if (c.Name == "PON")
                 *              ponIsExist = true;
                 *      board.CookieContainer.Add(c);
                 * }
                 *
                 * if (!ponIsExist && response == PostResponse.Cookie)
                 * {
                 *      board.CookieContainer.Add(res.Cookies);
                 * }*/

                // 投稿イベントを発生させる
                PostEventArgs e = new PostEventArgs(response, parser.Title,
                                                    parser.PlainText, null, parser.SambaCount);

                OnPosted(this, e);

                is_retry = e.Retry;
            }
            catch (Exception ex)
            {
#if DEBUG
                WebException webex = ex as WebException;
                if (webex != null)
                {
                    TwinDll.ShowOutput("Status " + webex.Status + ", " + webex.ToString());
                }
                else
                {
                    TwinDll.ShowOutput(ex);
                }
#endif
                // タイムアウトやそれ以外の例外が発生したら無条件でリトライを中止
                //is_retry = false;
                OnError(this, new PostErrorEventArgs(ex));
            }
            finally {
                if (res != null)
                {
                    res.Close();
                }

                // クッキー確認などでの再試行処理
                // ※既に再試行されていたら無限ループ防止のためfalseに設定
                if (retried)
                {
                    retried = false;
                }
                else
                {
                    retried = is_retry;
                }
            }

            return(response);
        }
Пример #15
0
 public void OnPostCreated(object sender, PostEventArgs args)
 {
     Console.WriteLine("MessageService: A new post has been created!");
     Console.WriteLine($"{args.Post.Date}\n{args.Post.Content}\n");
 }
Пример #16
0
 protected void OnPostAction(PostEventArgs <Dictionary <string, object> > e)
 {
     OnPost?.Invoke(this, e);
 }
Пример #17
0
        protected bool ProcessPost(HttpListenerContext context)
        {
            PostEventArgs <ObjectType> eventArgs = new PostEventArgs <ObjectType>()
            {
                AskedDate = DateTime.Now, AskedUrl = context.Request.Url
            };
            bool result = true;

            try
            {
                if (!context.Request.HasEntityBody)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    result = false;
                }
                else
                {
                    string parameters = null;
                    using (System.IO.Stream body = context.Request.InputStream)
                    {
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(body, context.Request.ContentEncoding))
                        {
                            parameters = reader.ReadToEnd();
                        }
                    }

                    if (string.IsNullOrWhiteSpace(parameters))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        result = false;
                    }
                    else
                    {
                        ObjectType objFromParameters = JsonSerializer.Deserialize <ObjectType>(parameters);

                        if (!Item.Any(item => item.GetType().GetProperties().Where(prop => System.Attribute.IsDefined(prop, typeof(PrimaryKeyAttribute))).All(prop => prop.GetValue(item).Equals(prop.GetValue(objFromParameters)))))
                        {
                            Item.Add(objFromParameters);
                            eventArgs.New = objFromParameters;
                        }
                        else
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            result = false;
                        }
                    }
                }
            }
            catch
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                result = false;
            }

            eventArgs.EndDate = DateTime.Now;
            eventArgs.ResponseHttpStatusCode = (HttpStatusCode)context.Response.StatusCode;
            OnPostAction(eventArgs);

            PrepareResponse(context);
            return(result);
        }