Exemplo n.º 1
0
        private void ok_Clicked(object sender, EventArgs e)
        {
            project.BrowsingUrl   = browsing.Text;
            project.EditingUrl    = editing.Text;
            project.LocalCacheDir = localCache.Text;

            BlogXBrowsing browse = new BlogXBrowsing();

            browse.Url = project.BrowsingUrl;
            XmlNode      nodeRoot = browse.GetRssWithDayCount(1);
            StringWriter sw       = new StringWriter();

            nodeRoot.WriteTo(new XmlTextWriter(sw));
            XmlSerializer ser  = new XmlSerializer(typeof(RssRoot));
            RssRoot       root = (RssRoot)ser.Deserialize(new StringReader(sw.ToString()));

            project.Name = root.Channels[0].Title;

            if (project.LocalCacheDir == null || project.LocalCacheDir == "")
            {
                project.LocalCacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WinBlogX\\Cache\\" + project.Name);
            }

            Directory.CreateDirectory(project.LocalCacheDir);

            DialogResult = DialogResult.OK;
        }
Exemplo n.º 2
0
        public IActionResult RssByCategory(string category)
        {
            RssRoot rss = null;

            if (!memoryCache.TryGetValue(RSS_CACHE_KEY + "_" + category, out rss))
            {
                rss = subscriptionManager.GetRssCategory(category);

                var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5));

                memoryCache.Set(RSS_CACHE_KEY + "_" + category, rss, cacheEntryOptions);
            }

            return(Ok(rss));
        }
Exemplo n.º 3
0
        public IActionResult Rss()
        {
            RssRoot rss = null;

            if (!_cache.TryGetValue(RSS_CACHE_KEY, out rss))
            {
                rss = _subscriptionManager.GetRss();

                var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5));

                _cache.Set(RSS_CACHE_KEY, rss, cacheEntryOptions);
            }

            return(Ok(rss));
        }
Exemplo n.º 4
0
        public void Run()
        {
            SiteConfig          siteConfig     = SiteConfig.GetSiteConfig(configPath);
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(logPath);
            IBlogDataService    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


            loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

                    SyndicationServiceImplementation syndicator = new SyndicationServiceImplementation(siteConfig, dataService, loggingService);

                    if (siteConfig.EnableXSSUpstream &&
                        siteConfig.XSSUpstreamPassword != null &&
                        siteConfig.XSSUpstreamUsername != null)
                    {
                        try
                        {
                            MemoryStream  memoryStream = new MemoryStream();
                            StreamWriter  streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
                            XmlSerializer ser          = new XmlSerializer(typeof(RssRoot));
                            RssRoot       root         = syndicator.GetRss();
                            ser.Serialize(streamWriter, root);



                            XmlStorageSystemClientProxy xssProxy = new XmlStorageSystemClientProxy();
                            if (siteConfig.XSSUpstreamEndpoint != null && siteConfig.XSSUpstreamEndpoint.Length > 0)
                            {
                                xssProxy.Url = siteConfig.XSSUpstreamEndpoint;
                            }

                            string rssFileName = "rss-dasblog.xml";
                            if (siteConfig.XSSRSSFilename != null && siteConfig.XSSRSSFilename.Length > 0)
                            {
                                rssFileName = siteConfig.XSSRSSFilename;
                            }

                            // the buffer is longer than the output and must be shortened
                            // by copying into a new buffer
                            byte[] rssBuffer          = new byte[memoryStream.Position];
                            byte[] memoryStreamBuffer = memoryStream.GetBuffer();
                            for (int l = 0; l < rssBuffer.Length; l++)
                            {
                                rssBuffer[l] = memoryStreamBuffer[l];
                            }


                            XSSSaveMultipleFilesReply reply =
                                xssProxy.SaveMultipleFiles(
                                    siteConfig.XSSUpstreamUsername,
                                    XmlStorageSystemClientProxy.EncodePassword(siteConfig.XSSUpstreamPassword),
                                    new string[] { rssFileName },
                                    new byte[][] { rssBuffer });

                            if (reply.flError)
                            {
                                loggingService.AddEvent(
                                    new EventDataItem(
                                        EventCodes.XSSUpstreamError, reply.message, null, null));
                            }
                            else
                            {
                                loggingService.AddEvent(
                                    new EventDataItem(
                                        EventCodes.XSSUpstreamSuccess, reply.message, rssFileName, xssProxy.Url));
                            }
                        }
                        catch (Exception e)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(
                                    EventCodes.XSSUpstreamError, e.Message, e.StackTrace, null));
                        }
                    }

                    upstreamTrigger.WaitOne(TimeSpan.FromSeconds(siteConfig.XSSUpstreamInterval), false);

                    // introduce a little time offset to limit competition for the files.
                    Thread.Sleep(500);
                }
                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 4 minutes in that case
                    Thread.Sleep(TimeSpan.FromSeconds(240));
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                }
            }while (true);
            loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceShutdown, "", ""));
        }
        private RssRoot GetRssCore(string category, int maxDayCount, int maxEntryCount)
        {
            EntryCollection entries = null;

            //We only build the entries if blogcore doesn't exist and we'll need them later...
            if (_dataService.GetLastEntryUpdate() == DateTime.MinValue)
            {
                entries = BuildEntries(category, maxDayCount, maxEntryCount);
            }

            // TODO: Detecting modified data?
            //DateTime lastModified = this.GetLatestModifedEntryDateTime(entries);

            //if (SiteUtilities.GetStatusNotModified(lastModified))
            //    return null;

            RssRoot documentRoot = new RssRoot();;

            //However, if we made it this far, the not-modified check didn't work, and we may not have entries...
            if (entries == null)
            {
                entries = BuildEntries(category, maxDayCount, maxEntryCount);
            }

            documentRoot.Namespaces.Add("dc", "http://purl.org/dc/elements/1.1/");
            documentRoot.Namespaces.Add("trackback", "http://madskills.com/public/xml/rss/module/trackback/");
            documentRoot.Namespaces.Add("pingback", "http://madskills.com/public/xml/rss/module/pingback/");
            if (_dasBlogSettings.SiteConfiguration.EnableComments)
            {
                documentRoot.Namespaces.Add("wfw", "http://wellformedweb.org/CommentAPI/");
                documentRoot.Namespaces.Add("slash", "http://purl.org/rss/1.0/modules/slash/");
            }
            if (_dasBlogSettings.SiteConfiguration.EnableGeoRss)
            {
                documentRoot.Namespaces.Add("georss", "http://www.georss.org/georss");
            }

            RssChannel ch = new RssChannel();

            if (category == null)
            {
                ch.Title = _dasBlogSettings.SiteConfiguration.Title;
            }
            else
            {
                ch.Title = _dasBlogSettings.SiteConfiguration.Title + " - " + category;
            }

            if (_dasBlogSettings.SiteConfiguration.Description == null || _dasBlogSettings.SiteConfiguration.Description.Trim().Length == 0)
            {
                ch.Description = _dasBlogSettings.SiteConfiguration.Subtitle;
            }
            else
            {
                ch.Description = _dasBlogSettings.SiteConfiguration.Description;
            }

            ch.Link      = _dasBlogSettings.GetBaseUrl();
            ch.Copyright = _dasBlogSettings.SiteConfiguration.Copyright;
            if (_dasBlogSettings.SiteConfiguration.RssLanguage != null && _dasBlogSettings.SiteConfiguration.RssLanguage.Length > 0)
            {
                ch.Language = _dasBlogSettings.SiteConfiguration.RssLanguage;
            }
            ch.ManagingEditor = _dasBlogSettings.SiteConfiguration.Contact;
            ch.WebMaster      = _dasBlogSettings.SiteConfiguration.Contact;
            ch.Image          = null;
            if (_dasBlogSettings.SiteConfiguration.ChannelImageUrl != null && _dasBlogSettings.SiteConfiguration.ChannelImageUrl.Trim().Length > 0)
            {
                newtelligence.DasBlog.Web.Services.Rss20.ChannelImage channelImage = new newtelligence.DasBlog.Web.Services.Rss20.ChannelImage();
                channelImage.Title = ch.Title;
                channelImage.Link  = ch.Link;
                if (_dasBlogSettings.SiteConfiguration.ChannelImageUrl.StartsWith("http"))
                {
                    channelImage.Url = _dasBlogSettings.SiteConfiguration.ChannelImageUrl;
                }
                else
                {
                    channelImage.Url = _dasBlogSettings.RelativeToRoot(_dasBlogSettings.SiteConfiguration.ChannelImageUrl);
                }
                ch.Image = channelImage;
            }

            documentRoot.Channels.Add(ch);

            foreach (Entry entry in entries)
            {
                if (entry.IsPublic == false || entry.Syndicated == false)
                {
                    continue;
                }
                XmlDocument       doc2        = new XmlDocument();
                List <XmlElement> anyElements = new List <XmlElement>();
                RssItem           item        = new RssItem();
                item.Title            = entry.Title;
                item.Guid             = new newtelligence.DasBlog.Web.Services.Rss20.Guid();
                item.Guid.IsPermaLink = false;
                item.Guid.Text        = _dasBlogSettings.GetPermaLinkUrl(entry.EntryId);
                item.Link             = _dasBlogSettings.GetPermaLinkUrl(entry.EntryId);
                User user = _dasBlogSettings.GetUser(entry.Author);

                XmlElement trackbackPing = doc2.CreateElement("trackback", "ping", "http://madskills.com/public/xml/rss/module/trackback/");
                trackbackPing.InnerText = _dasBlogSettings.GetTrackbackUrl(entry.EntryId);
                anyElements.Add(trackbackPing);

                XmlElement pingbackServer = doc2.CreateElement("pingback", "server", "http://madskills.com/public/xml/rss/module/pingback/");
                pingbackServer.InnerText = _dasBlogSettings.RelativeToRoot("pingback");
                anyElements.Add(pingbackServer);

                XmlElement pingbackTarget = doc2.CreateElement("pingback", "target", "http://madskills.com/public/xml/rss/module/pingback/");
                pingbackTarget.InnerText = _dasBlogSettings.GetPermaLinkUrl(entry.EntryId);
                anyElements.Add(pingbackTarget);

                XmlElement dcCreator = doc2.CreateElement("dc", "creator", "http://purl.org/dc/elements/1.1/");
                if (user != null)
                {
                    dcCreator.InnerText = user.DisplayName;
                }
                anyElements.Add(dcCreator);

                // Add GeoRSS if it exists.
                if (_dasBlogSettings.SiteConfiguration.EnableGeoRss)
                {
                    Nullable <double> latitude  = new Nullable <double>();
                    Nullable <double> longitude = new Nullable <double>();

                    if (entry.Latitude.HasValue)
                    {
                        latitude = entry.Latitude;
                    }
                    else
                    {
                        if (_dasBlogSettings.SiteConfiguration.EnableDefaultLatLongForNonGeoCodedPosts)
                        {
                            latitude = _dasBlogSettings.SiteConfiguration.DefaultLatitude;
                        }
                    }

                    if (entry.Longitude.HasValue)
                    {
                        longitude = entry.Longitude;
                    }
                    else
                    {
                        if (_dasBlogSettings.SiteConfiguration.EnableDefaultLatLongForNonGeoCodedPosts)
                        {
                            longitude = _dasBlogSettings.SiteConfiguration.DefaultLongitude;
                        }
                    }

                    if (latitude.HasValue && longitude.HasValue)
                    {
                        XmlElement geoLoc = doc2.CreateElement("georss", "point", "http://www.georss.org/georss");
                        geoLoc.InnerText = String.Format(CultureInfo.InvariantCulture, "{0:R} {1:R}", latitude, longitude);
                        anyElements.Add(geoLoc);
                    }
                }

                if (_dasBlogSettings.SiteConfiguration.EnableComments)
                {
                    if (entry.AllowComments)
                    {
                        XmlElement commentApi = doc2.CreateElement("wfw", "comment", "http://wellformedweb.org/CommentAPI/");
                        commentApi.InnerText = _dasBlogSettings.GetCommentViewUrl(entry.EntryId);
                        anyElements.Add(commentApi);
                    }

                    XmlElement commentRss = doc2.CreateElement("wfw", "commentRss", "http://wellformedweb.org/CommentAPI/");
                    commentRss.InnerText = _dasBlogSettings.GetEntryCommentsRssUrl(entry.EntryId);
                    anyElements.Add(commentRss);

                    //for RSS conformance per FeedValidator.org
                    int commentsCount = _dataService.GetPublicCommentsFor(entry.EntryId).Count;
                    if (commentsCount > 0)
                    {
                        XmlElement slashComments = doc2.CreateElement("slash", "comments", "http://purl.org/rss/1.0/modules/slash/");
                        slashComments.InnerText = commentsCount.ToString();
                        anyElements.Add(slashComments);
                    }
                    item.Comments = _dasBlogSettings.GetCommentViewUrl(entry.EntryId);
                }
                item.Language = entry.Language;

                if (entry.Categories != null && entry.Categories.Length > 0)
                {
                    if (item.Categories == null)
                    {
                        item.Categories = new RssCategoryCollection();
                    }

                    string[] cats = entry.Categories.Split(';');
                    foreach (string c in cats)
                    {
                        RssCategory cat      = new RssCategory();
                        string      cleanCat = c.Replace('|', '/');
                        cat.Text = cleanCat;
                        item.Categories.Add(cat);
                    }
                }
                if (entry.Attachments.Count > 0)
                {
                    // RSS currently supports only a single enclsoure so we return the first one
                    item.Enclosure        = new Enclosure();
                    item.Enclosure.Url    = entry.Attachments[0].Name;
                    item.Enclosure.Type   = entry.Attachments[0].Type;
                    item.Enclosure.Length = entry.Attachments[0].Length.ToString();
                }
                item.PubDate = entry.CreatedUtc.ToString("R");
                if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                {
                    ch.LastBuildDate = item.PubDate;
                }


                if (!_dasBlogSettings.SiteConfiguration.AlwaysIncludeContentInRSS &&
                    entry.Description != null &&
                    entry.Description.Trim().Length > 0)
                {
                    item.Description = PreprocessItemContent(entry.EntryId, entry.Description);
                }
                else
                {
                    if (_dasBlogSettings.SiteConfiguration.HtmlTidyContent == false)
                    {
                        item.Description = "<div>" + PreprocessItemContent(entry.EntryId, entry.Content) + "</div>";
                    }
                    else
                    {
                        item.Description = ContentFormatter.FormatContentAsHTML(PreprocessItemContent(entry.EntryId, entry.Content));


                        try
                        {
                            string xhtml = ContentFormatter.FormatContentAsXHTML(PreprocessItemContent(entry.EntryId, entry.Content));
                            doc2.LoadXml(xhtml);
                            anyElements.Add((XmlElement)doc2.SelectSingleNode("//*[local-name() = 'body'][namespace-uri()='http://www.w3.org/1999/xhtml']"));
                        }
                        catch //(Exception ex)
                        {
                            //Debug.Write(ex.ToString());
                            // absorb
                        }
                    }
                }

                item.anyElements = anyElements.ToArray();
                ch.Items.Add(item);
            }

            return(documentRoot);
        }
Exemplo n.º 6
0
        private XmlNode GetRssCore(string category, int maxDayCount)
        {
            BlogXData.Resolver = new ResolveFileCallback(ResolvePath);

            RssRoot    r      = new RssRoot();
            RssChannel ch     = new RssChannel();
            SiteConfig config = SiteConfig.GetSiteConfig();

            ch.Title          = config.Title;
            ch.Link           = config.Root;
            ch.Copyright      = config.Copyright;
            ch.ManagingEditor = config.Contact;
            ch.WebMaster      = config.Contact;
            r.Channels.Add(ch);

            BlogXData       data    = new BlogXData();
            EntryCollection entries = BuildEntries(data, category, maxDayCount);

            using (StreamWriter sw = new StreamWriter(Server.MapPath(Path.Combine("logs", "dump.txt"))))
            {
                DateTime latest = new DateTime(0);

                foreach (Entry entry in entries)
                {
                    DateTime created = entry.Created;
                    if (created > latest)
                    {
                        latest = created;
                    }
                }

                HttpRequest  req         = Context.Request;
                HttpResponse res         = Context.Response;
                bool         notModified = false;

                // Check the request's if-modified-since field.
                // If it matches our last build date, then the
                // caller already has the most recent data and
                // we can abort the whole process with an
                // error 304: Not Modified

                string ifModifiedSince = req.Headers["if-modified-since"];
                if (ifModifiedSince != null)
                {
                    DateTime modDate = latest;
                    modDate = new DateTime(modDate.Year, modDate.Month, modDate.Day, modDate.Hour, modDate.Minute, modDate.Second);
                    try
                    {
                        DateTime ifModDate = DateTime.Parse(ifModifiedSince);
                        notModified = (ifModDate == modDate);
                    }
                    catch {}
                }

                // Also check the request for an etag header and
                // see if it maches our date.  The rules are if
                // both headers are there, they both have to match.  But,
                // if only one header is there only it has to match.

                string etag = req.Headers["etag"];
                if (etag != null)
                {
                    notModified = (etag.Equals(latest.Ticks.ToString()));
                }

                if (notModified)
                {
                    res.StatusCode      = 304;
                    res.SuppressContent = true;
                    return(null);
                }

                // Either no one used if-modified-since or we have
                // new data.  Record the last modified time and
                // etag in the http header for next time.

                res.Cache.SetLastModified(latest);
                res.Cache.SetETag(latest.Ticks.ToString());
            }

            BlogXUtils.TrackReferrer(Context.Request, Server);

            foreach (Entry entry in entries)
            {
                RssItem item = new RssItem();
                item.Title    = entry.Title;
                item.Guid     = item.Link = new Uri(new Uri(config.Root), " PermaLink.aspx/" + entry.EntryId).ToString();
                item.Comments = new Uri(new Uri(config.Root), "CommentView.aspx/" + entry.EntryId).ToString();
                if (entry.Categories != null && entry.Categories.Length > 0)
                {
                    item.Category = entry.GetSplitCategories()[0];
                }
                item.PubDate = entry.Created.ToString("R");
                if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                {
                    ch.LastBuildDate = item.PubDate;
                }
                if (entry.Description != null && entry.Description.Trim().Length > 0)
                {
                    item.Description = entry.Description;
                }
                else
                {
                    item.Description = entry.Content;
                }

                XmlDocument doc2 = new XmlDocument();
                try
                {
                    doc2.LoadXml(entry.Content);
                    item.Body = (XmlElement)doc2.SelectSingleNode("//*[local-name() = 'body'][namespace-uri()='http://www.w3.org/1999/xhtml']");
                }
                catch {}

                ch.Items.Add(item);
            }

            XmlSerializer ser    = new XmlSerializer(typeof(RssRoot));
            StringWriter  writer = new StringWriter();

            ser.Serialize(writer, r);

            XmlDocument doc = new XmlDocument();

            doc.Load(new StringReader(writer.ToString()));

            return(doc.FirstChild.NextSibling);
        }
Exemplo n.º 7
0
        private RssRoot GetCommentsRssCore(CommentCollection _com, string guid)
        {
            //Try to get out as soon as possible with as little CPU as possible
            if (inASMX)
            {
                DateTime lastModified = SiteUtilities.GetLatestModifedCommentDateTime(dataService, _com);
                if (SiteUtilities.GetStatusNotModified(lastModified))
                {
                    return(null);
                }
            }

            if (inASMX)
            {
                string referrer = Context.Request.UrlReferrer != null?Context.Request.UrlReferrer.AbsoluteUri:"";
                if (ReferralBlackList.IsBlockedReferrer(referrer) == false)
                {
                    loggingService.AddReferral(
                        new LogDataItem(
                            Context.Request.RawUrl,
                            referrer,
                            Context.Request.UserAgent,
                            Context.Request.UserHostName));
                }
            }

            // TODO: Figure out why this code is copied and pasted from above rather than using a function (shame!)
            RssRoot    documentRoot = new RssRoot();
            RssChannel ch           = new RssChannel();

            if (guid != null && guid != String.Empty)
            {
                //Set the title for this RSS Comments feed
                ch.Title = siteConfig.Title + " - Comments on " + dataService.GetEntry(guid).Title;
            }
            else
            {
                ch.Title = siteConfig.Title + " - Comments";
            }
            ch.Link           = SiteUtilities.GetBaseUrl(siteConfig);
            ch.Copyright      = siteConfig.Copyright;
            ch.ManagingEditor = siteConfig.Contact;
            ch.WebMaster      = siteConfig.Contact;
            documentRoot.Channels.Add(ch);


            int i = 0;

            foreach (Comment c in _com)
            {
                List <XmlElement> anyElements = new List <XmlElement>();
                if (i == siteConfig.RssEntryCount)
                {
                    break;
                }
                i++;
                string  tempTitle = "";
                RssItem item      = new RssItem();

                if (c.TargetTitle != null && c.TargetTitle.Length > 0)
                {
                    tempTitle = " on \"" + c.TargetTitle + "\"";
                }

                if (c.Author == null || c.Author == "")
                {
                    item.Title = "Comment" + tempTitle;
                }
                else
                {
                    item.Title = "Comment by " + c.Author + tempTitle;
                }

                //Per the RSS Comments Spec it makes more sense for guid and link to be the same.
                // http://blogs.law.harvard.edu/tech/rss#comments
                // 11/11/05 - SDH - Now, I'm thinking not so much...
                item.Guid             = new Rss20.Guid();
                item.Guid.Text        = c.EntryId;
                item.Guid.IsPermaLink = false;
                item.Link             = SiteUtilities.GetCommentViewUrl(siteConfig, c.TargetEntryId, c.EntryId);

                item.PubDate = c.CreatedUtc.ToString("R");

                item.Description = c.Content.Replace(Environment.NewLine, "<br />");
                if (c.AuthorHomepage == null || c.AuthorHomepage == "")
                {
                    if (c.AuthorEmail == null || c.AuthorEmail == "")
                    {
                        if (!(c.Author == null || c.Author == ""))
                        {
                            item.Description = c.Content.Replace(Environment.NewLine, "<br />") + "<br /><br />" + "Posted by: " + c.Author;
                        }
                    }
                    else
                    {
                        string content = c.Content.Replace(Environment.NewLine, "<br />");
                        if (!siteConfig.SupressEmailAddressDisplay)
                        {
                            item.Description = content + "<br /><br />" + "Posted by: " + "<a href=\"mailto:" + SiteUtilities.SpamBlocker(c.AuthorEmail) + "\">" + c.Author + "</a>";
                        }
                        else
                        {
                            item.Description = content + "<br /><br />" + "Posted by: " + c.Author;
                        }
                    }
                }
                else
                {
                    if (c.AuthorHomepage.IndexOf("http://") < 0)
                    {
                        c.AuthorHomepage = "http://" + c.AuthorHomepage;
                    }
                    item.Description += "<br /><br />" + "Posted by: " + "<a href=\"" + c.AuthorHomepage +
                                        "\">" + c.Author + "</a>";
                }

                if (c.Author != null && c.Author.Length > 0)
                {
                    // the rss spec requires an email address in the author tag
                    // and it can not be obfuscated
                    // according to the feedvalidator
                    string email;

                    if (!siteConfig.SupressEmailAddressDisplay)
                    {
                        email = (c.AuthorEmail != null && c.AuthorEmail.Length > 0 ? c.AuthorEmail : "*****@*****.**");
                    }
                    else
                    {
                        email = "*****@*****.**";
                    }

                    item.Author = String.Format("{0} ({1})", email, c.Author);
                }

                item.Comments = SiteUtilities.GetCommentViewUrl(siteConfig, c.TargetEntryId, c.EntryId);

                if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                {
                    ch.LastBuildDate = item.PubDate;
                }

                XmlDocument doc2 = new XmlDocument();
                try
                {
                    doc2.LoadXml(c.Content);
                    anyElements.Add((XmlElement)doc2.SelectSingleNode("//*[local-name() = 'body'][namespace-uri()='http://www.w3.org/1999/xhtml']"));
                }
                catch
                {
                    // absorb
                }
                item.anyElements = anyElements.ToArray();
                ch.Items.Add(item);
            }

            return(documentRoot);
        }
Exemplo n.º 8
0
        private RssRoot GetRssCore(string category, int maxDayCount, int maxEntryCount)
        {
            if (RedirectToFeedBurnerIfNeeded(category) == true)
            {
                return(null);
            }
            EntryCollection entries = null;

            //We only build the entries if blogcore doesn't exist and we'll need them later...
            if (dataService.GetLastEntryUpdate() == DateTime.MinValue)
            {
                entries = BuildEntries(category, maxDayCount, maxEntryCount);
            }

            //Try to get out as soon as possible with as little CPU as possible
            if (inASMX)
            {
                DateTime lastModified = SiteUtilities.GetLatestModifedEntryDateTime(dataService, entries);
                if (SiteUtilities.GetStatusNotModified(lastModified))
                {
                    return(null);
                }
            }

            if (inASMX)
            {
                string referrer = Context.Request.UrlReferrer != null?Context.Request.UrlReferrer.AbsoluteUri:"";
                if (ReferralBlackList.IsBlockedReferrer(referrer))
                {
                    if (siteConfig.EnableReferralUrlBlackList404s)
                    {
                        return(null);
                    }
                }
                else
                {
                    loggingService.AddReferral(
                        new LogDataItem(
                            Context.Request.RawUrl,
                            referrer,
                            Context.Request.UserAgent,
                            Context.Request.UserHostName));
                }
            }

            //not-modified didn't work, do we have this in cache?
            string  CacheKey     = "Rss:" + category + ":" + maxDayCount.ToString() + ":" + maxEntryCount.ToString();
            RssRoot documentRoot = cache[CacheKey] as RssRoot;

            if (documentRoot == null)             //we'll have to build it...
            {
                //However, if we made it this far, the not-modified check didn't work, and we may not have entries...
                if (entries == null)
                {
                    entries = BuildEntries(category, maxDayCount, maxEntryCount);
                }

                documentRoot = new RssRoot();
                documentRoot.Namespaces.Add("dc", "http://purl.org/dc/elements/1.1/");
                documentRoot.Namespaces.Add("trackback", "http://madskills.com/public/xml/rss/module/trackback/");
                documentRoot.Namespaces.Add("pingback", "http://madskills.com/public/xml/rss/module/pingback/");
                if (siteConfig.EnableComments)
                {
                    documentRoot.Namespaces.Add("wfw", "http://wellformedweb.org/CommentAPI/");
                    documentRoot.Namespaces.Add("slash", "http://purl.org/rss/1.0/modules/slash/");
                }
                if (siteConfig.EnableGeoRss)
                {
                    documentRoot.Namespaces.Add("georss", "http://www.georss.org/georss");
                }

                RssChannel ch = new RssChannel();

                if (category == null)
                {
                    ch.Title = siteConfig.Title;
                }
                else
                {
                    ch.Title = siteConfig.Title + " - " + category;
                }

                if (siteConfig.Description == null || siteConfig.Description.Trim().Length == 0)
                {
                    ch.Description = siteConfig.Subtitle;
                }
                else
                {
                    ch.Description = siteConfig.Description;
                }

                ch.Link      = SiteUtilities.GetBaseUrl(siteConfig);
                ch.Copyright = siteConfig.Copyright;
                if (siteConfig.RssLanguage != null && siteConfig.RssLanguage.Length > 0)
                {
                    ch.Language = siteConfig.RssLanguage;
                }
                ch.ManagingEditor = siteConfig.Contact;
                ch.WebMaster      = siteConfig.Contact;
                ch.Image          = null;
                if (siteConfig.ChannelImageUrl != null && siteConfig.ChannelImageUrl.Trim().Length > 0)
                {
                    ChannelImage channelImage = new ChannelImage();
                    channelImage.Title = ch.Title;
                    channelImage.Link  = ch.Link;
                    if (siteConfig.ChannelImageUrl.StartsWith("http"))
                    {
                        channelImage.Url = siteConfig.ChannelImageUrl;
                    }
                    else
                    {
                        channelImage.Url = SiteUtilities.RelativeToRoot(siteConfig, siteConfig.ChannelImageUrl);
                    }
                    ch.Image = channelImage;
                }

                documentRoot.Channels.Add(ch);

                foreach (Entry entry in entries)
                {
                    if (entry.IsPublic == false || entry.Syndicated == false)
                    {
                        continue;
                    }
                    XmlDocument       doc2        = new XmlDocument();
                    List <XmlElement> anyElements = new List <XmlElement>();
                    RssItem           item        = new RssItem();
                    item.Title            = entry.Title;
                    item.Guid             = new Rss20.Guid();
                    item.Guid.IsPermaLink = false;
                    item.Guid.Text        = SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId);
                    item.Link             = SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)entry);
                    User user = SiteSecurity.GetUser(entry.Author);
                    //Scott Hanselman: According to the RSS 2.0 spec and FeedValidator.org,
                    // we can have EITHER an Author tag OR the preferred dc:creator tag, but NOT BOTH.
                    //					if (user != null && user.EmailAddress != null && user.EmailAddress.Length > 0)
                    //					{
                    //						if (user.DisplayName != null && user.DisplayName.Length > 0)
                    //						{
                    //							item.Author = String.Format("{0} ({1})", user.EmailAddress, user.DisplayName);
                    //						}
                    //						else
                    //						{
                    //							item.Author = user.EmailAddress;
                    //						}
                    //					}
                    XmlElement trackbackPing = doc2.CreateElement("trackback", "ping", "http://madskills.com/public/xml/rss/module/trackback/");
                    trackbackPing.InnerText = SiteUtilities.GetTrackbackUrl(siteConfig, entry.EntryId);
                    anyElements.Add(trackbackPing);

                    XmlElement pingbackServer = doc2.CreateElement("pingback", "server", "http://madskills.com/public/xml/rss/module/pingback/");
                    pingbackServer.InnerText = new Uri(new Uri(SiteUtilities.GetBaseUrl(siteConfig)), "pingback.aspx").ToString();
                    anyElements.Add(pingbackServer);

                    XmlElement pingbackTarget = doc2.CreateElement("pingback", "target", "http://madskills.com/public/xml/rss/module/pingback/");
                    pingbackTarget.InnerText = SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId);
                    anyElements.Add(pingbackTarget);

                    XmlElement dcCreator = doc2.CreateElement("dc", "creator", "http://purl.org/dc/elements/1.1/");
                    if (user != null)
                    {
                        // HACK AG No author e-mail address in feed items.
                        //						if (user.DisplayName != null && user.DisplayName.Length > 0)
                        //						{
                        //							if(user.EmailAddress != null && user.EmailAddress.Length > 0)
                        //							{
                        //								dcCreator.InnerText = String.Format("{0} ({1})", user.EmailAddress, user.DisplayName);
                        //							}
                        //							else
                        //							{
                        dcCreator.InnerText = user.DisplayName;
                        //							}
                        //						}
                        //						else
                        //						{
                        //							dcCreator.InnerText = user.EmailAddress;
                        //						}
                    }
                    anyElements.Add(dcCreator);

                    // Add GeoRSS if it exists.
                    if (siteConfig.EnableGeoRss)
                    {
                        Nullable <double> latitude  = new Nullable <double>();
                        Nullable <double> longitude = new Nullable <double>();

                        if (entry.Latitude.HasValue)
                        {
                            latitude = entry.Latitude;
                        }
                        else
                        {
                            if (siteConfig.EnableDefaultLatLongForNonGeoCodedPosts)
                            {
                                latitude = siteConfig.DefaultLatitude;
                            }
                        }

                        if (entry.Longitude.HasValue)
                        {
                            longitude = entry.Longitude;
                        }
                        else
                        {
                            if (siteConfig.EnableDefaultLatLongForNonGeoCodedPosts)
                            {
                                longitude = siteConfig.DefaultLongitude;
                            }
                        }

                        if (latitude.HasValue && longitude.HasValue)
                        {
                            XmlElement geoLoc = doc2.CreateElement("georss", "point", "http://www.georss.org/georss");
                            geoLoc.InnerText = String.Format(CultureInfo.InvariantCulture, "{0:R} {1:R}", latitude, longitude);
                            anyElements.Add(geoLoc);
                        }
                    }

                    if (siteConfig.EnableComments)
                    {
                        if (entry.AllowComments)
                        {
                            XmlElement commentApi = doc2.CreateElement("wfw", "comment", "http://wellformedweb.org/CommentAPI/");
                            commentApi.InnerText = SiteUtilities.GetCommentViewUrl(siteConfig, entry.EntryId);
                            anyElements.Add(commentApi);
                        }

                        XmlElement commentRss = doc2.CreateElement("wfw", "commentRss", "http://wellformedweb.org/CommentAPI/");
                        commentRss.InnerText = SiteUtilities.GetEntryCommentsRssUrl(siteConfig, entry.EntryId);
                        anyElements.Add(commentRss);

                        //for RSS conformance per FeedValidator.org
                        int commentsCount = dataService.GetPublicCommentsFor(entry.EntryId).Count;
                        if (commentsCount > 0)
                        {
                            XmlElement slashComments = doc2.CreateElement("slash", "comments", "http://purl.org/rss/1.0/modules/slash/");
                            slashComments.InnerText = commentsCount.ToString();
                            anyElements.Add(slashComments);
                        }
                        item.Comments = SiteUtilities.GetCommentViewUrl(siteConfig, entry.EntryId);
                    }
                    item.Language = entry.Language;

                    if (entry.Categories != null && entry.Categories.Length > 0)
                    {
                        if (item.Categories == null)
                        {
                            item.Categories = new RssCategoryCollection();
                        }

                        string[] cats = entry.Categories.Split(';');
                        foreach (string c in cats)
                        {
                            RssCategory cat      = new RssCategory();
                            string      cleanCat = c.Replace('|', '/');
                            cat.Text = cleanCat;
                            item.Categories.Add(cat);
                        }
                    }
                    if (entry.Attachments.Count > 0)
                    {
                        // RSS currently supports only a single enclsoure so we return the first one
                        item.Enclosure        = new Enclosure();
                        item.Enclosure.Url    = SiteUtilities.GetEnclosureLinkUrl(entry.EntryId, entry.Attachments[0]);
                        item.Enclosure.Type   = entry.Attachments[0].Type;
                        item.Enclosure.Length = entry.Attachments[0].Length.ToString();
                    }
                    item.PubDate = entry.CreatedUtc.ToString("R");
                    if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                    {
                        ch.LastBuildDate = item.PubDate;
                    }


                    if (!siteConfig.AlwaysIncludeContentInRSS &&
                        entry.Description != null &&
                        entry.Description.Trim().Length > 0)
                    {
                        item.Description = PreprocessItemContent(entry.EntryId, entry.Description);
                    }
                    else
                    {
                        if (siteConfig.HtmlTidyContent == false)
                        {
                            item.Description = "<div>" + PreprocessItemContent(entry.EntryId, entry.Content) + "</div>";
                        }
                        else
                        {
                            item.Description = ContentFormatter.FormatContentAsHTML(PreprocessItemContent(entry.EntryId, entry.Content));


                            try
                            {
                                string xhtml = ContentFormatter.FormatContentAsXHTML(PreprocessItemContent(entry.EntryId, entry.Content));
                                doc2.LoadXml(xhtml);
                                anyElements.Add((XmlElement)doc2.SelectSingleNode("//*[local-name() = 'body'][namespace-uri()='http://www.w3.org/1999/xhtml']"));
                            }
                            catch //(Exception ex)
                            {
                                //Debug.Write(ex.ToString());
                                // absorb
                            }
                        }
                    }

                    item.anyElements = anyElements.ToArray();
                    ch.Items.Add(item);
                }
                cache.Insert(CacheKey, documentRoot, DateTime.Now.AddMinutes(5));
            }
            return(documentRoot);
        }