Exemplo n.º 1
0
        public bool AddEnclosure(SyndicationItem item, IFile file, string fileUrl)
        {
            Guard.NotNull(item, nameof(item));
            Guard.NotNull(file, nameof(file));

            if (file != null && fileUrl.HasValue())
            {
                // We do not have the size behind fileUrl but the original file size should be fine.
                long fileLength = file.Length;
                if (fileLength <= 0)
                {
                    // 0 omits the length attribute but that invalidates the feed!
                    fileLength = 10000;
                }

                var enclosure = SyndicationLink.CreateMediaEnclosureLink(
                    new Uri(fileUrl),
                    MimeTypes.MapNameToMimeType(file.Name).EmptyNull(),
                    fileLength);

                item.Links.Add(enclosure);

                return(true);
            }

            return(false);
        }
Exemplo n.º 2
0
        IEnumerable <SyndicationItem> GetItems(Feed feedDefinition)
        {
            var count = 0;

            foreach (var file in feedDefinition.Files)
            {
                var shortFile = file.FullName.Replace(feedDefinition.Folder, "").Replace('\\', '/');

                var item  = new SyndicationItem();
                var title = file.Name.Substring(0, file.Name.Length - file.Extension.Length);
                item.Title       = new TextSyndicationContent(title);
                item.PublishDate = file.CreationTime;
                item.Id          = title;
                item.Summary     = new TextSyndicationContent(title);
                item.Categories.Add(new SyndicationCategory("Talk Radio"));

                var uri    = new Uri(Constants.RootURL + "file/" + feedDefinition.ID + "/" + count + "/" + file.Name);
                var length = file.Length;
                var type   = GetContentType(file.FullName);

                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(uri, type, length));
                count++;
                yield return(item);
            }
        }
Exemplo n.º 3
0
        public static SyndicationFeed GetSyndycationHelper()
        {
            //Uri uri = new Uri("http://localhost/WebApplication1/");
            SyndicationFeed syndicationFeed = new SyndicationFeed(
                "AAA ラジオ",
                "",
                //uri,
                null,
                "",
                DateTime.Now);
            List <SyndicationItem> items     = new List <SyndicationItem>();
            List <Blog>            oBlogList = Blog.GetMyBlogList();

            foreach (Blog oBlog in oBlogList)
            {
                SyndicationItem oItem = new SyndicationItem(
                    oBlog.Title,
                    SyndicationContent.CreateHtmlContent(oBlog.Description),
                    new Uri(oBlog.Url),
                    oBlog.BlogId.ToString(),
                    oBlog.LastUpdated);
                SyndicationLink syndicationLink =
                    SyndicationLink.CreateMediaEnclosureLink(new Uri(oBlog.Url), "audio/mpeg", 0);
                oItem.Links.Add(syndicationLink);
                items.Add(oItem);
            }
            syndicationFeed.Items = items;
            return(syndicationFeed);
        }
Exemplo n.º 4
0
        public void CreateMediaEnclosureLink()
        {
            SyndicationLink link = SyndicationLink.CreateMediaEnclosureLink(null, null, 1);

            Assert.IsNull(link.Uri, "#1");
            Assert.IsNull(link.MediaType, "#2");
            Assert.AreEqual(1, link.Length, "#3");
            Assert.AreEqual("enclosure", link.RelationshipType, "#4");
        }
        protected void ConfigureMediaEntry(string collection, SyndicationItem entry, string id, string contentType, out Uri location)
        {
            location = GetMediaItemUri(collection, id);
            Uri mediaUri = GetMediaItemUri(collection, id);

            entry.Content = new UrlSyndicationContent(mediaUri, contentType);
            entry.Links.Add(CreateEditMediaLink(collection, id, contentType));
            //entry.Links.Add(CreateEditLink(collection, id));
            entry.Links.Add(SyndicationLink.CreateMediaEnclosureLink(mediaUri, contentType, 0));
        }
        public void CreateMediaEnclosureLink_Invoke_ReturnsExpected(Uri uri, string mediaType, long length)
        {
            SyndicationLink link = SyndicationLink.CreateMediaEnclosureLink(uri, mediaType, length);

            Assert.Empty(link.AttributeExtensions);
            Assert.Null(link.BaseUri);
            Assert.Empty(link.ElementExtensions);
            Assert.Equal(length, link.Length);
            Assert.Equal(mediaType, link.MediaType);
            Assert.Equal("enclosure", link.RelationshipType);
            Assert.Null(link.Title);
            Assert.Same(uri, link.Uri);
        }
        /// <summary>
        /// Gets the collection of <see cref="SyndicationItem"/>'s that represent the atom entries.
        /// </summary>
        /// <returns>A collection of <see cref="SyndicationItem"/>'s.</returns>
        private List <SyndicationItem> GetItems()
        {
            List <SyndicationItem> items = new List <SyndicationItem>();

            for (int i = 1; i < 4; ++i)
            {
                SyndicationItem item = new SyndicationItem()
                {
                    // id (Required) - Identifies the entry using a universally unique and permanent URI. Two entries in a feed can have the same value for id if they represent the same entry at different points in time.
                    Id = FeedId + i,
                    // title (Required) - Contains a human readable title for the entry. This value should not be blank.
                    Title = SyndicationContent.CreatePlaintextContent("Item " + i),
                    // description (Reccomended) - A summary of the entry.
                    Summary = SyndicationContent.CreatePlaintextContent("A summary of item " + i),
                    // updated (Optional) - Indicates the last time the entry was modified in a significant way. This value need not change after a typo is fixed, only after a substantial modification. Generally, different entries in a feed will have different updated timestamps.
                    LastUpdatedTime = DateTimeOffset.Now,
                    // published (Optional) - Contains the time of the initial creation or first availability of the entry.
                    PublishDate = DateTimeOffset.Now,
                    // rights (Optional) - Conveys information about rights, e.g. copyrights, held in and over the entry.
                    Copyright = new TextSyndicationContent(string.Format("© {0} - {0}", DateTime.Now.Year, Application.Name)),
                };

                // link (Reccomended) - Identifies a related Web page. An entry must contain an alternate link if there is no content element.
                item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex)), ContentType.Html));
                // AND/OR
                // Text content  (Optional) - Contains or links to the complete content of the entry. Content must be provided if there is no alternate link.
                // item.Content = SyndicationContent.CreatePlaintextContent("The actual plain text content of the entry");
                // HTML content (Optional) - Content can be plain text or HTML. Here is a HTML example.
                // item.Content = SyndicationContent.CreateHtmlContent("The actual HTML content of the entry");

                // author (Optional) - Names one author of the entry. An entry may have multiple authors. An entry must contain at least one author element unless there is an author element in the enclosing feed, or there is an author element in the enclosed source element.
                item.Authors.Add(this.GetPerson());

                // contributor (Optional) - Names one contributor to the entry. An entry may have multiple contributor elements.
                item.Contributors.Add(this.GetPerson());

                // category (Optional) - Specifies a category that the entry belongs to. A entry may have multiple category elements.
                item.Categories.Add(new SyndicationCategory("CategoryName"));

                // link - Add additional links to related images, audio or video like so.
                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(new Uri(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png")), ContentType.Png, 0));

                // media:thumbnail - Add a Yahoo Media thumbnail for the entry. See http://www.rssboard.org/media-rss for more information.
                item.SetThumbnail(this.urlHelper.AbsoluteContent("~/content/icons/atom-icon-48x48.png"), 48, 48);

                items.Add(item);
            }

            return(items);
        }
Exemplo n.º 8
0
        AtomItem CreateItemFromLink(string key, Uri url, bool withOrbits)
        {
            string identifier = key.Replace(".EOF", "");
            Match  match      = Regex.Match(identifier,
                                            @"^(?'mission'\w{3})_OPER_AUX_(?'type'\w{6})_(?'system'\w{4})_(?'proddate'\w{15})_V(?'startdate'\w{15})_(?'stopdate'\w{15})$");

            if (!match.Success)
            {
                return(null);
            }

            AtomItem item = new AtomItem(identifier, string.Format("{0} {1} {2} {3}", match.Groups["mission"].Value,
                                                                   match.Groups["type"].Value,
                                                                   match.Groups["startdate"].Value,
                                                                   match.Groups["stopdate"].Value),
                                         url,
                                         identifier,
                                         DateTimeOffset.ParseExact(match.Groups["proddate"].Value, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime());

            DateTime start = DateTime.ParseExact(match.Groups["startdate"].Value, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            DateTime stop  = DateTime.ParseExact(match.Groups["stopdate"].Value, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();

            item.Identifier  = identifier;
            item.PublishDate = DateTimeOffset.ParseExact(match.Groups["proddate"].Value, "yyyyMMddTHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(url, "application/xml", 0));
            item.ElementExtensions.Add("polygon", "http://www.georss.org/georss", "-90 -180 -90 180 90 180 90 -180 -90 -180");
            item.ElementExtensions.Add("date", "http://purl.org/dc/elements/1.1/", string.Format("{0}/{1}", start.ToString("O"), stop.ToString("O")));

            Terradue.ServiceModel.Ogc.Eop21.EarthObservationType eo = OrbToEo(identifier, match.Groups["mission"].Value, match.Groups["type"].Value, start, stop, item.PublishDate);
            if (eo != null)
            {
                log.DebugFormat("EOP extension created from {0}", url);
                item.ElementExtensions.Add(eo.CreateReader());
            }

            if (withOrbits)
            {
                var request = HttpWebRequest.Create(url);

                using (var response = request.GetResponse())
                {
                    Terradue.OpenSearch.Sentinel.Data.Earth_Explorer_File eefile = (Terradue.OpenSearch.Sentinel.Data.Earth_Explorer_File)eeser.Deserialize(response.GetResponseStream());
                    item.ElementExtensions.Add(GenerateOrbitsExtension(eefile));
                }
            }

            return(item);
        }
        public bool AddEnclosue(SyndicationItem item, Picture picture, string pictureUrl)
        {
            if (picture != null && pictureUrl.HasValue())
            {
                long pictureLength = 10000;                             // 0 omits the length attribute but that invalidates the feed

                if (picture.PictureBinary != null)
                {
                    pictureLength = picture.PictureBinary.LongLength;
                }

                var enclosure = SyndicationLink.CreateMediaEnclosureLink(new Uri(pictureUrl), picture.MimeType.EmptyNull(), pictureLength);

                item.Links.Add(enclosure);

                return(true);
            }
            return(false);
        }
Exemplo n.º 10
0
        public bool AddEnclosue(SyndicationItem item, Picture picture, string pictureUrl)
        {
            if (picture != null && pictureUrl.HasValue())
            {
                // 0 omits the length attribute but that invalidates the feed
                long pictureLength = 10000;

                if ((picture.MediaStorageId ?? 0) != 0)
                {
                    // do not care about storage provider
                    pictureLength = picture.MediaStorage.Data.LongLength;
                }

                var enclosure = SyndicationLink.CreateMediaEnclosureLink(new Uri(pictureUrl), picture.MimeType.EmptyNull(), pictureLength);

                item.Links.Add(enclosure);

                return(true);
            }
            return(false);
        }
Exemplo n.º 11
0
 public static void Snippet6()
 {
     // <Snippet6>
     SyndicationLink link = SyndicationLink.CreateMediaEnclosureLink(new Uri("http://server/link"), "audio/mpeg", 100000);
     // </Snippet6>
 }
Exemplo n.º 12
0
        private SyndicationItem GetSyndicationItem(Store store, Product product, ProductCategory productCategory, int description, int isDetailLink)
        {
            if (productCategory == null)
            {
                return(null);
            }

            if (description == 0)
            {
                description = 300;
            }

            var    productDetailLink = LinkHelper.GetProductLink(product, productCategory.Name);
            String detailPage        = String.Format("http://{0}{1}", store.Domain.ToLower(), productDetailLink);

            if (isDetailLink == 1)
            {
                detailPage = String.Format("http://{0}{1}", store.Domain.ToLower(), "/products/productbuy/" + product.Id);
            }
            string desc = "";

            if (description > 0)
            {
                desc = GeneralHelper.GeneralHelper.GetDescription(product.Description, description);
            }
            var uri = new Uri(detailPage);
            var si  = new SyndicationItem(product.Name, desc, uri);

            if (product.UpdatedDate != null)
            {
                si.PublishDate = product.UpdatedDate.Value.ToUniversalTime();
            }


            if (!String.IsNullOrEmpty(productCategory.Name))
            {
                si.ElementExtensions.Add("products:category", String.Empty, productCategory.Name);
            }
            si.ElementExtensions.Add("guid", String.Empty, uri);



            if (product.ProductFiles.Any())
            {
                List <BaseFileEntity> baseFileEntities = product.ProductFiles != null && product.ProductFiles.Any() ? product.ProductFiles.Cast <BaseFileEntity>().ToList() : new List <BaseFileEntity>();
                var imageLiquid = new ImageLiquid(baseFileEntities, this.ImageWidth, this.ImageHeight);
                imageLiquid.ImageState = true;
                String imageSrcHtml = String.Format("http://{0}{1}", store.Domain.ToLower(), imageLiquid.SmallImageSource);
                try
                {
                    SyndicationLink imageLink =
                        SyndicationLink.CreateMediaEnclosureLink(new Uri(imageSrcHtml), "image/jpeg", 100);
                    si.Links.Add(imageLink);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "GetSyndicationItem");
                }
            }

            return(si);
        }
Exemplo n.º 13
0
        private void UpdateSyndicationFeed()
        {
            //See if feed is already in the cache
            List <SyndicationItem> items = Cache["AudiosFeed"] as List <SyndicationItem>;

            if (items == null)
            {
                var container = client.GetContainerReference(companyName.ToLower());
                var blob      = container.GetBlockBlobReference("audios/" + "audio.rss");
                using (MemoryStream ms = new MemoryStream())
                {
                    blob.DownloadToStream(ms);
                    StreamReader reader = new StreamReader(ms);
                    if (reader != null)
                    {
                        reader.BaseStream.Position = 0;
                    }
                    SyndicationFeed audiosList = SyndicationFeed.Load(XmlReader.Create(ms));
                    items = audiosList.Items.ToList <SyndicationItem>();
                    //Custom Tags
                    string           prefix   = "itunes";
                    XmlQualifiedName nam      = new XmlQualifiedName(prefix, "http://www.w3.org/2000/xmlns/");
                    XNamespace       itunesNs = "http://www.itunes.com/dtds/podcast-1.0.dtd";
                    audiosList.AttributeExtensions.Add(nam, itunesNs.NamespaceName);
                    SyndicationItem item = new SyndicationItem();


                    //Create syndication Item
                    item.Title       = TextSyndicationContent.CreatePlaintextContent(name.Text);
                    item.PublishDate = DateTimeOffset.Now;
                    item.Links.Add(SyndicationLink.CreateAlternateLink(uri));
                    item.ElementExtensions.Add(new SyndicationElementExtension("author", itunesNs.NamespaceName, name.Text));
                    item.ElementExtensions.Add(new SyndicationElementExtension("explicit", itunesNs.NamespaceName, "no"));
                    item.ElementExtensions.Add(new SyndicationElementExtension("summary", itunesNs.NamespaceName, description.Text));
                    item.ElementExtensions.Add(new SyndicationElementExtension("subtitle", itunesNs.NamespaceName, subtitle.Text));
                    item.ElementExtensions.Add(
                        new XElement(itunesNs + "image", new XAttribute("href", uri2.ToString())));
                    item.ElementExtensions.Add(new SyndicationElementExtension("Size", null, upload_file.PostedFile.ContentLength / 1000000));

                    item.Summary = TextSyndicationContent.CreatePlaintextContent(description.Text);
                    item.Categories.Add(new SyndicationCategory(category.Text));
                    SyndicationLink enclosure = SyndicationLink.CreateMediaEnclosureLink(uri, "audio/mpeg", upload_file.PostedFile.ContentLength);
                    item.ElementExtensions.Add(new SyndicationElementExtension("subtitle", itunesNs.NamespaceName, subtitle.Text));
                    item.Links.Add(enclosure);

                    //create author Info
                    SyndicationPerson authInfo = new SyndicationPerson();
                    authInfo.Name = authorName.Text;
                    item.Authors.Add(authInfo);
                    items.Add(item);

                    //recreate Feed
                    audiosList.Items = items;
                    blob.Delete();

                    MemoryStream       ms1          = new MemoryStream();
                    XmlWriter          feedWriter   = XmlWriter.Create(ms1);
                    Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(audiosList);
                    rssFormatter.WriteTo(feedWriter);
                    feedWriter.Close();

                    blob.UploadFromByteArray(ms1.ToArray(), 0, ms1.ToArray().Length);
                    ms1.Close();
                }
                Cache.Insert("AudiosFeed",
                             items,
                             null,
                             DateTime.Now.AddHours(1.0),
                             TimeSpan.Zero);
            }
        }
Exemplo n.º 14
0
        private SyndicationItem GetSyndicationItem(Store store, Content product, Category category, int description, String type)
        {
            if (category == null)
            {
                return(null);
            }

            if (description == 0)
            {
                description = 300;
            }

            var    productDetailLink = LinkHelper.GetContentLink(product, category.Name, type);
            String detailPage        = String.Format("http://{0}{1}", store.Domain.ToLower(), productDetailLink);

            string desc = "";

            if (description > 0)
            {
                desc = GeneralHelper.GetDescription(product.Description, description);
            }
            var uri = new Uri(detailPage);
            var si  = new SyndicationItem(product.Name, desc, uri);

            si.ElementExtensions.Add("guid", String.Empty, uri);
            if (product.UpdatedDate != null)
            {
                si.PublishDate = product.UpdatedDate.Value.ToUniversalTime();
            }


            if (!String.IsNullOrEmpty(category.Name))
            {
                si.ElementExtensions.Add(type + ":category", String.Empty, category.Name);
            }



            if (product.ContentFiles.Any())
            {
                var mainImage = product.ContentFiles.FirstOrDefault(r => r.IsMainImage);
                if (mainImage == null)
                {
                    mainImage = product.ContentFiles.FirstOrDefault();
                }

                if (mainImage != null)
                {
                    string imageSrc = LinkHelper.GetImageLink("Thumbnail", mainImage.FileManager, this.ImageWidth, this.ImageHeight);
                    if (!string.IsNullOrEmpty(imageSrc))
                    {
                        try
                        {
                            SyndicationLink imageLink =
                                SyndicationLink.CreateMediaEnclosureLink(new Uri(imageSrc), "image/jpeg", 100);
                            si.Links.Add(imageLink);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }

            return(si);
        }
Exemplo n.º 15
0
 public void CreateMediaEnclosureLink_NegativeLength_ThrowsArgumentOutOfRangeException()
 {
     AssertExtensions.Throws <ArgumentOutOfRangeException>("length", () => SyndicationLink.CreateMediaEnclosureLink(null, null, -1));
 }
Exemplo n.º 16
0
        public FileResult Index(string path, bool recursive = false, string title = null)
        {
            path = ValidatePath(path);

            var baseDirInfo = new DirectoryInfo(path);

            var feed = new SyndicationFeed(
                title ?? baseDirInfo.Name,
                $"{(recursive ? "Recursive " : "")}Filefeed generated feed for {baseDirInfo.FullName}",
                new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}")
                );

            var folderImage = baseDirInfo.GetFiles("folder.*").FirstOrDefault();

            if (folderImage != null)
            {
                feed.ImageUrl = new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}" + Url.Action("GetFile", new { Path = folderImage.FullName }));
            }

            var files = baseDirInfo.EnumerateFiles(
                "*",
                new EnumerationOptions {
                RecurseSubdirectories = recursive
            })
                        .Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden) && !x.Name.ToLower().StartsWith("folder."))
                        .Take(100)
                        .OrderBy(x => x.FullName);

            var items = new List <SyndicationItem>(files.Count());

            //We fake the date to get a publish date in the same order as alphabetical
            var pubDate = new DateTime(DateTime.Now.Year - 1, 1, 1, 12, 0, 0);

            foreach (var file in files)
            {
                if (!_contentTypeProvider.TryGetContentType(file.Name, out var type))
                {
                    type = System.Net.Mime.MediaTypeNames.Application.Octet;
                }

                var item = new SyndicationItem
                {
                    Title       = new TextSyndicationContent(file.Name),
                    Id          = Url.Action("GetFile", new { Path = file.FullName }),
                    PublishDate = pubDate,
                };
                item.Links.Add(SyndicationLink.CreateMediaEnclosureLink(
                                   new Uri($"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}" + Url.Action("GetFile", new { Path = file.FullName })),
                                   type,
                                   file.Length));
                pubDate = pubDate.AddDays(1);

                items.Add(item);
            }
            feed.Items = items;

            var settings = new XmlWriterSettings
            {
                Encoding            = System.Text.Encoding.UTF8,
                NewLineHandling     = NewLineHandling.Entitize,
                NewLineOnAttributes = true,
                Indent = true
            };

            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);

            rssFormatter.SerializeExtensionsAsAtom = false;
            using (var stream = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(stream, settings))
                {
                    rssFormatter.WriteTo(writer);
                    writer.Flush();
                    return(File(stream.ToArray(), "application/rss+xml; charset=utf-8"));
                }
            }
        }