Пример #1
0
        public static void EditChannel(RssChannel channel)
        {
            GetRssFeed(Path);

            // If _channel is still zero, rss feed does not jet exist
            if (_channel == null)
            {
                _channel = new RssChannel();
                _channel.Items = new List<RssItem>();
                _channel.PubDate = channel.PubDate;
            }

            _channel.Title = channel.Title;
            _channel.Description = channel.Description;
            _channel.Link = channel.Link;
            _channel.LastBuild = channel.LastBuild;
            _channel.Ttl = channel.Ttl;

            WriteRss(Path);
        }
Пример #2
0
 public void AddRssChannel(RssChannel channel)
 {
     _rss = addRssChannel(_rss, channel);
 }
Пример #3
0
 /// <summary>Gets if the specified RSS Channel is in the collection.</summary>
 /// <param name="channels">Target collection.</param>
 /// <param name="channel">Target channel.</param>
 /// <returns>true if found, false otherwise.</returns>
 public static bool Contains(RssChannelCollection channels, RssChannel channel)
 {
     return(IndexOf(channels, channel) >= 0);
 }
Пример #4
0
        /// <summary>
        /// RSSを生成・取得する。
        /// </summary>
        /// <param name="log">イベントログオブジェクト</param>
        /// <returns>RSS Feed</returns>
        internal static RssFeed GetFeed(EventLog log, Uri url, string type)
        {
            // エントリ取得最大数を決定
            string maxLogEntryCountStr = ConfigurationManager.AppSettings["MaxLogEntryCount"];
            int    maxLogEntryCount    = 100;
            int    count = maxLogEntryCount;

            if (!string.IsNullOrEmpty(maxLogEntryCountStr) &&
                int.TryParse(maxLogEntryCountStr, out count))
            {
                maxLogEntryCount = count;
            }

            //イベントログ用の新規フィード作成
            RssChannel channel = new RssChannel();

            channel.Title       = "EventLog(" + log.Log + ")";
            channel.Description = log.LogDisplayName;
            channel.Link        = url;

            //対象エントリを新しいものから全て抽出
            //List<RssItem> itemList = new List<RssItem>();
            count = 0;
            for (int i = log.Entries.Count - 1; i >= 0; i--)
            {
                EventLogEntry entry = log.Entries[i];

                if (!EventLogUtil.IsVisible(entry, type))
                {
                    continue;
                }

                RssItem item = new RssItem();
                item.Title = "[" + entry.EntryType.ToString()
                             + "] " + entry.Source;
                item.PubDate = entry.TimeGenerated.ToUniversalTime();
                if (!string.IsNullOrEmpty(entry.UserName))
                {
                    item.Author = entry.UserName;
                }
                item.Description = entry.Message;

                string query = entry.Source + " " + entry.Message;
                query = query.Replace('\n', ' ');
                if (query.Length > 127)
                {
                    query = query.Substring(0, 127);
                }
                //query = Uri.EscapeUriString(query); //SecurityCenter%20Windows%20%E3%82%BB%E3%82%AD%E3%83%A5%E3%83%AA%E3%83%86%E3%82%A3%20%E3%82%BB%E3%83%B3%E3%82%BF%E3%83%BC%20%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%82%92%E9%96%8B%E5%A7%8B%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F%E3%80%82
                query = HttpUtility.UrlEncode(query); //SecurityCenter+Windows+%e3%82%bb%e3%82%ad%e3%83%a5%e3%83%aa%e3%83%86%e3%82%a3+%e3%82%bb%e3%83%b3%e3%82%bf%e3%83%bc+%e3%82%b5%e3%83%bc%e3%83%93%e3%82%b9%e3%82%92%e9%96%8b%e5%a7%8b%e3%81%97%e3%81%be%e3%81%97%e3%81%9f%e3%80%82
                Debug.WriteLine("query : " + query);
                item.Link = new Uri("http://www.google.co.jp/search?q=" + query);

                RssGuid guid = new RssGuid();
                guid.PermaLink = false;
                //とりあえず、発行時刻をglobally unique identifierに設定してみる
                guid.Name = entry.TimeGenerated.ToUniversalTime().ToString("yyyyMMdd_HHmmss.fff");
                item.Guid = guid;

                RssCategory EntryType = new RssCategory();
                EntryType.Domain = "EntryType";
                EntryType.Name   = entry.EntryType.ToString();
                item.Categories.Add(EntryType);

                RssCategory Source = new RssCategory();
                Source.Domain = "Source";
                Source.Name   = entry.Source;
                item.Categories.Add(Source);

                RssCategory Category = new RssCategory();
                Category.Domain = "Category";
                Category.Name   = entry.Category;
                item.Categories.Add(Category);

                RssCategory InstanceId = new RssCategory();
                InstanceId.Domain = "InstanceId";
                InstanceId.Name   = entry.InstanceId.ToString();
                item.Categories.Add(InstanceId);

                channel.Items.Add(item);
                //itemList.Add(item);

                //指定最大数に達したら、抽出処理完了
                if (++count >= maxLogEntryCount)
                {
                    break;
                }
            }

            /*
             * //RSSオブジェクトに逆順で追加
             * channel.Items.Capacity = itemList.Count;
             * for (int i = itemList.Count - 1; i >= 0; i--)
             * {
             *  channel.Items.Add(itemList[i]);
             * }
             */

            AddEmptyItemToEmptyChannel(channel);
            RssFeed feed = new RssFeed(Encoding.UTF8);

            feed.Channels.Add(channel);
            return(feed);
        }
Пример #5
0
 /// <summary>
 /// Create a new collection for the specified channel
 /// </summary>
 /// <param name="parent">Channel for which this collection holds the data.</param>
 public RssItemCollection(RssChannel parent)
 {
     _parent = parent;
 }
 /// <summary>
 /// Public constructor.
 /// </summary>
 /// <param name="rssChannel"></param>
 public Rss(RssChannel rssChannel)
 {
     this.Channel = rssChannel;
 }
Пример #7
0
        private void RenderRss()
        {
            DataView dv = FeedCache.GetRssFeedEntries(
                module.ModuleId,
                module.ModuleGuid,
                entryCacheTimeout,
                maxDaysOld,
                maxEntriesPerFeed,
                EnableSelectivePublishing
                ).DefaultView;

            dv.Sort = "PubDate DESC";

            if (dv.Table.Rows.Count == 0)
            {
                return;
            }

            Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed();

            RssChannel channel = new RssChannel
            {
                Generator = "mojoPortal Feed Manager module"
            };

            feed.Channel = channel;

            if (module != null)
            {
                channel.Title       = module.ModuleTitle;
                channel.Description = module.ModuleTitle;

                try
                {
                    channel.Link = new Uri(WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl()));
                }
                catch (UriFormatException)
                {
                    channel.Link = new Uri(SiteUtils.GetNavigationSiteRoot());
                }
            }
            else
            {
                // this prevents an error: Can't close RssWriter without first writing a channel.
                channel.Title         = "Not Found";
                channel.Description   = "Not Found";
                channel.LastBuildDate = DateTime.UtcNow;
            }

            foreach (DataRowView row in dv)
            {
                bool confirmed = Convert.ToBoolean(row["Confirmed"]);

                if (!EnableSelectivePublishing)
                {
                    confirmed = true;
                }

                if (confirmed)
                {
                    RssItem item = new RssItem
                    {
                        Title           = row["Title"].ToString(),
                        Description     = row["Description"].ToString(),
                        PublicationDate = Convert.ToDateTime(row["PubDate"]),
                        Link            = new System.Uri(row["Link"].ToString())
                    };

                    Trace.Write(item.Link.ToString());
                    item.Author = row["Author"].ToString();
                    channel.AddItem(item);
                }
            }

            Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();

            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");
                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");
                }
                ///////////////////////////

                feed.Save(xmlTextWriter);
            }
        }
Пример #8
0
        private void writeChannel(RssChannel.RssChannel channel)
        {
            if (this.writer == null)
                throw new InvalidOperationException("RssWriter has been closed, and can not be written to.");
            if (channel == null)
                throw new ArgumentNullException("Channel must be instanciated with data to be written.");

            if (this.wroteChannel)
                this.writer.WriteEndElement();
            else
                this.wroteChannel = true;

            this.BeginDocument();

            this.writer.WriteStartElement("channel");
            WriteElement("title", channel.Title, true);
            WriteElement("description", channel.Description, true);
            WriteElement("link", channel.Link, true);
            if (channel.Image != null)
            {
                this.writer.WriteStartElement("image");
                WriteElement("title", channel.Image.Title, true);
                WriteElement("url", channel.Image.Url, true);
                WriteElement("link", channel.Image.Link, true);
                switch (this.rssVersion)
                {
                    case RssVersion.RSS091:
                    case RssVersion.RSS092:
                    case RssVersion.RSS20:
                        WriteElement("description", channel.Image.Description, false);
                        WriteElement("width", channel.Image.Width, false);
                        WriteElement("height", channel.Image.Height, false);
                        break;
                }
                this.writer.WriteEndElement();
            }
            switch (this.rssVersion)
            {
                case RssVersion.RSS091:
                case RssVersion.RSS092:
                case RssVersion.RSS20:
                    WriteElement("language", channel.Language, this.rssVersion == RssVersion.RSS091);
                    WriteElement("copyright", channel.Copyright, false);
                    WriteElement("managingEditor", channel.ManagingEditor, false);
                    WriteElement("webMaster", channel.WebMaster, false);
                    WriteElement("pubDate", channel.PubDate, false);
                    WriteElement("lastBuildDate", channel.LastBuildDate, false);
                    if (channel.Docs != RssDefault.String)
                        WriteElement("docs", channel.Docs, false);
                    else
                        switch (this.rssVersion)
                        {
                            case RssVersion.RSS091:
                                this.WriteElement("docs", "http://my.netscape.com/publish/formats/rss-spec-0.91.html",
                                                  false);
                                break;
                            case RssVersion.RSS092:
                                this.WriteElement("docs", "http://backend.userland.com/rss092", false);
                                break;
                            case RssVersion.RSS20:
                                this.WriteElement("docs", "http://backend.userland.com/rss", false);
                                break;
                        }
                    WriteElement("rating", channel.Rating, false);
                    string[] Days = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};
                    for (int i = 0; i <= 6; i++)
                        if (channel.SkipDays[i])
                        {
                            this.writer.WriteStartElement("skipDays");
                            for (int i2 = 0; i2 <= 6; i2++)
                                if (channel.SkipDays[i2])
                                    WriteElement("day", Days[i2], false);
                            this.writer.WriteEndElement();
                            break;
                        }
                    for (int i = 0; i <= 23; i++)
                        if (channel.SkipHours[i])
                        {
                            this.writer.WriteStartElement("skipHours");
                            for (int i2 = 0; i2 <= 23; i2++)
                                if (channel.SkipHours[i2])
                                    this.WriteElement("hour", i2 + 1, false);
                            this.writer.WriteEndElement();
                            break;
                        }
                    break;
            }
            switch (this.rssVersion)
            {
                case RssVersion.RSS092:
                case RssVersion.RSS20:
                    if (channel.Categories != null)
                        foreach (RssCategory category in channel.Categories)
                            if (category.Name != RssDefault.String)
                            {
                                this.writer.WriteStartElement("category");
                                WriteAttribute("domain", category.Domain, false);
                                this.writer.WriteString(category.Name);
                                this.writer.WriteEndElement();
                            }
                    if (channel.Cloud != null)
                    {
                        this.writer.WriteStartElement("cloud");
                        WriteElement("domain", channel.Cloud.Domain, false);
                        WriteElement("port", channel.Cloud.Port, false);
                        WriteElement("path", channel.Cloud.Path, false);
                        WriteElement("registerProcedure", channel.Cloud.RegisterProcedure, false);
                        if (channel.Cloud.Protocol != RssCloudProtocol.Empty)
                            WriteElement("Protocol", channel.Cloud.Protocol, false);
                        this.writer.WriteEndElement();
                    }
                    break;
            }
            if (this.rssVersion == RssVersion.RSS20)
            {
                if (channel.Generator != RssDefault.String)
                    WriteElement("generator", channel.Generator, false);
                else
                    this.WriteElement("generator", "RSS.NET: http://www.rssdotnet.com/", false);
                WriteElement("ttl", channel.TimeToLive, false);

                // RSS Modules
                foreach (RssModule rssModule in this._rssModules)
                {
                    if (rssModule.IsBoundTo(channel.GetHashCode()))
                    {
                        foreach (RssModuleItem rssModuleItem in rssModule.ChannelExtensions)
                        {
                            if (rssModuleItem.SubElements.Count == 0)
                                WriteElement(rssModule.NamespacePrefix + ":" + rssModuleItem.Name, rssModuleItem.Text,
                                             rssModuleItem.IsRequired);
                            else
                                this.writeSubElements(rssModuleItem.SubElements, rssModule.NamespacePrefix);
                        }
                    }
                }
            }
            if (channel.TextInput != null)
            {
                this.writer.WriteStartElement("textinput");
                WriteElement("title", channel.TextInput.Title, true);
                WriteElement("description", channel.TextInput.Description, true);
                WriteElement("name", channel.TextInput.Name, true);
                WriteElement("link", channel.TextInput.Link, true);
                this.writer.WriteEndElement();
            }
            foreach (RssItem.RssItem item in channel.Items)
            {
                this.writeItem(item, channel.GetHashCode());
            }
            this.writer.Flush();
        }
Пример #9
0
        private void RenderRss()
        {
            if (pageSettings == null)
            {
                return;
            }

            RssForum rssForum = new RssForum();

            rssForum.SiteId      = siteSettings.SiteId;
            rssForum.ModuleId    = moduleId;
            rssForum.PageId      = pageId;
            rssForum.ItemId      = itemId;
            rssForum.ThreadId    = threadId;
            rssForum.MaximumDays = maxDaysOld;

            Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed();
            RssChannel channel = new RssChannel();

            channel.Generator = "mojoPortal Forum module";

            string channelLink = WebUtils.ResolveServerUrl(SiteUtils.GetPageUrl(pageSettings));

            channel.Link = new System.Uri(channelLink);

            // if (config.ChannelDescription.Length > 0) { channel.Description = config.ChannelDescription; }

            feed.Channel = channel;

            string target = navigationSiteRoot + "/Forums/Thread.aspx?pageid=";

            using (IDataReader posts = rssForum.GetPostsForRss())
            {
                while ((posts.Read()) && (entryCount <= entriesLimit))
                {
                    string pageViewRoles   = posts["AuthorizedRoles"].ToString();
                    string moduleViewRoles = posts["ViewRoles"].ToString();
                    bool   include         = (bypassPageSecurity ||
                                              (pageViewRoles.Contains("All Users")) &&
                                              ((moduleViewRoles.Length == 0) || (moduleViewRoles.Contains("All Users")))
                                              )
                    ;

                    if (!include)
                    {
                        continue;
                    }

                    RssItem item = new RssItem();

                    item.Title           = posts["Subject"].ToString();
                    item.Description     = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, posts["Post"].ToString());
                    item.PublicationDate = Convert.ToDateTime(posts["PostDate"]);

                    int p = Convert.ToInt32(posts["PageID"]);
                    int t = Convert.ToInt32(posts["ThreadID"]);

                    //if (target.IndexOf("&thread=") < 0 && target.IndexOf("?thread=") < 0)
                    //{
                    //    if (target.IndexOf("?") < 0)
                    //    {
                    //        target += "?thread=" + posts["ThreadID"].ToString() + "#post" + posts["PostID"].ToString();
                    //    }
                    //    else
                    //    {
                    //        target += "&thread=" + posts["ThreadID"].ToString() + "#post" + posts["PostID"].ToString();
                    //    }
                    //}

                    //https://www.mojoportal.com/Forums/Thread.aspx?pageid=5&t=11417~1#post47516
                    if ((isGoogleFeedReader) && (ForumConfiguration.UseOldParamsForGoogleReader))
                    {
                        //item.Link = new System.Uri(target + p.ToInvariantString() + "&thread=" + t.ToInvariantString() + "#post" + posts["PostID"].ToString());
                        item.Link = new System.Uri(target + p.ToInvariantString() + "&thread=" + t.ToInvariantString());
                    }
                    else
                    {
                        item.Link = new System.Uri(target + p.ToInvariantString() + "&t=" + t.ToInvariantString() + "~-1#post" + posts["PostID"].ToString());
                    }

                    RssGuid g = new RssGuid(target, true);
                    item.Guid = g;

                    item.Author = posts["StartedBy"].ToString();

                    channel.AddItem(item);
                    entryCount += 1;
                }
            }

            Response.Cache.SetExpires(DateTime.Now.AddMinutes(5));
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();

            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");
                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");
                }
                ///////////////////////////


                feed.Save(xmlTextWriter);
            }
        }
Пример #10
0
        //one call is fuctionality for update duration that has many feeds
        private Feed UpdatingFeed(long feedId)
        {
            int  NumberOfNewItem = 0;
            var  entiti          = new TazehaContext();
            Feed dbfeed          = entiti.Feeds.Single <Feed>(x => x.Id == feedId);

            dbfeed.UpdatingCount    = dbfeed.UpdatingCount == null ? 1 : dbfeed.UpdatingCount + 1;
            dbfeed.LastUpdaterVisit = DateTime.Now;
            try
            {
                if (dbfeed.FeedType == 0 || !dbfeed.FeedType.HasValue)
                {
                    #region Feed
                    RssFeed feed = RssFeed.Read(dbfeed.Link);
                    //-----------shart check kardane inke feed aslan update shode dar site marja ya kheir------------
                    if (feed == null)
                    {
                        dbfeed.Deleted = Common.Share.DeleteStatus.NotWork;
                    }
                    else if (feed.Channels.Count > 0)
                    {
                        bool Exist = false;

                        if (Exist)
                        {
                            GeneralLogs.WriteLog("NoUpdated(last item exist) feed: " + feedId, TypeOfLog.Info);
                        }
                        else
                        {
                            //--------Feed has new items-----------
                            if (feed.Channels.Count > 0)
                            {
                                RssChannel        channel = (RssChannel)feed.Channels[0];
                                List <FeedItemSP> listReturnBack;
                                if (channel.Items.LatestPubDate() != channel.Items[0].PubDate)
                                {
                                    listReturnBack = FeedItemsOperation.InsertFeedItems(channel.ItemsSorted, dbfeed);
                                }
                                else
                                {
                                    listReturnBack = FeedItemsOperation.InsertFeedItems(channel.Items, dbfeed);
                                }

                                GeneralLogs.WriteLog("Updating feed " + dbfeed.Id + " Num:" + listReturnBack.Count + " " + dbfeed.Link, TypeOfLog.OK);
                            }
                        }
                    }
                    #endregion
                }
                else if (dbfeed.FeedType.HasValue && dbfeed.FeedType.Value == Common.Share.FeedType.Atom)
                {
                    #region Atom
                    //-----------------atom feed--------------
                    XmlReader       reader   = XmlReader.Create(dbfeed.Link);
                    SyndicationFeed atomfeed = SyndicationFeed.Load(reader);
                    int             i        = 0;
                    if (atomfeed == null)
                    {
                        dbfeed.Deleted = Common.Share.DeleteStatus.NotWork;
                    }
                    else if (atomfeed.Items.Any())
                    {
                        foreach (SyndicationItem item in atomfeed.Items)
                        {
                            i++;
                            break;
                        }
                        if (i > 0)
                        {
                            List <FeedItem> listReturnBack = FeedItemsOperation.InsertFeedItems(atomfeed.Items, dbfeed);

                            GeneralLogs.WriteLog("OK updating atom " + dbfeed.Id + " Num:" + listReturnBack.Count + " " + dbfeed.Link);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                #region Exception
                if (ex.Message.IndexOf("404") > 0)
                {
                    dbfeed.Deleted = Common.Share.DeleteStatus.NotFound;
                }
                else if (ex.Message.IndexOf("403") > 0)
                {
                    dbfeed.Deleted = Common.Share.DeleteStatus.Forbidden;
                }
                else if (ex.Message.IndexOfX("timed out") > 0)
                {
                    //------request time out
                    dbfeed.Deleted = Common.Share.DeleteStatus.RequestTimeOut;
                }
                //-----------log error-----
                if (ex.Message.IndexOfX("Inner Exception") > 0)
                {
                    CrawlerLog.FailLog(dbfeed, ex.InnerException.Message.SubstringX(0, 1020));
                }
                else
                {
                    GeneralLogs.WriteLog("Info " + ex.Message);
                }
                #endregion
            }
            #region LASTFLOW
            try
            {
                CheckForChangeDuration(dbfeed, NumberOfNewItem > 0 ? true : false);
                CrawlerLog.SuccessLog(dbfeed, NumberOfNewItem);
                entiti.SaveChanges();
            }
            catch (Exception ex)
            {
                GeneralLogs.WriteLog(ex.Message);
            }
            #endregion

            return(dbfeed);
        }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            con = ConnectionDB.getConnection();
            var feed_language = Languages.userLanguage(Request);
            // get user ID
            string userId = null;
            if (Request.QueryString["userId"] != null)
            {
                userId = Request["userId"];
            }
            else
            {
                throw new HttpException(401, "We need your user ID!");
            }

            // get team list
            string[] teamList = null;
            if (Request.QueryString["teamList"] != null)
            {
                teamList = Request["teamList"].Split(',');
            }
            else
            {
                throw new HttpException(400, "We need your teams subscribe list!");
            }

            teamsNames = new Hashtable();

            // get teams name and verify if exists
            foreach (string team in teamList)
            {
                if (team.Length != 0)
                {
                    String CmdString1 = "SELECT * FROM football.udf_get_teamNames(@teamId)";
                    SqlCommand cmd1 = new SqlCommand(CmdString1, con);
                    cmd1.Parameters.AddWithValue("@teamId", Convert.ToInt32(team));
                    SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
                    DataTable dt1 = new DataTable("team");
                    sda1.Fill(dt1);

                    if (dt1.Rows.Count == 0)
                    {
                        throw new HttpException(404, "Team doesn't exists!");
                    }

                    var columnName = "name" + feed_language.ToUpper();
                    var index = dt1.Columns.IndexOf(columnName);

                    teamsNames[Convert.ToInt32(team)] = dt1.Rows[0].ItemArray[index].ToString();
                }
            }

            // verify if the user subscribe the team list

            foreach(string team in teamList)
            {
                if (team.Length != 0)
                {
                    string cmd_str = "SELECT football.udf_user_subscribed_team(@user_id, @team_id)";
                    SqlCommand cmd_subscribe = new SqlCommand(cmd_str, con);
                    cmd_subscribe.Parameters.AddWithValue("@user_id", userId);
                    cmd_subscribe.Parameters.AddWithValue("@team_id", Convert.ToInt32(team));
                    cmd_subscribe.CommandType = CommandType.Text;

                    int subscribing = 0;

                    try
                    {
                        con.Open();
                        subscribing = (int)cmd_subscribe.ExecuteScalar();
                        con.Close();
                    }
                    catch (Exception exc)
                    {
                        con.Close();
                    }

                    if (subscribing == 0)
                    {
                        throw new HttpException(401, "Please subscribe!");
                    }
                }
            }

            // format, default => full
            string format = "full";
            if (Request.QueryString["format"] == "simple")
            {
                format = Request["format"];
            }

            // language
            string language = "pt";
            if (Request.QueryString["language"] != null && Languages.languages_name.ContainsKey(Request["language"]))
            {
                language = Request["language"];
            }

            // get content
            teamNews = new LinkedList<TeamNew>();

            string teamsList = "";

            foreach (String teamId in teamList)
            {
                if (teamId.Length != 0)
                {
                    teamsList += teamId + ",";
                }
            }

            if (teamsList.Length == 0)
            {
                teamsList = ",,";
            }
            else
            {
                teamsList = ',' + teamsList;
            }

            String CmdString = "SELECT * FROM football.udf_get_rss_news(@teamsList, @language) ORDER BY pubDate DESC";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            cmd.Parameters.AddWithValue("@teamsList", teamsList);
            cmd.Parameters.AddWithValue("@language", language);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("teamNews");
            sda.Fill(dt);

            int count_news = 0;

            foreach (DataRow teamNew in dt.Rows)
            {
                TeamNew tmp = new TeamNew(teamNew, Convert.ToInt32(teamNew.ItemArray[6]));

                if((++count_news) >= 30)
                {
                    teamNews.AddLast(tmp);
                    break;
                }

                // search for related news
                String CmdString1 = "SELECT * FROM football.udf_get_team_news_related(@related_id)";
                SqlCommand cmd1 = new SqlCommand(CmdString1, con);
                cmd1.Parameters.AddWithValue("@related_id", tmp.id);
                SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
                DataTable dt1 = new DataTable("relatedNews");
                sda1.Fill(dt1);

                foreach (DataRow relatedNew in dt1.Rows)
                {
                    TeamRelatedNew tmp1 = new TeamRelatedNew(relatedNew, Convert.ToInt32(teamNew.ItemArray[6]), tmp.pubDate);
                    tmp.related.AddLast(tmp1);
                    if(format == "simple" && (++count_news) >= 30){
                        break;
                    }
                }

                teamNews.AddLast(tmp);

                if (count_news >= 30)
                {
                    break;
                }
            }

            string title = "";
            foreach(string clubName in teamsNames.Values)
            {
                title += clubName + " ";
            }

            title += "RSS Feed";

            rssChannel = new RssChannel(HttpContext.Current.Request.Url.AbsoluteUri, title, language, format);
            RepeaterRSS.DataSource = teamNews;

            RepeaterRSS.DataBind();

            url = "http://" + HttpContext.Current.Request.Url.Authority + "/";
            Page.DataBind();
        }
Пример #12
0
 public Rss()
 {
     Channel = new RssChannel();
     Version = "2.0";
 }
Пример #13
0
        private void ManageChannels()
        {
            // ******** suppression d'un channel *********
            DeleteChannelCmd = new Command(new Action(() =>
            {
                if (SelectedChannel != null)
                {
                    try
                    {
                        ChannelsList.Remove(SelectedChannel);
                        _serveur.dropChannel(SelectedChannel.IdEntity);

                        IList <RssChannel> correctList = ChannelsList;

                        ChannelsList = null;
                        ChannelsList = correctList;

                        SelectedChannel = null;
                    }
                    catch (Exception e)
                    {
                        IsProgressRingActive = false;
                        if (e.InnerException != null)
                        {
                            DebugText = e.InnerException.Message;
                        }
                        else
                        {
                            DebugText = e.Message;
                        }
                    }
                }
            }));


            // ******** ajout d'un channel *********
            AddChannelCmd = new Command(new Action(async() =>
            {
                IsFlyoutAddChannelOpenned = true;
                CurrentChannel            = new RssChannel();
                NewCategoryForChannel     = CurrentCategory;
                if (ChannelsList == null)
                {
                    ChannelsList = new List <RssChannel>();
                }
            }));

            AddChannelCmdValidate = new Command(new Action(async() =>
            {
                try
                {
                    FlyoutMessage        = "";
                    IsProgressRingActive = true;
                    CurrentChannel       = await _serveur.addChannelInCategoryWithCategoryNameAsync(CurrentChannel.RssLink, NewCategoryForChannel.Name);

                    ChannelsList.Add(CurrentChannel);
                    IList <RssChannel> correctList = ChannelsList;

                    ChannelsList = null;
                    ChannelsList = correctList;

                    IsFlyoutAddChannelOpenned = false;
                    IsProgressRingActive      = false;
                }
                catch (Exception e)
                {
                    IsProgressRingActive = false;
                    if (e.InnerException != null)
                    {
                        FlyoutMessage = e.InnerException.Message;
                    }
                    else
                    {
                        FlyoutMessage = e.Message;
                    }
                }
            }));



            // ******** edition d'un channel *********
            EditChannelCmd = new Command(new Action(async() =>
            {
                if (SelectedChannel != null)
                {
                    CurrentChannel             = SelectedChannel;
                    IsFlyoutEditChannelOpenned = true;
                    NewCategoryForChannel      = CurrentCategory;
                }
            }));

            EditChannelCmdValidate = new Command(new Action(async() =>
            {
                IsFlyoutEditChannelOpenned = false;
                try
                {
                    if (NewCategoryForChannel != CurrentCategory)
                    {
                        _serveur.moveChannelToCategory(CurrentCategory.IdEntity, NewCategoryForChannel.IdEntity, CurrentChannel.IdEntity);

                        CategoryList = _serveur.getCategories();
                        ChannelsList = _serveur.getRssChannelsInCategoryWithCategoryName(CurrentCategory.Name);
                    }
                    FlyoutMessage = "";
                }
                catch (Exception e)
                {
                    if (e.InnerException != null)
                    {
                        FlyoutMessage = e.InnerException.Message;
                    }
                    else
                    {
                        FlyoutMessage = e.Message;
                    }
                }
            }));


            // ******** Set Channel lu *********
            SetReadChannelCmd = new Command(new Action(() =>
            {
                if (SelectedChannel != null)
                {
                    try
                    {
                        if (IsOn)
                        {
                            _serveur.setChannelAsRead(SelectedChannel.IdEntity);
                        }
                    }
                    catch (Exception e)
                    {
                        if (e.InnerException != null)
                        {
                            DebugText = "[Exception]" + e.InnerException.Message;
                        }
                        else
                        {
                            DebugText = "[Exception]" + e.Message;
                        }
                    }
                }
                else
                {
                    DebugText = "[Error] SelectedChannel == null";
                }
            }));

            // ******** Set Channel non lu *********
            SetUnreadChannelCmd = new Command(new Action(() =>
            {
                if (SelectedChannel != null)
                {
                    try
                    {
                        if (IsOn)
                        {
                            _serveur.setChannelAsUnread(SelectedChannel.IdEntity);
                        }
                    }
                    catch (Exception e)
                    {
                        if (e.InnerException != null)
                        {
                            DebugText = "[Exception]" + e.InnerException.Message;
                        }
                        else
                        {
                            DebugText = "[Exception]" + e.Message;
                        }
                    }
                }
                else
                {
                    DebugText = "[Error] SelectedChannel == null";
                }
            }));
        }
Пример #14
0
        public int UpdatingFeed(Feed dbfeed, bool saveItems = true)
        {
            int NumberOfNewItem = 0;
            var items           = new List <FeedItem>();
            var log             = new FeedLog()
            {
                FeedId = dbfeed.Id
            };

            try
            {
                if (dbfeed.FeedType == 0 || !dbfeed.FeedType.HasValue)
                {
                    #region Feed
                    RssFeed feed = RssFeed.Read(dbfeed.Link);
                    //-----------shart check kardane inke feed aslan update shode dar site marja ya kheir------------
                    if (feed == null)
                    {
                        dbfeed.Deleted = Common.Share.DeleteStatus.NotWork;
                    }
                    else if (feed.Channels.Count > 0)
                    {
                        //--------Feed has new items-----------
                        if (feed.Channels.Count > 0)
                        {
                            RssChannel channel = (RssChannel)feed.Channels[0];

                            if (channel.Items.LatestPubDate() != channel.Items[0].PubDate)
                            {
                                items = new FeedItemsOperation(_appConfigBiz).RssItemsToFeedItems(channel.ItemsSorted, dbfeed);
                            }
                            else
                            {
                                items = new FeedItemsOperation(_appConfigBiz).RssItemsToFeedItems(channel.Items, dbfeed);
                            }


                            //----------Visual Items---------
                            //NumberOfNewItem = listReturnBack.Count;
                            //if (NumberOfNewItem > 0)
                            //{
                            //    if (dbfeed.InIndex == 1)
                            //    {
                            //        if (dbfeed.Site.HasSocialTag.HasValue && dbfeed.Site.HasSocialTag.Value)
                            //            Updater.FeedItemImage.setFeedItemsImage(dbfeed, listReturnBack, 5);
                            //        //else
                            //        //    FeedItemsOperation.insertFeedItemsIndex(dbfeed, listReturnBack, 5);
                            //    }
                            //    entiti.SaveChanges();
                            //}
                        }
                    }
                    #endregion
                }
                else if (dbfeed.FeedType.HasValue && dbfeed.FeedType.Value == Common.Share.FeedType.Atom)
                {
                    #region Atom
                    XmlReader       reader   = XmlReader.Create(dbfeed.Link);
                    SyndicationFeed atomfeed = SyndicationFeed.Load(reader);
                    int             i        = 0;
                    if (atomfeed == null)
                    {
                        dbfeed.Deleted = Common.Share.DeleteStatus.NotWork;
                    }
                    else if (atomfeed.Items.Any())
                    {
                        foreach (SyndicationItem item in atomfeed.Items)
                        {
                            i++;
                            break;
                        }
                        if (i > 0)
                        {
                            items = new FeedItemsOperation(_appConfigBiz).AtomItemsToFeedItems(atomfeed.Items, dbfeed);
                        }
                    }
                    #endregion
                }

                if (items.Any())
                {
                    if (dbfeed.Site.HasImage != HasImage.NotSupport)
                    {
                        new FeedItemImage(_appConfigBiz).SetItemsImage(items, dbfeed);
                    }
                    if (saveItems)
                    {
                        NumberOfNewItem = ItemBiz.AddItems(items);
                        if (NumberOfNewItem > 0)
                        {
                            dbfeed.LastUpdatedItemUrl = items.Last().Link.SubstringM(0, 400);
                        }
                    }

                    GeneralLogs.WriteLog("Updating feed " + dbfeed.Id + "  Items:" + NumberOfNewItem + "  New:" + NumberOfNewItem + " " + dbfeed.Link.Replace("http://", ""), TypeOfLog.OK, typeof(FeedUpdater));
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("404") > 0)
                {
                    dbfeed.Deleted = Common.Share.DeleteStatus.NotFound;
                }
                else if (ex.Message.IndexOf("403") > 0)
                {
                    dbfeed.Deleted = Common.Share.DeleteStatus.Forbidden;
                }
                else if (ex.Message.IndexOfX("timed out") > 0)
                {
                    dbfeed.Deleted = Common.Share.DeleteStatus.RequestTimeOut;
                }
                else
                {
                    dbfeed.Deleted = Common.Share.DeleteStatus.Temporary;
                }

                log.HasError = true;
                log.Message  = "Error:" + (ex.InnerException != null ? ex.InnerException.Message.SubstringM(0, 512) : ex.Message.SubstringM(0, 512));
                FeedBiz.CreateFeedLog(log);
                var msg = "FeedId " + dbfeed.Id + " " + dbfeed.Link.SubstringM(0, 40) + " Error:" + (ex.InnerException != null ? ex.InnerException.Message.SubstringM(0, 512) : ex.Message.SubstringM(0, 512));
                GeneralLogs.WriteLog(msg, TypeOfLog.Error, typeof(FeedUpdater));

                FeedBiz.Edit(dbfeed);
                return(NumberOfNewItem);
            }

            dbfeed.LastUpdaterVisit = DateTime.Now;

            if (saveItems)
            {
                FeedBiz.CheckForChangeDuration(dbfeed, NumberOfNewItem > 0 ? true : false);
                if (NumberOfNewItem > 0)
                {
                    dbfeed.LastUpdateDateTime = DateTime.Now;
                }
            }

            var res = FeedBiz.Edit(dbfeed);
            if (saveItems && res.Status)
            {
                log.HasError   = false;
                log.Message    = "Successfull Updat Feed " + dbfeed.Title.SubstringM(0, 16) + " " + dbfeed.Link.Replace("http://", "").SubstringM(0, 24);
                log.ItemsCount = NumberOfNewItem;
                FeedBiz.CreateFeedLog(log);
            }

            return(saveItems ? NumberOfNewItem : items.Count);
        }
Пример #15
0
        private void RenderRss()
        {
            Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed();
            RssChannel channel = new RssChannel();

            channel.Generator = "mojoPortal Blog Module";

            channel.Language = SiteUtils.GetDefaultCulture();
            feed.Channel     = channel;
            if (module.ModuleTitle.Length > 0)
            {
                channel.Title = module.ModuleTitle;
            }
            else
            {
                channel.Title = "Blog"; // it will cause an error if this is left blank so we must populate it if the module title is an emty string.
            }

            // this became broken when we combined query string params, since pageid is not one of the params this always returns the home page url
            // instead of the blog page url
            //string pu = WebUtils.ResolveServerUrl(SiteUtils.GetCurrentPageUrl());

            string pu = WebUtils.ResolveServerUrl(SiteUtils.GetPageUrl(pageSettings));


            channel.Link     = new System.Uri(pu);
            channel.SelfLink = Request.Url;


            if (config.ChannelDescription.Length > 0)
            {
                channel.Description = config.ChannelDescription;
            }
            if (config.Copyright.Length > 0)
            {
                channel.Copyright = config.Copyright;
            }

            channel.ManagingEditor = config.ManagingEditorEmail;
            if (config.ManagingEditorName.Length > 0)
            {
                channel.ManagingEditor += " (" + config.ManagingEditorName + ")";
            }


            if (config.FeedTimeToLive > -1)
            {
                channel.TimeToLive = config.FeedTimeToLive;
            }


            //  Create and add iTunes information to feed channel
            ITunesSyndicationExtension channelExtension = new ITunesSyndicationExtension();

            channelExtension.Context.Subtitle = config.ChannelDescription;


            if (config.HasExplicitContent)
            {
                channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.Yes;
            }
            else
            {
                channelExtension.Context.ExplicitMaterial = ITunesExplicitMaterial.No;
            }

            channelExtension.Context.Author = config.ManagingEditorEmail;
            if (config.ManagingEditorName.Length > 0)
            {
                channelExtension.Context.Author += " (" + config.ManagingEditorName + ")";
            }
            channelExtension.Context.Summary = config.ChannelDescription;
            channelExtension.Context.Owner   = new ITunesOwner(config.ManagingEditorEmail, config.ManagingEditorName);



            if (config.FeedLogoUrl.Length > 0)
            {
                try
                {
                    channelExtension.Context.Image = new Uri(config.FeedLogoUrl);
                }
                catch (ArgumentNullException) { }
                catch (UriFormatException) { }
            }


            if (config.FeedMainCategory.Length > 0)
            {
                ITunesCategory mainCat = new ITunesCategory(config.FeedMainCategory);

                if (config.FeedSubCategory.Length > 0)
                {
                    mainCat.Categories.Add(new ITunesCategory(config.FeedSubCategory));
                }


                channelExtension.Context.Categories.Add(mainCat);
            }


            feed.Channel.AddExtension(channelExtension);


            DataSet dsBlogPosts = GetData();

            DataTable posts = dsBlogPosts.Tables["Posts"];


            foreach (DataRow dr in posts.Rows)
            {
                bool inFeed = Convert.ToBoolean(dr["IncludeInFeed"]);
                if (!inFeed)
                {
                    continue;
                }

                RssItem item = new RssItem();

                int    itemId      = Convert.ToInt32(dr["ItemID"]);
                string blogItemUrl = FormatBlogUrl(dr["ItemUrl"].ToString(), itemId);
                item.Link            = new Uri(Request.Url, blogItemUrl);
                item.Guid            = new RssGuid(blogItemUrl);
                item.Title           = dr["Heading"].ToString();
                item.PublicationDate = Convert.ToDateTime(dr["StartDate"]);

                bool showAuthor = Convert.ToBoolean(dr["ShowAuthorName"]);
                if (showAuthor)
                {
                    // techically this is supposed to be an email address
                    // but wouldn't that lead to a lot of spam?

                    string authorEmail = dr["Email"].ToString();
                    string authorName  = dr["Name"].ToString();

                    if (BlogConfiguration.IncludeAuthorEmailInFeed)
                    {
                        item.Author = authorEmail + " (" + authorName + ")";
                    }
                    else
                    {
                        item.Author = authorName;
                    }
                }
                else if (config.ManagingEditorEmail.Length > 0)
                {
                    item.Author = config.ManagingEditorEmail;
                }

                item.Comments = new Uri(blogItemUrl);

                string signature = string.Empty;

                if (config.AddSignature)
                {
                    signature = "<br /><a href='" + blogItemUrl + "'>" + dr["Name"].ToString() + "</a>";
                }

                if ((config.AddCommentsLinkToFeed) && (config.AllowComments))
                {
                    signature += "&nbsp;&nbsp;" + "<a href='" + blogItemUrl + "'>...</a>";
                }

                if (config.AddTweetThisToFeed)
                {
                    signature += GenerateTweetThisLink(item.Title, blogItemUrl);
                }

                if (config.AddFacebookLikeToFeed)
                {
                    signature += GenerateFacebookLikeButton(blogItemUrl);
                }


                string blogPost = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Description"].ToString().RemoveCDataTags());

                string staticMapLink = BuildStaticMapMarkup(dr);

                if (staticMapLink.Length > 0)
                {
                    // add a google static map
                    blogPost += staticMapLink;
                }


                if ((!config.UseExcerptInFeed) || (blogPost.Length <= config.ExcerptLength))
                {
                    item.Description = blogPost + signature;
                }
                else
                {
                    string excerpt = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, dr["Abstract"].ToString().RemoveCDataTags());

                    if ((excerpt.Length > 0) && (excerpt != "<p>&#160;</p>"))
                    {
                        excerpt = excerpt
                                  + config.ExcerptSuffix
                                  + " <a href='"
                                  + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'>&nbsp;</div>";
                    }
                    else
                    {
                        excerpt = UIHelper.CreateExcerpt(dr["Description"].ToString(), config.ExcerptLength, config.ExcerptSuffix)
                                  + " <a href='"
                                  + blogItemUrl + "'>" + config.MoreLinkText + "</a><div class='excerptspacer'>&nbsp;</div>";;
                    }

                    item.Description = excerpt;
                }



                // how to add media enclosures for podcasting
                //http://www.podcast411.com/howto_1.html

                //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed

                //http://techwhimsy.com/stream-mp3s-with-google-mp3-player


                //Uri url = new Uri("http://media.libsyn.com/media/podcast411/411_060325.mp3");
                //string type = "audio/mpeg";
                //long length = 11779397;

                string blogGuid    = dr["BlogGuid"].ToString();
                string whereClause = string.Format("ItemGuid = '{0}'", blogGuid);


                if (!config.UseExcerptInFeed)
                {
                    DataView dv = new DataView(dsBlogPosts.Tables["Attachments"], whereClause, "", DataViewRowState.CurrentRows);

                    foreach (DataRowView rowView in dv)
                    {
                        DataRow row = rowView.Row;

                        Uri    mediaUrl      = new Uri(WebUtils.ResolveServerUrl(attachmentBaseUrl + row["ServerFileName"].ToString()));
                        long   contentLength = Convert.ToInt64(row["ContentLength"]);
                        string contentType   = row["ContentType"].ToString();

                        RssEnclosure enclosure = new RssEnclosure(contentLength, contentType, mediaUrl);
                        item.Enclosures.Add(enclosure);

                        //http://argotic.codeplex.com/wikipage?title=Generating%20an%20extended%20RSS%20feed

                        ITunesSyndicationExtension itemExtension = new ITunesSyndicationExtension();
                        itemExtension.Context.Author   = dr["Name"].ToString();
                        itemExtension.Context.Subtitle = dr["SubTitle"].ToString();
                        //itemExtension.Context.Summary = "The iTunes syndication extension properties that are used vary based on whether extending the channel or an item";
                        //itemExtension.Context.Duration = new TimeSpan(1, 2, 13);
                        //itemExtension.Context.Keywords.Add("Podcast");
                        //itemExtension.Context.Keywords.Add("iTunes");


                        whereClause = string.Format("ItemID = '{0}'", itemId);
                        DataView dvCat = new DataView(dsBlogPosts.Tables["Categories"], whereClause, "", DataViewRowState.CurrentRows);

                        foreach (DataRowView rView in dvCat)
                        {
                            DataRow r = rView.Row;

                            item.Categories.Add(new RssCategory(r["Category"].ToString()));

                            itemExtension.Context.Keywords.Add(r["Category"].ToString());
                        }

                        item.AddExtension(itemExtension);
                    }
                }



                channel.AddItem(item);
            }


            if ((config.FeedburnerFeedUrl.Length > 0) || (Request.Url.AbsolutePath.Contains("localhost")))
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30));
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.VaryByParams["r"] = true;
            }
            else
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(30));
                Response.Cache.SetCacheability(HttpCacheability.Public);
            }


            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();

            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");
                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");
                }
                ///////////////////////////

                feed.Save(xmlTextWriter);
            }
        }
Пример #16
0
        private static RssFeed SetRssAndChannel(string RssTitle, string RssDescription,
                                               string RssLink)
        {
            RssFeed ObjRss = new RssFeed { Version = RssVersion.RSS20, Encoding = Encoding.UTF8 };

            RssChannel ObjRSSChannel = new RssChannel
                                           {
                                               Title = RssTitle,
                                               Description = RssDescription,
                                               LastBuildDate = PersianDateTime.MiladiToPersian(DateTime.Now).ToShortDateString(),
                                               Link = new Uri(RssLink),
                                               PubDate = DateTime.Now,
                                               WebMaster = "BMI WebSite",
                                               Copyright = "(c) 2010, www.hossein-shirazi.ir. All rights reserved.",
                                               Generator = "www.hossein-shirazi.ir"
                                           };
            ObjRss.Channels.Add(ObjRSSChannel);

            return ObjRss;
        }
Пример #17
0
        public static RssChannel GetRssFeed(string path)
        {
            Path = path;
            if (_channel == null)
            {
                _channel = new RssChannel();
                _channel.Items = new List<RssItem>();

                try
                {
                    // Parse RSS
                    using (XmlReader reader = XmlReader.Create(path))
                    {
                        // Get channel Info
                        if (!reader.ReadToFollowing("channel")) return null;

                        if (reader.ReadToFollowing("title"))
                        {
                            _channel.Title = reader.ReadElementContentAsString();
                        }
                        if (reader.ReadToFollowing("description"))
                        {
                            _channel.Description = reader.ReadElementContentAsString();
                        }
                        if (reader.ReadToFollowing("link"))
                        {
                            _channel.Link = reader.ReadElementContentAsString();
                        }
                        if (reader.ReadToFollowing("lastBuildDate"))
                        {
                            _channel.LastBuild = StringToDateTime(reader.ReadElementContentAsString());
                        }
                        if (reader.ReadToFollowing("pubDate"))
                        {
                            _channel.PubDate = StringToDateTime(reader.ReadElementContentAsString());
                        }
                        if (reader.ReadToFollowing("ttl"))
                        {
                            _channel.Ttl = reader.ReadElementContentAsInt();
                        }

                        // Get items
                        while (reader.ReadToFollowing("item"))
                        {
                            RssItem item = new RssItem();

                            if (reader.ReadToFollowing("title"))
                            {
                                item.Title = reader.ReadElementContentAsString();
                            }
                            if (reader.ReadToFollowing("description"))
                            {
                                item.Description = reader.ReadElementContentAsString();
                            }
                            if (reader.ReadToFollowing("link"))
                            {
                                item.Link = reader.ReadElementContentAsString();
                            }
                            if (reader.ReadToFollowing("guid"))
                            {
                                item.GuID = reader.ReadElementContentAsInt();
                            }
                            if (reader.ReadToFollowing("pubDate"))
                            {
                                item.PubDate = StringToDateTime(reader.ReadElementContentAsString());
                            }

                            // Add the new item
                            _channel.Items.Add(item);
                        }
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    _channel = null;
                }
            }

            return _channel;
        }
Пример #18
0
 public RssDocument()
 {
     Channel = new RssChannel();
     Version = "2.0";
 }
Пример #19
0
        /// <summary>Reads the next RssElement from the stream.</summary>
        /// <returns>An RSS Element</returns>
        /// <exception cref="InvalidOperationException">RssReader has been closed, and can not be read.</exception>
        /// <exception cref="System.IO.FileNotFoundException">RSS file not found.</exception>
        /// <exception cref="System.Xml.XmlException">Invalid XML syntax in RSS file.</exception>
        /// <exception cref="System.IO.EndOfStreamException">Unable to read an RssElement. Reached the end of the stream.</exception>
        public RssElement Read()
        {
            bool readData = false;
            bool pushElement = true;
            RssElement rssElement = null;
            int lineNumber = -1;
            int linePosition = -1;

            if (reader == null)
                throw new InvalidOperationException("RssReader has been closed, and can not be read.");

            do
            {
                pushElement = true;
                try
                {
                    readData = reader.Read();
                }
                catch (EndOfStreamException e)
                {
                    throw new EndOfStreamException("Unable to read an RssElement. Reached the end of the stream.", e);
                }
                catch (XmlException e)
                {
                    if (lineNumber != -1 || linePosition != -1)
                        if (reader.LineNumber == lineNumber && reader.LinePosition == linePosition)
                            throw exceptions.LastException;

                    lineNumber = reader.LineNumber;
                    linePosition = reader.LinePosition;

                    exceptions.Add(e); // just add to list of exceptions and continue :)
                }
                if (readData)
                {
                    string readerName = reader.Name.ToLower();
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            {
                                if (reader.IsEmptyElement)
                                    break;
                                elementText = new StringBuilder();

                                switch (readerName)
                                {
                                    case "item":
                                        // is this the end of the channel element? (absence of </channel> before <item>)
                                        if (!wroteChannel)
                                        {
                                            wroteChannel = true;
                                            rssElement = channel; // return RssChannel
                                            readData = false;
                                        }
                                        item = new global::Utility.RSS.NET.RssItem.RssItem(); // create new RssItem
                                        channel.Items.Add(item);
                                        break;
                                    case "source":
                                        source = new RssSource();
                                        item.Source = source;
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            switch (reader.Name.ToLower())
                                            {
                                                case "url":
                                                    try
                                                    {
                                                        source.Url = new Uri(reader.Value);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        exceptions.Add(e);
                                                    }
                                                    break;
                                            }
                                        }
                                        break;
                                    case "enclosure":
                                        enclosure = new RssEnclosure();
                                        item.Enclosure = enclosure;
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            switch (reader.Name.ToLower())
                                            {
                                                case "url":
                                                    try
                                                    {
                                                        enclosure.Url = new Uri(reader.Value);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        exceptions.Add(e);
                                                    }
                                                    break;
                                                case "length":
                                                    try
                                                    {
                                                        enclosure.Length = int.Parse(reader.Value);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        exceptions.Add(e);
                                                    }
                                                    break;
                                                case "type":
                                                    enclosure.Type = reader.Value;
                                                    break;
                                            }
                                        }
                                        break;
                                    case "guid":
                                        guid = new RssGuid();
                                        item.Guid = guid;
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            switch (reader.Name.ToLower())
                                            {
                                                case "ispermalink":
                                                    try
                                                    {
                                                        guid.PermaLink = bool.Parse(reader.Value);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        exceptions.Add(e);
                                                    }
                                                    break;
                                            }
                                        }
                                        break;
                                    case "category":
                                        category = new RssCategory();
                                        if ((string) xmlNodeStack.Peek() == "channel")
                                            channel.Categories.Add(category);
                                        else
                                            item.Categories.Add(category);
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            switch (reader.Name.ToLower())
                                            {
                                                case "url":
                                                    goto case "domain";
                                                case "domain":
                                                    category.Domain = reader.Value;
                                                    break;
                                            }
                                        }
                                        break;
                                    case "channel":
                                        channel = new RssChannel();
                                        textInput = null;
                                        image = null;
                                        cloud = null;
                                        source = null;
                                        enclosure = null;
                                        category = null;
                                        item = null;
                                        break;
                                    case "image":
                                        image = new RssImage();
                                        channel.Image = image;
                                        break;
                                    case "textinput":
                                        textInput = new RssTextInput();
                                        channel.TextInput = textInput;
                                        break;
                                    case "cloud":
                                        pushElement = false;
                                        cloud = new RssCloud();
                                        channel.Cloud = cloud;
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            switch (reader.Name.ToLower())
                                            {
                                                case "domain":
                                                    cloud.Domain = reader.Value;
                                                    break;
                                                case "port":
                                                    try
                                                    {
                                                        cloud.Port = ushort.Parse(reader.Value);
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        exceptions.Add(e);
                                                    }
                                                    break;
                                                case "path":
                                                    cloud.Path = reader.Value;
                                                    break;
                                                case "registerprocedure":
                                                    cloud.RegisterProcedure = reader.Value;
                                                    break;
                                                case "protocol":
                                                    switch (reader.Value.ToLower())
                                                    {
                                                        case "xml-rpc":
                                                            cloud.Protocol = RssCloudProtocol.XmlRpc;
                                                            break;
                                                        case "soap":
                                                            cloud.Protocol = RssCloudProtocol.Soap;
                                                            break;
                                                        case "http-post":
                                                            cloud.Protocol = RssCloudProtocol.HttpPost;
                                                            break;
                                                        default:
                                                            cloud.Protocol = RssCloudProtocol.Empty;
                                                            break;
                                                    }
                                                    break;
                                            }
                                        }
                                        break;
                                    case "rss":
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            if (reader.Name.ToLower() == "version")
                                                switch (reader.Value)
                                                {
                                                    case "0.91":
                                                        rssVersion = RssVersion.RSS091;
                                                        break;
                                                    case "0.92":
                                                        rssVersion = RssVersion.RSS092;
                                                        break;
                                                    case "2.0":
                                                        rssVersion = RssVersion.RSS20;
                                                        break;
                                                    default:
                                                        rssVersion = RssVersion.NotSupported;
                                                        break;
                                                }
                                        }
                                        break;
                                    case "rdf":
                                        for (int i = 0; i < reader.AttributeCount; i++)
                                        {
                                            reader.MoveToAttribute(i);
                                            if (reader.Name.ToLower() == "version")
                                                switch (reader.Value)
                                                {
                                                    case "0.90":
                                                        rssVersion = RssVersion.RSS090;
                                                        break;
                                                    case "1.0":
                                                        rssVersion = RssVersion.RSS10;
                                                        break;
                                                    default:
                                                        rssVersion = RssVersion.NotSupported;
                                                        break;
                                                }
                                        }
                                        break;
                                }
                                if (pushElement)
                                    xmlNodeStack.Push(readerName);
                                break;
                            }
                        case XmlNodeType.EndElement:
                            {
                                if (xmlNodeStack.Count == 1)
                                    break;
                                string childElementName = (string) xmlNodeStack.Pop();
                                string parentElementName = (string) xmlNodeStack.Peek();
                                switch (childElementName) // current element
                                {
                                        // item classes
                                    case "item":
                                        rssElement = item;
                                        readData = false;
                                        break;
                                    case "source":
                                        source.Name = elementText.ToString();
                                        rssElement = source;
                                        readData = false;
                                        break;
                                    case "enclosure":
                                        rssElement = enclosure;
                                        readData = false;
                                        break;
                                    case "guid":
                                        guid.Name = elementText.ToString();
                                        rssElement = guid;
                                        readData = false;
                                        break;
                                    case "category": // parent is either item or channel
                                        category.Name = elementText.ToString();
                                        rssElement = category;
                                        readData = false;
                                        break;
                                        // channel classes
                                    case "channel":
                                        if (wroteChannel)
                                            wroteChannel = false;
                                        else
                                        {
                                            wroteChannel = true;
                                            rssElement = channel;
                                            readData = false;
                                        }
                                        break;
                                    case "textinput":
                                        rssElement = textInput;
                                        readData = false;
                                        break;
                                    case "image":
                                        rssElement = image;
                                        readData = false;
                                        break;
                                    case "cloud":
                                        rssElement = cloud;
                                        readData = false;
                                        break;
                                }
                                switch (parentElementName) // parent element
                                {
                                    case "item":
                                        switch (childElementName)
                                        {
                                            case "title":
                                                item.Title = elementText.ToString();
                                                break;
                                            case "link":
                                                item.Link = new Uri(elementText.ToString());
                                                break;
                                            case "description":
                                                item.Description = elementText.ToString();
                                                break;
                                            case "author":
                                                item.Author = elementText.ToString();
                                                break;
                                            case "comments":
                                                item.Comments = elementText.ToString();
                                                break;
                                            case "pubdate":
                                                try
                                                {
                                                    item.PubDate = DateTime.Parse(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    try
                                                    {
                                                        string tmp = elementText.ToString();
                                                        tmp = tmp.Substring(0, tmp.Length - 5);
                                                        tmp += "GMT";
                                                        item.PubDate = DateTime.Parse(tmp);
                                                    }
                                                    catch
                                                    {
                                                        exceptions.Add(e);
                                                    }
                                                }
                                                break;
                                        }
                                        break;
                                    case "channel":
                                        switch (childElementName)
                                        {
                                            case "title":
                                                channel.Title = elementText.ToString();
                                                break;
                                            case "link":
                                                try
                                                {
                                                    channel.Link = new Uri(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                            case "description":
                                                channel.Description = elementText.ToString();
                                                break;
                                            case "language":
                                                channel.Language = elementText.ToString();
                                                break;
                                            case "copyright":
                                                channel.Copyright = elementText.ToString();
                                                break;
                                            case "managingeditor":
                                                channel.ManagingEditor = elementText.ToString();
                                                break;
                                            case "webmaster":
                                                channel.WebMaster = elementText.ToString();
                                                break;
                                            case "rating":
                                                channel.Rating = elementText.ToString();
                                                break;
                                            case "pubdate":
                                                try
                                                {
                                                    channel.PubDate = DateTime.Parse(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                            case "lastbuilddate":
                                                try
                                                {
                                                    channel.LastBuildDate = elementText.ToString();
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                            case "generator":
                                                channel.Generator = elementText.ToString();
                                                break;
                                            case "docs":
                                                channel.Docs = elementText.ToString();
                                                break;
                                            case "ttl":
                                                try
                                                {
                                                    channel.TimeToLive = int.Parse(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                        }
                                        break;
                                    case "image":
                                        switch (childElementName)
                                        {
                                            case "url":
                                                try
                                                {
                                                    image.Url = new Uri(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                            case "title":
                                                image.Title = elementText.ToString();
                                                break;
                                            case "link":
                                                try
                                                {
                                                    image.Link = new Uri(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                            case "description":
                                                image.Description = elementText.ToString();
                                                break;
                                            case "width":
                                                try
                                                {
                                                    image.Width = Byte.Parse(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                            case "height":
                                                try
                                                {
                                                    image.Height = Byte.Parse(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                        }
                                        break;
                                    case "textinput":
                                        switch (childElementName)
                                        {
                                            case "title":
                                                textInput.Title = elementText.ToString();
                                                break;
                                            case "description":
                                                textInput.Description = elementText.ToString();
                                                break;
                                            case "name":
                                                textInput.Name = elementText.ToString();
                                                break;
                                            case "link":
                                                try
                                                {
                                                    textInput.Link = new Uri(elementText.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    exceptions.Add(e);
                                                }
                                                break;
                                        }
                                        break;
                                    case "skipdays":
                                        if (childElementName == "day")
                                            switch (elementText.ToString().ToLower())
                                            {
                                                case "monday":
                                                    channel.SkipDays[0] = true;
                                                    break;
                                                case "tuesday":
                                                    channel.SkipDays[1] = true;
                                                    break;
                                                case "wednesday":
                                                    channel.SkipDays[2] = true;
                                                    break;
                                                case "thursday":
                                                    channel.SkipDays[3] = true;
                                                    break;
                                                case "friday":
                                                    channel.SkipDays[4] = true;
                                                    break;
                                                case "saturday":
                                                    channel.SkipDays[5] = true;
                                                    break;
                                                case "sunday":
                                                    channel.SkipDays[6] = true;
                                                    break;
                                            }
                                        break;
                                    case "skiphours":
                                        if (childElementName == "hour")
                                            channel.SkipHours[Byte.Parse(elementText.ToString().ToLower())] = true;
                                        break;
                                }
                                break;
                            }
                        case XmlNodeType.Text:
                            elementText.Append(reader.Value);
                            break;
                        case XmlNodeType.CDATA:
                            elementText.Append(reader.Value);
                            break;
                    }
                }
            } while (readData);
            return rssElement;
        }
Пример #20
0
        public async Task <RssChannel> GetChannel(CancellationToken cancellationToken = default(CancellationToken))
        {
            var blog  = _blogService.GetBlogSettings();
            var posts = _blogService.GetPostList(new PostListRequest
            {
                PageIndex = 0,
                PageSize  = maxFeedItems
            }).Posts;

            var categories = _blogService.GetCategories();

            var channel = new RssChannel();

            channel.Title       = blog.BlogName;
            channel.Description = blog.Description;
            channel.Generator   = Name;

            foreach (var cat in categories)
            {
                channel.Categories.Add(new RssCategory(cat.Title));
            }

            var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccesor.ActionContext);
            var baseUrl   = string.Concat(
                _contextAccessor.HttpContext.Request.Scheme,
                "://",
                _contextAccessor.HttpContext.Request.Host.ToUriComponent()
                );

            var indexUrl = urlHelper.RouteUrl("spa-fallback");

            if (indexUrl.StartsWith("/"))
            {
                indexUrl = string.Concat(baseUrl, indexUrl);
            }
            channel.Link = new Uri(indexUrl);

            channel.TimeToLive = 60;

            var items = new List <RssItem>();

            foreach (var post in posts)
            {
                var rssItem = new RssItem();
                rssItem.Author = post.UserDisplayName;

                foreach (var c in post.Categories)
                {
                    rssItem.Categories.Add(new RssCategory(c.Title));
                }

                rssItem.Description = _htmlProcessor.ConvertUrlsToAbsolute(baseUrl, post.Content);

                var postUrl = $"{baseUrl}/post/{post.Slug}";
                rssItem.Link = new Uri(postUrl);

                rssItem.Guid            = new RssGuid(postUrl);
                rssItem.PublicationDate = DateTime.Parse(post.PublishDate);
                rssItem.Title           = post.Title;
                items.Add(rssItem);
            }

            channel.PublicationDate = DateTime.Parse(posts.First().PublishDate);
            channel.Items           = items;

            return(channel);
        }
Пример #21
0
        private static string ParseImpl(PageInfo pageInfo, ContextInfo contextInfo, string title, string description, string scopeTypeString, string groupChannel, string groupChannelNot, string groupContent, string groupContentNot, string tags, string channelIndex, string channelName, int totalNum, int startNum, string orderByString, bool isTop, bool isTopExists, bool isRecommend, bool isRecommendExists, bool isHot, bool isHotExists, bool isColor, bool isColorExists)
        {
            var feed = new RssFeed
            {
                Encoding = ECharsetUtils.GetEncoding(pageInfo.TemplateInfo.Charset),
                Version  = RssVersion.RSS20
            };

            var channel = new RssChannel
            {
                Title       = title,
                Description = description
            };

            var scopeType = !string.IsNullOrEmpty(scopeTypeString) ? EScopeTypeUtils.GetEnumType(scopeTypeString) : EScopeType.All;

            var channelId = StlDataUtility.GetChannelIdByChannelIdOrChannelIndexOrChannelName(pageInfo.SiteId, contextInfo.ChannelId, channelIndex, channelName);

            var nodeInfo = ChannelManager.GetChannelInfo(pageInfo.SiteId, channelId);

            if (string.IsNullOrEmpty(channel.Title))
            {
                channel.Title = nodeInfo.ChannelName;
            }
            if (string.IsNullOrEmpty(channel.Description))
            {
                channel.Description = nodeInfo.Content;
                channel.Description = string.IsNullOrEmpty(channel.Description) ? nodeInfo.ChannelName : StringUtils.MaxLengthText(channel.Description, 200);
            }
            channel.Link = new Uri(PageUtils.AddProtocolToUrl(PageUtility.GetChannelUrl(pageInfo.SiteInfo, nodeInfo, pageInfo.IsLocal)));

            var minContentInfoList = StlDataUtility.GetMinContentInfoList(pageInfo.SiteInfo, channelId, 0, groupContent, groupContentNot, tags, false, false, false, false, false, false, false, startNum, totalNum, orderByString, isTopExists, isTop, isRecommendExists, isRecommend, isHotExists, isHot, isColorExists, isColor, string.Empty, scopeType, groupChannel, groupChannelNot, null);

            if (minContentInfoList != null)
            {
                foreach (var minContentInfo in minContentInfoList)
                {
                    var item = new RssItem();

                    var contentInfo = ContentManager.GetContentInfo(pageInfo.SiteInfo, minContentInfo.ChannelId, minContentInfo.Id);
                    item.Title       = StringUtils.Replace("&", contentInfo.Title, "&amp;");
                    item.Description = contentInfo.Summary;
                    if (string.IsNullOrEmpty(item.Description))
                    {
                        item.Description = StringUtils.StripTags(contentInfo.Content);
                        item.Description = string.IsNullOrEmpty(item.Description) ? contentInfo.Title : StringUtils.MaxLengthText(item.Description, 200);
                    }
                    item.Description = StringUtils.Replace("&", item.Description, "&amp;");
                    item.PubDate     = contentInfo.AddDate;
                    item.Link        = new Uri(PageUtils.AddProtocolToUrl(PageUtility.GetContentUrl(pageInfo.SiteInfo, contentInfo, false)));

                    channel.Items.Add(item);
                }
            }

            feed.Channels.Add(channel);

            var builder    = new StringBuilder();
            var textWriter = new EncodedStringWriter(builder, ECharsetUtils.GetEncoding(pageInfo.TemplateInfo.Charset));

            feed.Write(textWriter);

            return(builder.ToString());
        }
Пример #22
0
        public async Task AddChannelAsync(RssChannel newChannel)
        {
            await rSSContext.AddAsync(newChannel);

            await rSSContext.SaveChangesAsync();
        }
Пример #23
0
 /// <summary>
 /// Sets the parent channel that the item is assigned to.
 /// </summary>
 /// <remarks>
 /// This internal method is called when the item is assigned to <see cref="RssItemCollection"/>. Do not call directly!
 /// </remarks>
 internal void SetChannel(RssChannel value)
 {
     _rssChannel = value;
 }
Пример #24
0
        private bool Download(Uri location)
        {
            int i   = 0;
            Uri uri = location;

            for (int j = 0; j < NUM_STORIES; j++)
            {
                m_feed_details[j].m_site        = "";
                m_feed_details[j].m_title       = "";
                m_feed_details[j].m_description = "";
            }

            try
            {
                RssFeed    feed    = RssFeed.Read(location.ToString());
                RssChannel channel = (RssChannel)feed.Channels[0];

                // Download the image from the feed if available/needed
                if (channel.Image != null && m_strSiteIcon == DEFAULT_NEWS_ICON)
                {
                    string strImage = channel.Image.Url.ToString();

                    if (strImage.Length > 0)
                    {
                        //m_strSiteIcon = MediaPortal.Util.Utils.GetThumb(m_strSiteURL);
                        m_strSiteIcon = Util.Utils.GetCoverArtName(Thumbs.News, m_strSiteURL);
                        if (!Util.Utils.FileExistsInCache(m_strSiteIcon))
                        {
                            string strExtension;
                            strExtension = Path.GetExtension(strImage);
                            if (strExtension.Length > 0)
                            {
                                string strTemp = "temp";
                                strTemp += strExtension;
                                strTemp  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), strTemp);

                                Util.Utils.FileDelete(strTemp);
                                Util.Utils.DownLoadImage(strImage, strTemp);
                                //MediaPortal.Util.Utils.DownLoadAndCacheImage(strImage, strTemp);

                                if (Util.Utils.FileExistsInCache(strTemp))
                                {
                                    Util.Picture.CreateThumbnail(strTemp, m_strSiteIcon, (int)Thumbs.ThumbResolution,
                                                                 (int)Thumbs.ThumbResolution, 0, Thumbs.SpeedThumbsSmall);
                                }

                                Util.Utils.FileDelete(strTemp);
                            } //if ( strExtension.Length>0)
                            else
                            {
                                Log.Info("image has no extension:{0}", strImage);
                            }
                            m_strSiteIcon = Util.Utils.GetCoverArtName(Thumbs.News, m_strSiteURL);
                        }
                        //m_strSiteIcon = MediaPortal.Util.Utils.GetThumb(m_strSiteURL);
                    }
                }

                // Fill the items
                foreach (RssItem item in channel.Items)
                {
                    // Check if there are HTML tags in the description, if so we need to "parse" the HTML
                    // which is actually just stripping the tags.
                    if (Regex.IsMatch(item.Description, @"<[^>]*>"))
                    {
                        // Strip \n's
                        item.Description = Regex.Replace(item.Description, @"(\n|\r)", "", RegexOptions.Multiline);

                        // Remove whitespace (double spaces)
                        item.Description = Regex.Replace(item.Description, @"  +", "", RegexOptions.Multiline);

                        // Replace <br/> with \n
                        item.Description = Regex.Replace(item.Description, @"< *br */*>", "\n",
                                                         RegexOptions.IgnoreCase & RegexOptions.Multiline);

                        // Remove remaining HTML tags
                        item.Description = Regex.Replace(item.Description, @"<[^>]*>", "", RegexOptions.Multiline);
                    }

                    // Strip newlines from titles because it looks funny to see multiple lines in the listbox
                    item.Title = Regex.Replace(item.Title, @" *(\n|\r)+ *", " ", RegexOptions.Multiline);

                    if (item.Description == "")
                    {
                        item.Description = item.Title;
                    }
                    else
                    {
                        item.Description = item.Title + ": \n\n" + item.Description + "\n";
                    }

                    //
                    m_feed_details[i].m_site        = channel.Title;
                    m_feed_details[i].m_title       = item.Title;
                    m_feed_details[i].m_description = item.Description;
                    m_feed_details[i].m_link        = item.Link.ToString();

                    // Make sure that everything is "decoded" like &amp; becomes &
                    m_feed_details[i].m_title       = HttpUtility.HtmlDecode(m_feed_details[i].m_title);
                    m_feed_details[i].m_description = HttpUtility.HtmlDecode(m_feed_details[i].m_description);

                    i++;
                    if (i >= NUM_STORIES)
                    {
                        break;
                    }
                }

                UpdateButtons();
                m_lRefreshTime = DateTime.Now;
            }
            catch (WebException ex)
            {
                m_lRefreshTime = DateTime.Now;
                throw ex;
            }

            return(true);
        }
Пример #25
0
        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);
            }

            var 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/");
            documentRoot.Namespaces.Add("webfeeds", "http://webfeeds.org/rss/1.0");
            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");
            }

            var ch = new RssChannel();

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

            if (string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.Description))
            {
                ch.Description = dasBlogSettings.SiteConfiguration.Subtitle;
            }
            else
            {
                ch.Description = dasBlogSettings.SiteConfiguration.Description;
            }

            ch.Link      = dasBlogSettings.GetBaseUrl();
            ch.Copyright = dasBlogSettings.SiteConfiguration.Copyright;
            if (!string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.RssLanguage))
            {
                ch.Language = dasBlogSettings.SiteConfiguration.RssLanguage;
            }

            ch.ManagingEditor = dasBlogSettings.SiteConfiguration.Contact;
            ch.WebMaster      = dasBlogSettings.SiteConfiguration.Contact;
            ch.Image          = null;

            if (!string.IsNullOrWhiteSpace(dasBlogSettings.SiteConfiguration.ChannelImageUrl))
            {
                var channelImage = new DasBlog.Services.Rss.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;
            }

            var xdoc         = new XmlDocument();
            var rootElements = new List <XmlElement>();

            var wflogo = xdoc.CreateElement("webfeeds", "logo", "http://webfeeds.org/rss/1.0");

            wflogo.InnerText = dasBlogSettings.RelativeToRoot(dasBlogSettings.SiteConfiguration.ChannelImageUrl);
            rootElements.Add(wflogo);

            var wfanalytics = xdoc.CreateElement("webfeeds", "analytics", "http://webfeeds.org/rss/1.0");
            var attribId    = xdoc.CreateAttribute("id");

            attribId.Value = dasBlogSettings.MetaTags.GoogleAnalyticsID;
            wfanalytics.Attributes.Append(attribId);

            var attribEngine = xdoc.CreateAttribute("engine");

            attribEngine.Value = "GoogleAnalytics";
            wfanalytics.Attributes.Append(attribEngine);

            rootElements.Add(wfanalytics);

            ch.anyElements = rootElements.ToArray();

            ch.Items = new RssItemCollection();
            documentRoot.Channels.Add(ch);

            foreach (var entry in entries)
            {
                if (entry.IsPublic == false || entry.Syndicated == false)
                {
                    continue;
                }
                var doc2        = new XmlDocument();
                var anyElements = new List <XmlElement>();
                var item        = new RssItem();
                item.Title            = entry.Title;
                item.Guid             = new DasBlog.Services.Rss.Rss20.Guid();
                item.Guid.IsPermaLink = false;
                item.Guid.Text        = dasBlogSettings.GetPermaLinkUrl(entry.EntryId);
                item.Link             = dasBlogSettings.RelativeToRoot(dasBlogSettings.GeneratePostUrl(entry));
                User user = dasBlogSettings.GetUserByEmail(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.PingBackUrl;
                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)
                {
                    var latitude  = new Nullable <double>();
                    var 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(dasBlogSettings.GeneratePostUrl(entry));
                        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(dasBlogSettings.GeneratePostUrl(entry));
                }
                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);
        }
Пример #26
0
        private void RenderRss(int moduleId)
        {
            Response.ContentType     = "text/xml";
            Response.ContentEncoding = System.Text.Encoding.UTF8;

            //Cynthia.Business.RssFeed feed = new Cynthia.Business.RssFeed(moduleId);
            Module    module         = GetModule();
            Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleId);

            feedListCacheTimeout = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "RSSFeedFeedListCacheTimeoutSetting", 3660);

            entryCacheTimeout = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "RSSFeedEntryCacheTimeoutSetting", 3620);

            maxDaysOld = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "RSSFeedMaxDayCountSetting", 90);

            maxEntriesPerFeed = WebUtils.ParseInt32FromHashtable(
                moduleSettings, "RSSFeedMaxPostsPerFeedSetting", 90);

            EnableSelectivePublishing = WebUtils.ParseBoolFromHashtable(
                moduleSettings, "EnableSelectivePublishing", EnableSelectivePublishing);


            DataView dv = FeedCache.GetRssFeedEntries(
                module.ModuleId,
                module.ModuleGuid,
                entryCacheTimeout,
                maxDaysOld,
                maxEntriesPerFeed,
                EnableSelectivePublishing).DefaultView;

            dv.Sort = "PubDate DESC";

            //if (EnableSelectivePublishing)
            //{
            //    dv.RowFilter = "Confirmed = true";
            //}

            RssChannel channel = new RssChannel();
            object     value   = GetModule();
            Module     m;

            if (value != null)
            {
                m = (Module)value;

                channel.Title         = m.ModuleTitle;
                channel.Description   = m.ModuleTitle;
                channel.LastBuildDate = channel.Items.LatestPubDate();
                channel.Link          = new System.Uri(SiteUtils.GetCurrentPageUrl());
            }
            else
            {
                // this prevents an error: Can't close RssWriter without first writing a channel.
                channel.Title         = "Not Found";
                channel.Description   = "Not Found";
                channel.LastBuildDate = DateTime.UtcNow;
                //channel.Link = new System.Uri(SiteUtils.GetCurrentPageUrl());
            }

            foreach (DataRowView row in dv)
            {
                bool confirmed = Convert.ToBoolean(row["Confirmed"]);
                if (!EnableSelectivePublishing)
                {
                    confirmed = true;
                }

                if (confirmed)
                {
                    RssItem item = new RssItem();


                    item.Title       = row["Title"].ToString();
                    item.Description = row["Description"].ToString();
                    item.PubDate     = Convert.ToDateTime(row["PubDate"]);
                    item.Link        = new System.Uri(row["Link"].ToString());
                    Trace.Write(item.Link.ToString());
                    item.Author = row["Author"].ToString();

                    channel.Items.Add(item);
                }
            }



            Rss.RssFeed rss = new Rss.RssFeed();
            rss.Encoding = System.Text.Encoding.UTF8;
            rss.Channels.Add(channel);
            rss.Write(Response.OutputStream);

            //Response.End();
        }
Пример #27
0
        public async Task <IActionResult> Rss()
        {
            rss        rss        = new rss();
            RssChannel rssChannel = new RssChannel();

            rss.channel = rssChannel;

            Image feedImage = new Image();

            feedImage.link   = WeblogUri.AbsoluteUri;
            feedImage.title  = WeblogTitle;
            feedImage.width  = WeblogImageWidth.ToString(RssLocFormat);
            feedImage.height = WeblogImageHeight.ToString(RssLocFormat);
            feedImage.url    = WeblogImageUri.AbsoluteUri;

            rssChannel.ItemsElementName = new ItemsChoiceType[] {
                // Ordering must correspond to the contents of rssChannel.Items
                ItemsChoiceType.title,
                ItemsChoiceType.link,
                ItemsChoiceType.language,
                ItemsChoiceType.image
            };

            rssChannel.Items = new object[] {
                WeblogTitle,
                WeblogUri.AbsoluteUri,     // Must be a string value
                WeblogLanguage.ToString(), // Must be a string value
                feedImage
            };

            // Gets all the blog post items from repo.
            var     json      = await(await this.httpClient.GetAsync($"blogPosts/paginate/{this.pageSize}/1")).Content.ReadAsStringAsync();
            dynamic blogPosts = JsonConvert.DeserializeObject(json);

            var rssItemList = new List <RssItem>();

            foreach (dynamic post in blogPosts.data)
            {
                var rssItem = new RssItem();
                rssItem.ItemsElementName = new ItemsChoiceType1[]
                {
                    ItemsChoiceType1.link,
                    ItemsChoiceType1.pubDate,
                    ItemsChoiceType1.guid,
                    ItemsChoiceType1.title,
                    ItemsChoiceType1.description,
                    ItemsChoiceType1.category
                };

                var itemGuid = new RssItemGuid
                {
                    isPermaLink = false,
                    Value       = ((int)post.id).ToString()
                };


                var link         = Url.Action("Post", "BlogPosts", new { id = (int)post.id }, Url.ActionContext.HttpContext.Request.Scheme);
                var itemUri      = new Uri(link);
                var itemPubDate  = (DateTime)post.datePublished;
                var itemTitle    = (string)post.title;
                var itemBody     = (string)post.content;
                var itemCategory = new Category {
                    Value = ItemCategoryName
                };

                rssItem.Items = new object[] {
                    itemUri.AbsoluteUri,  // Must be a string value
                    itemPubDate.ToString( // Format data value
                        DateTimeFormatInfo.InvariantInfo.RFC1123Pattern,
                        RssLocFormat),
                    itemGuid,
                    itemTitle,
                    itemBody,
                    itemCategory
                };

                rssItemList.Add(rssItem);
            }

            rssChannel.item = rssItemList.ToArray();

            XmlSerializer serializer = new XmlSerializer(typeof(rss));

            using (var ms = new MemoryStream())
            {
                serializer.Serialize(ms, rss);
                return(Content(Encoding.UTF8.GetString(ms.ToArray()), "application/xml"));
            }
        }
Пример #28
0
        public Task <RssChannel> GetChannel(CancellationToken cancellationToken = default(CancellationToken))
        {
            var posts = feedRepository.GetPosts(settings.ItemsShownInFeed);

            var channel = new RssChannel();

            channel.Title       = settings.BlogName;
            channel.Description = settings.BlogDescription;

            foreach (Category category in feedRepository.GetAllCategories())
            {
                channel.Categories.Add(new RssCategory(category.Name));
            }

            foreach (var user in feedRepository.GetAllUsers())
            {
                //    feed.Authors.Add(new SyndicationPerson(user.Email, user.DisplayName, getAuthorUrl(user)));
            }

            channel.Generator = Name;

            var indexUrl = urlHelper.Action("Index", "Post", null, contextAccessor.HttpContext.Request.Scheme);

            channel.Link = new Uri(indexUrl);

            string feedUrl = urlHelper.Action("Rss20", "Feed", null, contextAccessor.HttpContext.Request.Scheme);

            channel.SelfLink = new Uri(feedUrl);

            var items = new List <RssItem>();

            foreach (var post in posts)
            {
                var rssItem = new RssItem();
                rssItem.Author = post.Author.DisplayName;

                foreach (var c in post.PostCategories)
                {
                    rssItem.Categories.Add(new RssCategory(c.Category.Name));
                }

                string content = post.Content ?? string.Empty;

                int moreIndex = content.IndexOf("[more]", StringComparison.OrdinalIgnoreCase);
                if (moreIndex >= 0)
                {
                    content = content.Remove(moreIndex, 6);
                }
                rssItem.Description = content;
                rssItem.Guid        = new RssGuid(post.Id.ToString());
                string postUrl = urlHelper.RouteUrl("PostDetail", new { postSlug = post.Slug }, contextAccessor.HttpContext.Request.Scheme);

                rssItem.Link            = new Uri(postUrl);
                rssItem.PublicationDate = post.LastModificationDate;
                rssItem.Title           = post.Title;

                items.Add(rssItem);
            }

            channel.PublicationDate = posts.Max(x => (DateTime?)x.LastModificationDate).GetValueOrDefault(DateTime.MinValue);
            channel.Items           = items;

            return(Task.FromResult(channel));
        }
 private ChannelWithSubscriptionCount ToChannelStatistics(RssChannel model)
 {
     var projection = new ChannelWithSubscriptionCount
     {
         Title = model.Title,
         Id = model.Id,
         SubscriptionCount = model.Subscriptions.Count
     };
     return projection;
 }
Пример #30
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            Context.Response.Clear();
            Context.Response.ContentType = "text/xml";
            if (Context.Request.QueryString["SectionId"] != null)
            {
                int    sectionId = Int32.Parse(Context.Request.QueryString["SectionId"]);
                string pathInfo  = Context.Request.PathInfo;
                string cacheKey  = String.Format("RSS_{0}_{1}", sectionId, pathInfo);
                string content   = null;

                if (Context.Cache[cacheKey] == null)
                {
                    // Get the data for the RSS feed because it's not in the cache yet.
                    // Use the same cache duration for the RSS feed as the Section.
                    Section section = this._sectionService.GetSectionById(sectionId);

                    ModuleBase module = this._moduleLoader.GetModuleFromSection(section);

                    module.ModulePathInfo = pathInfo;
                    ISyndicatable syndicatableModule = module as ISyndicatable;
                    if (syndicatableModule != null)
                    {
                        RssChannel channel = syndicatableModule.GetRssFeed();
                        // Rss feed writer code from http://aspnet.4guysfromrolla.com/articles/021804-1.aspx
                        // Use an XmlTextWriter to write the XML data to a string...
                        StringWriter  sw     = new StringWriter();
                        XmlTextWriter writer = new XmlTextWriter(sw);
                        writer.Formatting = Formatting.Indented;

                        // write out
                        writer.WriteStartElement("rss");
                        writer.WriteAttributeString("version", "2.0");
                        writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");

                        // write out
                        writer.WriteStartElement("channel");

                        // write out -level elements
                        writer.WriteElementString("title", channel.Title);
                        writer.WriteElementString("link", Util.UrlHelper.GetFullUrlFromSection(section) + pathInfo);
                        writer.WriteElementString("description", channel.Description);
                        writer.WriteElementString("language", channel.Language);
                        writer.WriteElementString("pubDate", channel.PubDate.ToUniversalTime().ToString("r"));
                        writer.WriteElementString("lastBuildDate", channel.LastBuildDate.ToUniversalTime().ToString("r"));
                        writer.WriteElementString("generator", channel.Generator);
                        writer.WriteElementString("ttl", channel.Ttl.ToString());

                        // Regular expression to find relative urls
                        string expression = String.Format(@"=[""']{0}", UrlHelper.GetApplicationPath());
                        Regex  regExUrl   = new Regex(expression, RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled);

                        foreach (RssItem item in channel.RssItems)
                        {
                            // replace inline relative hyperlinks with full hyperlinks
                            if (item.Description != null)
                            {
                                item.Description = regExUrl.Replace(item.Description, String.Format(@"=""{0}/", UrlHelper.GetSiteUrl()));
                            }

                            // write out
                            writer.WriteStartElement("item");

                            // write out -level information
                            writer.WriteElementString("title", item.Title);
                            // TODO: Only supports ID's in the pathinfo now...
                            writer.WriteElementString("link", Util.UrlHelper.GetFullUrlFromSection(section) + "/" + item.ItemId);
                            writer.WriteElementString("description", item.Description);
                            writer.WriteElementString("dc:creator", item.Author);
                            writer.WriteElementString("pubDate", item.PubDate.ToUniversalTime().ToString("r"));
                            writer.WriteElementString("category", item.Category);

                            // write out
                            writer.WriteEndElement();
                        }

                        // write out
                        writer.WriteEndElement();

                        // write out
                        writer.WriteEndElement();

                        content = sw.ToString();
                        // save the string in the cache
                        Cache.Insert(cacheKey, content, null, DateTime.Now.AddSeconds(section.CacheDuration), TimeSpan.Zero);

                        writer.Close();
                    }
                    else
                    {
                        throw new Exception(String.Format("The module {0} doesn't implement ISyndicatable", module.GetType().FullName));
                    }
                }
                else
                {
                    content = Context.Cache[cacheKey].ToString();
                }
                Context.Response.Write(content);
            }

            Context.Response.End();
        }
Пример #31
0
    private static XmlDocument addRssChannel(XmlDocument xmlDocument, RssChannel channel)
    {
        XmlElement channelElement = xmlDocument.CreateElement("channel");

        XmlNode rssElement = xmlDocument.SelectSingleNode("rss");

        rssElement.AppendChild(channelElement);

        XmlElement titleElement = xmlDocument.CreateElement("title");

        titleElement.InnerText = channel.Title;

        channelElement.AppendChild(titleElement);

        XmlElement linkElement = xmlDocument.CreateElement("link");

        linkElement.InnerText = channel.Link;

        channelElement.AppendChild(linkElement);

        XmlElement descriptionElement = xmlDocument.CreateElement("description");

        descriptionElement.InnerText = channel.Description;

        channelElement.AppendChild(descriptionElement);

        // Generator information

        XmlElement generatorElement = xmlDocument.CreateElement("generator");

        generatorElement.InnerText = "Your RSS Generator name and version ";

        channelElement.AppendChild(generatorElement);

        return xmlDocument;
    }
Пример #32
0
        public async Task GetRssTask(string link)
        {
            RssChanel = new RssChannel();

            bool isValid = await HttpService.GetHeadTask(link, true, true);

            if (!isValid)
            {
                //Link is not available
                ValidationText = "Link is not available";
                return;
            }

            ValidationText = "";

            string result = await HttpService.SendAsync(link);

            HtmlDocument doc = new HtmlDocument();

            if (string.IsNullOrEmpty(result))
            {
                //Link is not available
                ValidationText = "Link is not available";
                return;
            }
            doc.LoadHtml(result);

            var channelNode = doc.DocumentNode.Descendants("channel").First();

            bool t  = false;
            bool l  = false;
            bool d  = false;
            bool la = false;

            foreach (HtmlNode htmlNode in channelNode.ChildNodes)
            {
                switch (htmlNode.Name)
                {
                case "title":
                    t = true;
                    break;

                case "link":
                    l = true;
                    break;

                case "description":
                    d = true;
                    break;

                case "language":
                    la = true;
                    break;
                }
            }

            if (t)
            {
                RssChanel.Title = channelNode.ChildNodes["title"].InnerText;
            }
            if (l)
            {
                RssChanel.Link = channelNode.ChildNodes["link"].InnerText;
            }
            if (d)
            {
                RssChanel.Description = channelNode.ChildNodes["description"].InnerText;
            }
            if (la)
            {
                RssChanel.Language = channelNode.ChildNodes["language"].InnerText;
            }

            RssChanel.ItemList = new ObservableCollection <RssItem>();
            var itemNodes = channelNode.Descendants("item");

            foreach (HtmlNode itemNode in itemNodes)
            {
                bool it = false;
                bool il = false;
                bool id = false;
                bool ip = false;

                foreach (HtmlNode childNode in itemNode.ChildNodes)
                {
                    switch (childNode.Name)
                    {
                    case "title":
                        it = true;
                        break;

                    case "link":
                        il = true;
                        break;

                    case "description":
                        id = true;
                        break;

                    case "pubDate":
                        ip = true;
                        break;
                    }
                }

                RssItem i = new RssItem();
                if (id)
                {
                    i.Description = ExtractDescription(itemNode.ChildNodes["description"].InnerText);
                }
                if (il)
                {
                    i.Link = itemNode.ChildNodes["link"].NextSibling.InnerText;
                }
                if (string.IsNullOrEmpty(i.Link))
                {
                    i.Link = itemNode.ChildNodes["link"].InnerText;
                }
                if (ip)
                {
                    i.Time = itemNode.ChildNodes["pubDate"].InnerText;
                }
                if (it)
                {
                    i.Title = "» " + itemNode.ChildNodes["title"].InnerText;
                }

                RssChanel.ItemList.Add(i);
            }
        }
Пример #33
0
        private void RenderFeed()
        {
            if (siteSettings == null)
            {
                return;
            }
            Argotic.Syndication.RssFeed feed = new Argotic.Syndication.RssFeed();
            RssChannel channel = new RssChannel();

            channel.Generator = "mojoPortal CMS Recent Content Feed Geenrator";
            feed.Channel      = channel;

            List <IndexItem> recentContent = GetData(); // gets the data and initilizes the channel params

            if (!shouldRender)
            {
                WebUtils.SetupRedirect(this, redirectUrl);
                return;
            }

            if (channelTitle.Length == 0)
            {
                channelTitle = "Recent Content";
            }                                                                  //empty string will cause an error
            channel.Title = channelTitle;
            channel.Link  = new System.Uri(channelLink);
            if (channelDescription.Length == 0)
            {
                channelDescription = "Recent Content";
            }                                                                              //empty string will cause an error
            channel.Description    = channelDescription;
            channel.Copyright      = channelCopyright;
            channel.ManagingEditor = channelManagingEditor;
            channel.TimeToLive     = channelTimeToLive;

            int itemsAdded = 0;


            if (recentContent != null)
            {
                foreach (IndexItem indexItem in recentContent)
                {
                    RssItem item    = new RssItem();
                    string  itemUrl = BuildUrl(indexItem);
                    item.Link            = new Uri(itemUrl);
                    item.Guid            = new RssGuid(itemUrl);
                    item.Title           = FormatLinkText(indexItem);
                    item.PublicationDate = indexItem.LastModUtc;
                    item.Author          = indexItem.Author;
                    item.Description     = indexItem.ContentAbstract;
                    channel.AddItem(item);
                    itemsAdded += 1;
                }
            }

            if (itemsAdded == 0)
            {
                //channel must have at least one item
                RssItem item = new RssItem();
                item.Link  = new Uri(siteRoot);
                item.Title = "Stay tuned for future updates. ";
                //item.Description =
                item.PublicationDate = DateTime.UtcNow;

                channel.AddItem(item);
            }

            // no cache locally
            if (Request.Url.AbsolutePath.Contains("localhost"))
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(-30));
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
            else
            {
                Response.Cache.SetExpires(DateTime.Now.AddMinutes(feedCacheTimeInMinutes));
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.VaryByParams["f;gc;n;pageid;mid"] = true;
            }


            Response.ContentType = "application/xml";

            Encoding encoding = new UTF8Encoding();

            Response.ContentEncoding = encoding;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(Response.OutputStream, encoding))
            {
                xmlTextWriter.Formatting = Formatting.Indented;

                //////////////////
                // style for RSS Feed viewed in browsers
                if (ConfigurationManager.AppSettings["RSSCSS"] != null)
                {
                    string rssCss = ConfigurationManager.AppSettings["RSSCSS"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/css\" href=\"" + cssBaseUrl + rssCss + "\" ?>");
                }

                if (ConfigurationManager.AppSettings["RSSXsl"] != null)
                {
                    string rssXsl = ConfigurationManager.AppSettings["RSSXsl"].ToString();
                    xmlTextWriter.WriteWhitespace(" ");
                    xmlTextWriter.WriteRaw("<?xml-stylesheet type=\"text/xsl\" href=\"" + cssBaseUrl + rssXsl + "\" ?>");
                }
                ///////////////////////////

                feed.Save(xmlTextWriter);
            }
        }
Пример #34
0
        public async Task <RssChannel> GetChannel(CancellationToken cancellationToken = default(CancellationToken))
        {
            var project = await projectService.GetCurrentProjectSettings();

            if (project == null)
            {
                return(null);
            }
            var posts = await blogService.GetRecentPosts(maxFeedItems);

            if (posts == null)
            {
                return(null);
            }

            var channel = new RssChannel();

            channel.Title = project.Title;
            if (!string.IsNullOrEmpty(project.Description))
            {
                channel.Description = project.Description;
            }
            else
            {
                // prevent error, channel desc cannot be empty
                channel.Description = "Welcome to my blog";
            }

            channel.Copyright = project.CopyrightNotice;
            if (!string.IsNullOrEmpty(project.ChannelCategoriesCsv))
            {
                var channelCats = project.ChannelCategoriesCsv.Split(',');
                foreach (var cat in channelCats)
                {
                    channel.Categories.Add(new RssCategory(cat));
                }
            }

            channel.Generator     = Name;
            channel.RemoteFeedUrl = project.RemoteFeedUrl;
            channel.RemoteFeedProcessorUseAgentFragment = project.RemoteFeedProcessorUseAgentFragment;


            var urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccesor.ActionContext);

            if (project.Image.Length > 0)
            {
                channel.Image.Url = new Uri(urlHelper.Content(project.Image));
            }
            if (project.LanguageCode.Length > 0)
            {
                channel.Language = new CultureInfo(project.LanguageCode);
            }

            var baseUrl = string.Concat(
                contextAccessor.HttpContext.Request.Scheme,
                "://",
                contextAccessor.HttpContext.Request.Host.ToUriComponent()
                );

            // asp.net bug? the comments for this method say it returns an absolute fully qualified url but it returns relative
            // looking at latest code seems ok so maybe just a bug in rc1
            //https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/UrlHelperExtensions.cs
            //https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/Routing/UrlHelper.cs

            var indexUrl = urlHelper.RouteUrl(ProjectConstants.BlogIndexRouteName);

            if (indexUrl.StartsWith("/"))
            {
                indexUrl = string.Concat(baseUrl, indexUrl);
            }
            channel.Link = new Uri(indexUrl);
            if (project.ManagingEditorEmail.Length > 0)
            {
                channel.ManagingEditor = project.ManagingEditorEmail;
            }

            if (project.ChannelRating.Length > 0)
            {
                channel.Rating = project.ChannelRating;
            }


            var feedUrl = string.Concat(
                contextAccessor.HttpContext.Request.Scheme,
                "://",
                contextAccessor.HttpContext.Request.Host.ToUriComponent(),
                contextAccessor.HttpContext.Request.PathBase.ToUriComponent(),
                contextAccessor.HttpContext.Request.Path.ToUriComponent(),
                contextAccessor.HttpContext.Request.QueryString.ToUriComponent());

            channel.SelfLink = new Uri(feedUrl);
            //channel.TextInput =
            channel.TimeToLive = project.ChannelTimeToLive;
            if (project.WebmasterEmail.Length > 0)
            {
                channel.Webmaster = project.WebmasterEmail;
            }

            DateTime mostRecentPubDate = DateTime.MinValue;
            var      items             = new List <RssItem>();

            foreach (var post in posts)
            {
                if (post.PubDate > mostRecentPubDate)
                {
                    mostRecentPubDate = post.PubDate;
                }
                var rssItem = new RssItem();
                rssItem.Author = post.Author;

                if (post.Categories.Count > 0)
                {
                    foreach (var c in post.Categories)
                    {
                        rssItem.Categories.Add(new RssCategory(c));
                    }
                }


                //rssItem.Comments
                if (project.UseMetaDescriptionInFeed)
                {
                    rssItem.Description = post.MetaDescription;
                }
                else
                {
                    // change relative urls in content to absolute
                    rssItem.Description = htmlProcessor.ConvertUrlsToAbsolute(baseUrl, post.Content);
                }

                //rssItem.Enclosures

                var postUrl = await blogService.ResolvePostUrl(post);

                if (string.IsNullOrEmpty(postUrl))
                {
                    //TODO: log
                    continue;
                }


                if (postUrl.StartsWith("/"))
                {
                    //postUrl = urlHelper.Content(postUrl);
                    postUrl = string.Concat(
                        contextAccessor.HttpContext.Request.Scheme,
                        "://",
                        contextAccessor.HttpContext.Request.Host.ToUriComponent(),
                        postUrl);
                }

                rssItem.Guid            = new RssGuid(postUrl, true);
                rssItem.Link            = new Uri(postUrl);
                rssItem.PublicationDate = post.PubDate;
                //rssItem.Source
                rssItem.Title = post.Title;

                items.Add(rssItem);
            }

            channel.PublicationDate = mostRecentPubDate;
            channel.Items           = items;

            return(channel);
        }
Пример #35
0
 /// <summary>Writes an RSS channel</summary>
 /// <exception cref="InvalidOperationException">RssWriter has been closed, and can not be written to.</exception>
 /// <exception cref="ArgumentNullException">Channel must be instanciated with data, before calling Write.</exception>
 /// <param name="channel">RSS channel to write</param>
 public void Write(RssChannel channel)
 {
     writeChannel(channel);
 }
Пример #36
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);
        }
Пример #37
0
 /// <summary>
 ///     Writes an RSS channel
 /// </summary>
 /// <exception cref="InvalidOperationException">RssWriter has been closed, and can not be written to.</exception>
 /// <exception cref="ArgumentNullException">Channel must be instanciated with data, before calling Write.</exception>
 /// <param name="channel"> RSS channel to write </param>
 public void Write(RssChannel.RssChannel channel)
 {
     this.writeChannel(channel);
 }
Пример #38
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);
        }
Пример #39
0
 /// <summary>Closes connection to file.</summary>
 /// <remarks>This method also releases any resources held while reading.</remarks>
 public void Close()
 {
     textInput = null;
     image = null;
     cloud = null;
     channel = null;
     source = null;
     enclosure = null;
     category = null;
     item = null;
     if (reader != null)
     {
         reader.Close();
         reader = null;
     }
     elementText = null;
     xmlNodeStack = null;
 }
Пример #40
0
        public void ProcessRequest(HttpContext context)
        {
            string pagePath = "";

            if (context.Request.QueryString["p"] != null)
            {
                pagePath = context.Request.QueryString["p"];
            }
            CmsLanguage pageLang = CmsConfig.Languages[0];

            if (CmsConfig.Languages.Length > 1 && context.Request.QueryString["l"] != null)
            {
                string      langCode = context.Request.QueryString["l"];
                CmsLanguage testLang = CmsLanguage.GetFromHaystack(langCode, CmsConfig.Languages);
                if (!testLang.isInvalidLanguage)
                {
                    pageLang = testLang;
                }
            }

            CmsPage pageToRenderRSSFor = CmsContext.getPageByPath(pagePath, pageLang);

            if (pageToRenderRSSFor.Id < 0 || !pageToRenderRSSFor.currentUserCanRead)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Error: CMS page not found");
                context.Response.Flush();
                context.Response.End();
            }
            else
            {
                // -- generate the RssFeed
                RssFeed rssFeed = new RssFeed(System.Text.UTF8Encoding.UTF8);
                rssFeed.Version = RssVersion.RSS20;


                // -- setup the RSS channel
                string titlePrefix  = CmsConfig.getConfigValue("pageTitlePrefix", "");
                string titlePostfix = CmsConfig.getConfigValue("pageTitlePostfix", "");

                string     rssTitle       = titlePrefix + pageToRenderRSSFor.getTitle(pageLang) + titlePostfix;
                string     rssDescription = pageToRenderRSSFor.getSearchEngineDescription(pageLang);
                Uri        rssLink        = new Uri(pageToRenderRSSFor.getUrl(CmsUrlFormat.FullIncludingProtocolAndDomainName, pageLang), UriKind.RelativeOrAbsolute);
                RssChannel rssChannel     = new RssChannel(rssTitle, rssDescription, rssLink);
                rssChannel.Generator = "HatCMS: https://code.google.com/p/hatcms/";

                // -- call "GetRssFeedItems()" for each placeholder.
                CmsPlaceholderDefinition[] phDefs = pageToRenderRSSFor.getAllPlaceholderDefinitions();

                foreach (CmsPlaceholderDefinition phDef in phDefs)
                {
                    RssItem[] items = Placeholders.PlaceholderUtils.GetRssFeedItems(phDef.PlaceholderType, pageToRenderRSSFor, phDef, pageLang);
                    foreach (RssItem item in items)
                    {
                        rssChannel.Items.Add(item);
                    }
                }

                rssFeed.Channels.Add(rssChannel);

                context.Response.ContentType = "application/rss+xml";
                rssFeed.Write(context.Response.OutputStream);
                context.Response.Flush();
                context.Response.End();
            }
        }