public static string GetConcatenatedCategoryString(MediaCategories categories) { if (categories.Count == 0) { return(""); } string result = categories[0].Name; for (int index = 1; index < categories.Count - 1; index++) { result += ", " + categories[index].Name; } if (categories.Count > 1) { //TODO: Translate "och" result += " och " + categories[categories.Count - 1].Name; } return(result); }
public ICollection <Guid> GetMetadataExtractorsForCategory(string mediaCategory) { ICollection <Guid> ids = new HashSet <Guid>(); MediaCategory category; if (!MediaCategories.TryGetValue(mediaCategory, out category)) { return(ids); } ICollection <MediaCategory> categoriesToConsider = GetAllMediaCategoriesInHierarchy(category); foreach (KeyValuePair <Guid, IMetadataExtractor> localMetadataExtractor in LocalMetadataExtractors) { if (mediaCategory == null || localMetadataExtractor.Value.Metadata.MediaCategories.Intersect(categoriesToConsider).Any()) { ids.Add(localMetadataExtractor.Value.Metadata.MetadataExtractorId); } } return(ids); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Reporters reporters = Reporters.GetAll(); reporters.Sort(); this.GridReporters.DataSource = reporters; MediaCategories categories = MediaCategories.GetAll(); foreach (MediaCategory category in categories) { this.CheckListCategories.Items.Add(new ListItem(category.Name, category.Identity.ToString())); } } this.GridReporters.Columns.FindByUniqueNameSafe("DeleteCommand").Visible = _authority.HasAnyPermission(Permission.CanHandlePress); this.ButtonAdd.Enabled = _authority.HasAnyPermission(Permission.CanHandlePress); }
private static string GetConcatenatedCategoryString (MediaCategories categories) { string result = categories[0].Name; for (int index = 1; index < categories.Count - 1; index++) { result += ", " + categories[index].Name; } if (categories.Count > 1) { result += " och " + categories[categories.Count - 1].Name; } return result; }
private static void CheckOneFeed(string readerUrl, string persistAsKey, int orgIdForTemplate) { string persistenceKey = String.Format("Pressrelease-Highwater-{0}", persistAsKey); DateTime highWaterMark = DateTime.MinValue; RssReader reader = null; try { string highWaterMarkString = Persistence.Key[persistenceKey]; if (string.IsNullOrEmpty(highWaterMarkString)) { //Initialize highwatermark if never used highWaterMark = DateTime.Now; Persistence.Key[persistenceKey] = DateTime.Now.ToString(); } else { try { highWaterMark = DateTime.Parse(highWaterMarkString); } catch (Exception ex) { HeartBeater.Instance.SuggestRestart(); throw new Exception( "Triggered restart. Unable to read/parse old highwater mark from database in PressReleaseChecker.Run(), from key:" + persistenceKey + ", loaded string was '" + highWaterMarkString + "' expected format is " + DateTime.Now, ex); } } DateTime storedHighWaterMark = highWaterMark; reader = new RssReader(readerUrl); Rss rss = reader.Read(); foreach (RssChannelItem item in rss.Channel.Items) { // Ignore any items older than the highwater mark. // Also ignore if older than two days if (item.PubDate < highWaterMark || item.PubDate < DateTime.Now.AddDays(-2)) { continue; } // This is an item we should publish. // Set highwater datetime mark. We do this first, BEFORE processing, as a defense against mail floods, // if should something go wrong and unexpected exceptions happen. // We used to add 70 minutes as a defense against mistakes on DST switch in spring and fall (yes, it has happened), but have reduced to two. if (item.PubDate > storedHighWaterMark) { Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(2).ToString(); storedHighWaterMark = item.PubDate.AddMinutes(2); // Verify that it was written correctly to database. This is defensive programming to avoid a mail flood, // in case we can't write to the database for some reason. string newStoredHighWaterString = ""; try { newStoredHighWaterString = Persistence.Key[persistenceKey]; DateTime temp = DateTime.Parse(newStoredHighWaterString); } catch (Exception ex) { throw new Exception( "Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" + newStoredHighWaterString + "'", ex); } if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate) { throw new Exception( "Unable to commit new highwater mark to database in PressReleaseChecker.Run()"); } } bool allReporters = false; bool international = false; MediaCategories categories = new MediaCategories(); foreach (RssCategory category in item.Categories) { if (category.Name == "Alla") { allReporters = true; } else if (category.Name == "Uncategorized") { } else { try { MediaCategory mediaCategory = MediaCategory.FromName(category.Name); categories.Add(mediaCategory); if (category.Name.StartsWith("International")) { international = true; } } catch (Exception) { ExceptionMail.Send( new Exception("Unrecognized media category in press release: " + category.Name)); } } } string mailText = Blog2Mail(item.Content); // Create recipient list of relevant reporters Reporters reporters = null; if (allReporters) { reporters = Reporters.GetAll(); } else { reporters = Reporters.FromMediaCategories(categories); } // Add officers if not int'l People officers = new People(); Dictionary <int, bool> officerLookup = new Dictionary <int, bool>(); if (!international) { int[] officerIds = Roles.GetAllDownwardRoles(1, 1); foreach (int officerId in officerIds) { officerLookup[officerId] = true; } } else { officerLookup[1] = true; } // Send press release //TODO: hardcoded geo ... using World Organization org = Organization.FromIdentity(orgIdForTemplate); Geography geo = Geography.Root; PressReleaseMail pressreleasemail = new PressReleaseMail(); pressreleasemail.pSubject = item.Title; pressreleasemail.pDate = DateTime.Now; pressreleasemail.pBodyContent = Blog2Mail(item.Content); pressreleasemail.pOrgName = org.MailPrefixInherited; if (allReporters) { pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE } else if (international) { pressreleasemail.pPostedToCategories = "International/English"; // TODO: THIS IS HARDCODED } else { pressreleasemail.pPostedToCategories = PressReleaseMail.GetConcatenatedCategoryString(categories); } OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService, OutboundMail.PriorityHighest, org, geo); int recipientCount = 0; foreach (Reporter recipient in reporters) { if (!Formatting.ValidateEmailFormat(recipient.Email)) { continue; } ++recipientCount; newMail.AddRecipient(recipient); } foreach (int key in officerLookup.Keys) { Person recipient = Person.FromIdentity(key); if (!Formatting.ValidateEmailFormat(recipient.Mail)) { continue; } ++recipientCount; newMail.AddRecipient(recipient, true); } newMail.SetRecipientCount(recipientCount); newMail.SetResolved(); newMail.SetReadyForPickup(); } } catch (Exception ex) { ExceptionMail.Send( new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex)); } finally { reader.Close(); } }
public async Task <IActionResult> CreateAsync(MediaModel model, IFormFile file, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel)) { return(AccessDeniedView()); } try { if (model.Title == null) { return(RedirectToAction("Create")); } if (model.CategoryId == 0) { return(RedirectToAction("Create")); } #region FileUpload if (file == null || file.Length == 0) { return(RedirectToAction("Create")); } var Extention = Path.GetExtension(file.FileName); if (!Directory.Exists("wwwroot/Media/Company.Media/Media")) { Directory.CreateDirectory("wwwroot/Media/Company.Media/Media"); } var path = ""; if (System.IO.File.Exists("wwwroot/Media/Company.Media/Media/" + file.FileName)) { var Exist = true; int Count = 1; var StepCount = 0; while (Exist) { if (!System.IO.File.Exists("wwwroot/Media/Company.Media/Media/" + Count.ToString() + "_" + file.FileName)) { Exist = false; StepCount = Count; } Count++; } var Existpath = StepCount.ToString() + "_" + file.FileName; path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot/Media/Company.Media/Media", Existpath); } else { path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Media/Company.Media/Media", file.FileName); } using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } #endregion var Customer = EngineContext.Current.Resolve <IWorkContext>().CurrentCustomer; #region MediaTable var MediaModel = new Media.Domain.Media() { URL = $"/Media/Company.Media/Media/{file.FileName}", FileName = file.FileName, CreateDate = DateTime.Now, PublishDate = DateTime.Now, UpdateDate = DateTime.Now, ContentType = file.ContentType, MediaStatus = Media.Domain.Media.StatusType.Active, UserId = Customer.Id, Title = model.Title, AltText = model.Text, FileExtention = Extention }; _MediaService.InsertMedia(MediaModel); #endregion var parent = true; while (parent) { var Mediacategories = new MediaCategories() { MediaId = MediaModel.Id, MediaCategoryId = model.CategoryId }; _MediaCategoriesService.InsertMediaCategories(Mediacategories); var category = _MediaCategoryService.GetMediaCategoryById(model.CategoryId); if (category.MediaCategoryParentId != 0) { model.CategoryId = category.MediaCategoryParentId; } else { parent = false; } } ViewBag.RefreshPage = true; model.CategoryList = new System.Collections.Generic.List <SelectListItem>(); return(View("~/Plugins/Company.Media/Views/Media/Create.cshtml", model)); } catch (Exception exception) { ViewBag.RefreshPage = true; model.CategoryList = new System.Collections.Generic.List <SelectListItem>(); return(View("~/Plugins/Company.Media/Views/Media/Create.cshtml", model)); } }
public static void Send(string title, bool sendToAll, MediaCategories categories, string mailText, Reporters reporters) { string directory = "content" + Path.DirectorySeparatorChar + "pressreleasetemplate-1"; string htmlTemplate = "Failed to read HTML mail template."; using ( StreamReader reader = new StreamReader(directory + Path.DirectorySeparatorChar + "template.html", Encoding.GetEncoding(1252))) { htmlTemplate = reader.ReadToEnd(); } /* * using (StreamReader reader = new StreamReader(textTemplateFile, System.Text.Encoding.Default)) * { * textTemplate = reader.ReadToEnd(); * }*/ // PREPARE DATE // assume Swedish CultureInfo culture = new CultureInfo("sv-SE"); string date = DateTime.Today.ToString("d MMMM yyyy", culture); string time = DateTime.Now.ToString("HH:mm"); string categoriesSentTo = "Alla kategorier"; if (!sendToAll) { categoriesSentTo = GetConcatenatedCategoryString(categories); } // PREPARE HTML VIEW: // Write in the title, intro, and body htmlTemplate = htmlTemplate. Replace("%TITLE%", HttpUtility.HtmlEncode(title.ToUpper())). Replace("%title%", HttpUtility.HtmlEncode(title)). Replace("%date%", HttpUtility.HtmlEncode(date)). Replace("%DATE%", HttpUtility.HtmlEncode(date.ToUpper())). Replace("%time%", HttpUtility.HtmlEncode(time)). Replace("%postedtocategories%", HttpUtility.HtmlEncode(categoriesSentTo)); string body = mailText; body = body. Replace("<", "({[("). Replace(">", ")}])"). Replace("\"", "quotQUOTquot"); body = HttpUtility.HtmlEncode(body); body = body. Replace("({[(", "<"). Replace(")}])", ">"). Replace("quotQUOTquot", "\""). Replace("&#", "&#"); htmlTemplate = htmlTemplate.Replace("%body%", body); // Embed any inline images directly into the message string newsletterIdentifier = DateTime.Now.ToString("yyyyMMddhhMMssfff") + "@piratpartiet.se"; // TODO: Read the replacements from a config file htmlTemplate = htmlTemplate.Replace("header-pp-logo.png", "cid:pplogo" + newsletterIdentifier); /* * htmlTemplate = htmlTemplate.Replace("TopRight.png", "cid:topright" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("MiddleRight.png", "cid:middleright" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("BottomRight.png", "cid:bottomright" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("TopLeft.png", "cid:topleft" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("MiddleLeft.png", "cid:middleleft" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("BottomLeft.png", "cid:bottomleft" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("TopMiddle.png", "cid:topmiddle" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("BottomMiddle.png", "cid:bottommiddle" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("PPShield.png", "cid:ppshield" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("Rick.png", "cid:rick" + newsletterIdentifier); * htmlTemplate = htmlTemplate.Replace("RFe-signature.gif", "cid:rick-signature" + newsletterIdentifier);*/ // MemoryStream memStream = new MemoryStream(); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType( MediaTypeNames.Text.Html)); htmlView.TransferEncoding = TransferEncoding.Base64; /* * LinkedResource image = new LinkedResource(directory + Path.DirectorySeparatorChar + "header-pp-logo.png"); * image.ContentId = "pplogo" + newsletterIdentifier; * htmlView.LinkedResources.Add(image);*/ /* * -- DISABLED -- code writing a forum-style text file * * * // PREPARE FORUM FILE: * * string forumTemplate = textTemplate. * Replace("%TITLE%", "[h1]" + title.ToUpper() + "[/h1]"). * Replace("%title%", "[h1]" + title + "[/h1]"). * Replace("%intro%", intro). * Replace("%body%", mailBody); * * // Replace "<a href="http://link">Text</a>" with "Text (http://link)" * * Regex regexLinksForum = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline); * * forumTemplate = regexLinksForum.Replace(forumTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInForum)); * * using (StreamWriter writer = new StreamWriter(directory + "\\" + "forum.txt", false, System.Text.Encoding.Default)) * { * writer.WriteLine(forumTemplate); * }*/ /* * -- DISABLED -- no text view * * * * // PREPARE TEXT VIEW: * * // Write in the title, intro, and body * * textTemplate = textTemplate. * Replace("%TITLE%", title.ToUpper()). * Replace("%title%", title). * Replace("%intro%", intro). * Replace("%body%", mailBody); * * // Replace "<a href="http://link">Text</a>" with "Text (http://link)" * * Regex regexLinks = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline); * * textTemplate = regexLinks.Replace(textTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInText)); * * Regex regexHtmlCodes = new Regex("(?s)\\[[^\\[]+\\]", RegexOptions.Multiline); * * textTemplate = regexHtmlCodes.Replace(textTemplate, string.Empty); * * ContentType typeUnicode = new ContentType(MediaTypeNames.Text.Plain); * typeUnicode.CharSet = "utf-8"; * * AlternateView textUnicodeView = AlternateView.CreateAlternateViewFromString(textTemplate, typeUnicode); * * ContentType typeIsoLatin1 = new ContentType(MediaTypeNames.Text.Plain); * typeIsoLatin1.CharSet = "iso-8859-1"; * * AlternateView textHotmailView = new AlternateView(new MemoryStream(Encoding.Default.GetBytes(textTemplate)), typeIsoLatin1); * * */ foreach (Reporter reporter in reporters) { //Console.Write (recipient.Name + "(#" + recipient.Identity.ToString() + ")... "); try { SmtpClient client = new SmtpClient(Config.SmtpHost, Config.SmtpPort); client.Credentials = null; MailMessage message = new MailMessage( new MailAddress("*****@*****.**", "Piratpartiet Press"), new MailAddress(reporter.Email, reporter.Name, Encoding.UTF8)); message.Subject = "PP-Press: " + title; string individualBody = htmlTemplate; individualBody = individualBody. Replace("%reportername%", HttpUtility.HtmlEncode(reporter.Name)). Replace("%reporteremail%", HttpUtility.HtmlEncode(reporter.Email)). Replace("%reportercategories%", HttpUtility.HtmlEncode(GetConcatenatedCategoryString(reporter.MediaCategories))); message.Body = individualBody; message.BodyEncoding = Encoding.ASCII; message.IsBodyHtml = true; // COMPENSATE FOR MONO BUG -- put logo online instead of attached message.Body = message.Body.Replace("cid:pplogo" + newsletterIdentifier, "http://docs.piratpartiet.se/banners/newsletter-banner-pp-logo.png"); /* * Attachment attachment = new Attachment(directory + Path.DirectorySeparatorChar + "header-pp-logo.png", "image/png"); * attachment.ContentId = "pplogo" + newsletterIdentifier; * attachment.ContentDisposition.Inline = true; * message.Attachments.Add(attachment);*/ bool successOrPermanentFail = false; while (!successOrPermanentFail) { try { client.Send(message); successOrPermanentFail = true; } catch (SmtpException e) { if (!(e.ToString().StartsWith("System.Net.Mail.SmtpException: 4"))) { // This is NOT a temporary error (SMTP 4xx). Fail. successOrPermanentFail = true; throw e; } // Otherwise, sleep for a while and try again. Thread.Sleep(1000); } } //Console.WriteLine("ok"); //Console.WriteLine("ok"); } catch (Exception e) { //Console.WriteLine("FAIL! <" + recipient.Email + ">"); ExceptionMail.Send( new Exception("Error sending press release to " + reporter.Name + " <" + reporter.Email + ">:", e), true); } } }
internal static OutboundMailRecipient TransmitOneMail(OutboundMailRecipient recipient) { try { // If the mail address in illegal format, do not try to send anything: if (!Formatting.ValidateEmailFormat(recipient.EmailPerson.Email.Trim())) { string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + "], mail [" + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, null); } // If the mail address is marked as unreachable, do not try to send anything if (recipient.Person != null && recipient.Person.MailUnreachable) { string msg = "MailUnreachable email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + "], mail [" + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, null); } // If the mail address is marked as unreachable, do not try to send anything if (recipient.Person != null && recipient.Person.NeverMail) { string msg = "NeverMail email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + "], mail [" + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new IgnoreRecipientException(msg, null); } // Otherwise, let's start processing OutboundMail mail = recipient.OutboundMail; bool limitToLatin1 = false; bool limitToText = false; Encoding currentEncoding = Encoding.UTF8; string email = recipient.EmailPerson.Email.ToLower(); if (mail.MailType == 0 || mail.TemplateName.EndsWith("Plain")) { limitToText = true; } // TEST: Does this user require the use of a text-only message (as opposed to multipart/alternative)? if (recipient.Person != null && recipient.Person.LimitMailToText) { limitToText = true; } // This is supposedly not a problem anymore //if (email.EndsWith("@hotmail.com") || email.EndsWith("@msn.com")) //{ // limitToLatin1 = true; //} // TEST: Does this user require the limited use of the Latin-1 charset (as opposed to Unicode?) if (recipient.Person != null && recipient.Person.LimitMailToLatin1) { limitToLatin1 = true; } // Capability tests end here if (limitToLatin1) { currentEncoding = Encoding.GetEncoding("ISO-8859-1"); } else { currentEncoding = Encoding.UTF8; } QuotedPrintable qp = QuotedPrintableEncoder[currentEncoding]; MailMessage message = new MailMessage(); if (mail.AuthorType == MailAuthorType.Person) { try { message.From = new MailAddress(mail.Author.PartyEmail, qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"), currentEncoding); if (mail.Author.Identity == 1) { //TODO: Create alternative party mail optional data field, or organization chairman (based on roles) differently // Ugly hack message.From = new MailAddress("*****@*****.**", qp.EncodeMailHeaderString(mail.Author.Name + " (" + mail.Organization.MailPrefixInherited + ")"), currentEncoding); } } catch (Exception ex) { throw new InvalidSenderException( "Invalid author address in MailProcessor.TransmitOneMail:" + (mail.AuthorPersonId) + ";" + mail.Author.PartyEmail, ex); } } else { try { FunctionalMail.AddressItem aItem = mail.Organization.GetFunctionalMailAddressInh(mail.AuthorType); message.From = new MailAddress(aItem.Email, qp.EncodeMailHeaderString(aItem.Name), currentEncoding); } catch (Exception ex) { throw new InvalidSenderException( "Unknown MailAuthorType in MailProcessor.TransmitOneMail:" + ((int)mail.AuthorType), ex); } } if (recipient.AsOfficer && recipient.Person != null) { try { message.To.Add(new MailAddress(recipient.Person.PartyEmail, qp.EncodeMailHeaderString(recipient.Person.Name + " (" + mail.Organization.MailPrefixInherited + ")"), currentEncoding)); } catch (FormatException e) { string msg = "Invalid officer email address:\r\nperson [" + recipient.Person.Identity + "], mail [" + recipient.Person.PartyEmail + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, e); } } else { try { message.To.Add(new MailAddress(recipient.EmailPerson.Email, qp.EncodeMailHeaderString(recipient.EmailPerson.Name), currentEncoding)); } catch (FormatException e) { string msg = "Invalid email address:\r\nEmailPerson [" + recipient.EmailPerson.Identity + "], mail [" + recipient.EmailPerson.Email + "]\r\nwill not send mail:" + recipient.OutboundMail.Title; throw new InvalidRecipientException(msg, e); } } string culture = mail.Organization.DefaultCountry.Culture; // UGLY UGLY UGLY HACK, NEEDS TO CHANGE ASAP: // We need to determine the culture of the recipient in order to use the right template. However, this is also dependent on the text body, which needs to be // in the same culture. At this point, we don't have the mail/recipient cultures in the schema. This would be the correct solution. // The INCORRECT but working solution is to do as we do here and check if a) it's a reporter and b) the reporter has International/English as a category. If so, // we change the culture to en-US. It's an ugly as all hell hack but it should work as a temporary stopgap. if (recipient.Reporter != null) { MediaCategories categories = recipient.Reporter.MediaCategories; foreach (MediaCategory category in categories) { if (category.Name == "International/English") { culture = Strings.InternationalCultureCode; break; } } } if (limitToText) { // if just text, then just add a plaintext body; string text = ""; //Cant really see any reson the HtmlAgilityPack shouldn't be thread safe, but what the heck, just in case.. lock (lockObject) { try { text = mail.RenderText(recipient.EmailPerson, culture); } catch (Exception ex) { throw new RemoveRecipientException( "TextRendering failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex); } } message.BodyEncoding = currentEncoding; message.Body = text; } else { // otherwise, add a multipart/alternative with text and HTML string text = ""; string html = ""; //Cant really see any reson the HtmlAgilityPack shouldn't be thread safe, but what the heck, just in case.. Exception ex = null; lock (lockObject) { try { text = mail.RenderText(recipient.EmailPerson, culture); html = mail.RenderHtml(recipient.EmailPerson, culture); } catch (Exception e) { ex = e; } } if (text == "") { throw new RemoveRecipientException( "Rendering (text) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex); } if (html == "" || ex != null) { throw new RemoveRecipientException( "Rendering (html) failed for " + mail.Title + " to " + recipient.EmailPerson.Email + " will not retry.\n", ex); } ContentType textContentType = new ContentType(MediaTypeNames.Text.Plain); textContentType.CharSet = currentEncoding.BodyName; ContentType htmlContentType = new ContentType(MediaTypeNames.Text.Html); htmlContentType.CharSet = currentEncoding.BodyName; AlternateView textView = null; AlternateView htmlView = null; if (limitToLatin1) { textView = new AlternateView(new MemoryStream(currentEncoding.GetBytes(text)), textContentType); htmlView = new AlternateView(new MemoryStream(currentEncoding.GetBytes(text)), htmlContentType); } else { textView = AlternateView.CreateAlternateViewFromString(text, textContentType); htmlView = AlternateView.CreateAlternateViewFromString(html, htmlContentType); } // A f*****g stupid Mono bug forces us to transfer-encode in base64: it can't encode qp properly // (the "=" is not encoded to "=3D") htmlView.TransferEncoding = TransferEncoding.Base64; textView.TransferEncoding = TransferEncoding.Base64; // Add the views in increasing order of preference message.AlternateViews.Add(textView); message.AlternateViews.Add(htmlView); } if (mail.AuthorType == MailAuthorType.PirateWeb) { message.Subject = mail.Title; } else if (mail.MailType == 0) { message.Subject = mail.Organization.MailPrefixInherited + ": " + mail.Title; } else { //Title is set up in template processing in OutboundMail rendering. message.Subject = mail.Title; } message.SubjectEncoding = currentEncoding; string smtpServer = ConfigurationManager.AppSettings["SmtpServer"]; if (Debugger.IsAttached) { Debug.WriteLine("sending " + message.Subject + " to " + recipient.EmailPerson.Email); Thread.Sleep(200); //simulate delay } if (smtpServer.ToLower() != "none") { if (smtpServer == null || smtpServer.Length < 2) { smtpServer = "localhost"; } try { SmtpClient client = new SmtpClient(smtpServer, 25); client.Send(message); } catch (SmtpException e) { if (e.ToString().StartsWith("System.Net.Mail.SmtpException: 4")) { // Temporary error (SMTP 4xx). Try again. Thread.Sleep(2000); // Allow 2 seconds pause to wait for smtp-server to become available throw new ReportAndRetryRecipientException("Temporary smtp error, will retry.", e); } // Otherwise, bad recipient (assume so). Have the mail removed from the queue. List <string> recipients = new List <string>(); foreach (MailAddress address in message.To) { recipients.Add(address.Address); } ExceptionMail.Send( new ArgumentException( "Bad Recipients when sending to " + recipient.EmailPerson.Email + ": " + String.Join(", ", recipients.ToArray()), e)); if (mail.AuthorType == MailAuthorType.Person) { try { mail.Author.SendOfficerNotice( "Failed recipient(s): " + String.Join(", ", recipients.ToArray()), "Some recipients failed inexplicably in a mail from you.", 1); } catch (Exception ex) { throw new Exception("Failed to SendOfficerNotice to :" + mail.AuthorPersonId, ex); } } } } return(recipient); // To pass this object onto the we're-done callback } catch (InvalidRecipientException ex) { throw ex; } catch (RetryRecipientException ex) { Thread.Sleep(2000); // Allow 2 seconds pause to avoid flooding the errorlog too fast in case of a permanent failure throw ex; } catch (Exception ex) { throw ex; } }
public MediaManagerViewmodel(IEngine engine, IPreview preview) { _mediaManager = engine.MediaManager; Engine = engine; _preview = preview; if (preview != null) { PreviewViewmodel = new PreviewViewmodel(engine, preview); } MediaDirectories = new List <MediaDirectoryViewmodel>(); MediaDirectories.AddRange(_mediaManager.IngestDirectories.Where(d => d.ContainsImport()).Select(d => new MediaDirectoryViewmodel(d, d.DirectoryName, true))); var archiveDirectory = _mediaManager.ArchiveDirectory; if (archiveDirectory != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(archiveDirectory, resources._archive)); } var animationDirectorySec = _mediaManager.AnimationDirectorySEC; var animationDirectoryPri = _mediaManager.AnimationDirectoryPRI; if (animationDirectorySec != null && animationDirectorySec != animationDirectoryPri) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(animationDirectorySec, resources._animations_Secondary)); } if (animationDirectoryPri != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(animationDirectoryPri, resources._animations_Primary)); } var serverDirectoryPri = _mediaManager.MediaDirectoryPRI; var serverDirectorySec = _mediaManager.MediaDirectorySEC; if (serverDirectorySec != null && serverDirectorySec != serverDirectoryPri) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(serverDirectorySec, resources._secondary)); } if (serverDirectoryPri != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(serverDirectoryPri, resources._primary)); } _mediaCategory = MediaCategories.FirstOrDefault(); SelectedDirectory = MediaDirectories.FirstOrDefault(); if (_mediaManager.FileManager != null) { FileManagerViewmodel = new FileManagerViewmodel(_mediaManager.FileManager); } RecordersViewmodel = new RecordersViewmodel(Engine, _mediaManager.Recorders); RecordersViewmodel.PropertyChanged += _recordersViewmodel_PropertyChanged; VideoPreview = UiPluginManager.ComposePart <IVideoPreview>(this); VideoPreview?.SetSource(RecordersViewmodel.Channel?.PreviewUrl); CommandSearch = new UiCommand(_search, _canSearch); CommandClearFilters = new UiCommand(_clearFilters, _canClearFilters); CommandDeleteSelected = new UiCommand(_deleteSelected, o => _isSomethingSelected() && engine.HaveRight(EngineRight.MediaDelete)); CommandIngestSelectedToServer = new UiCommand(_ingestSelectedToServer, _canIngestSelectedToServer); CommandMoveSelectedToArchive = new UiCommand(_moveSelectedToArchive, o => _selectedDirectory != null && _selectedDirectory.IsServerDirectory && _isSomethingSelected() && engine.HaveRight(EngineRight.MediaArchive) && engine.HaveRight(EngineRight.MediaDelete)); CommandCopySelectedToArchive = new UiCommand(_copySelectedToArchive, o => _selectedDirectory != null && _selectedDirectory.IsServerDirectory && _isSomethingSelected() && engine.HaveRight(EngineRight.MediaArchive)); CommandSweepStaleMedia = new UiCommand(_sweepStaleMedia, o => CurrentUser.IsAdmin); CommandGetLoudness = new UiCommand(_getLoudness, o => _isSomethingSelected() && engine.HaveRight(EngineRight.MediaEdit)); CommandExport = new UiCommand(_export, _canExport); CommandRefresh = new UiCommand(async ob => await _reloadFiles(), _canRefresh); CommandSyncPriToSec = new UiCommand(_syncSecToPri, o => _selectedDirectory.IsServerDirectory && CurrentUser.IsAdmin); CommandCloneAnimation = new UiCommand(_cloneAnimation, _canCloneAnimation); CommandTogglePropertiesPanel = new UiCommand(o => IsPropertiesPanelVisible = !IsPropertiesPanelVisible); CommandVerifyAllMedia = new UiCommand(_verifyAllMedia, o => _selectedDirectory.IsServerDirectory && CurrentUser.IsAdmin); }
private bool _canClearFilters(object obj) { return(IsMediaCategoryVisible && _mediaCategory != MediaCategories.FirstOrDefault() || _mediaType != MediaTypes.FirstOrDefault() || !string.IsNullOrWhiteSpace(_searchText)); }
public static string GetConcatenatedCategoryString (MediaCategories categories) { if (categories.Count == 0) return ""; string result = categories[0].Name; for (int index = 1; index < categories.Count - 1; index++) { result += ", " + categories[index].Name; } if (categories.Count > 1) { //TODO: Translate "och" result += " och " + categories[categories.Count - 1].Name; } return result; }
private static void CheckOneFeed (string readerUrl, string persistAsKey, int orgIdForTemplate) { string persistenceKey = String.Format("Pressrelease-Highwater-{0}", persistAsKey); DateTime highWaterMark = DateTime.MinValue; RssReader reader = null; try { string highWaterMarkString = Persistence.Key[persistenceKey]; if (string.IsNullOrEmpty(highWaterMarkString)) { //Initialize highwatermark if never used highWaterMark = DateTime.Now; Persistence.Key[persistenceKey] = DateTime.Now.ToString(); } else { try { highWaterMark = DateTime.Parse(highWaterMarkString); } catch (Exception ex) { HeartBeater.Instance.SuggestRestart(); throw new Exception( "Triggered restart. Unable to read/parse old highwater mark from database in PressReleaseChecker.Run(), from key:" + persistenceKey + ", loaded string was '" + highWaterMarkString + "' expected format is " + DateTime.Now.ToString(), ex); } } DateTime storedHighWaterMark = highWaterMark; reader = new RssReader(readerUrl); Rss rss = reader.Read(); foreach (RssChannelItem item in rss.Channel.Items) { // Ignore any items older than the highwater mark. // Also ignore if older than two days if (item.PubDate < highWaterMark || item.PubDate < DateTime.Now.AddDays(-2)) { continue; } // This is an item we should publish. // Set highwater datetime mark. We do this first, BEFORE processing, as a defense against mail floods, // if should something go wrong and unexpected exceptions happen. // We used to add 70 minutes as a defense against mistakes on DST switch in spring and fall (yes, it has happened), but have reduced to two. if (item.PubDate > storedHighWaterMark) { Persistence.Key[persistenceKey] = item.PubDate.AddMinutes(2).ToString(); storedHighWaterMark = item.PubDate.AddMinutes(2); // Verify that it was written correctly to database. This is defensive programming to avoid a mail flood, // in case we can't write to the database for some reason. string newStoredHighWaterString = ""; try { newStoredHighWaterString = Persistence.Key[persistenceKey]; DateTime temp = DateTime.Parse(newStoredHighWaterString); } catch (Exception ex) { throw new Exception( "Unable to commit/parse new highwater mark to database in PressReleaseChecker.Run(), loaded string was '" + newStoredHighWaterString + "'", ex); } if (DateTime.Parse(Persistence.Key[persistenceKey]) < item.PubDate) { throw new Exception( "Unable to commit new highwater mark to database in PressReleaseChecker.Run()"); } } bool allReporters = false; bool international = false; MediaCategories categories = new MediaCategories(); foreach (RssCategory category in item.Categories) { if (category.Name == "Alla") { allReporters = true; } else if (category.Name == "Uncategorized") { continue; } else { try { MediaCategory mediaCategory = MediaCategory.FromName(category.Name); categories.Add(mediaCategory); if (category.Name.StartsWith("International")) { international = true; } } catch (Exception) { ExceptionMail.Send(new Exception("Unrecognized media category in press release: " + category.Name)); } } } string mailText = Blog2Mail(item.Content); // Create recipient list of relevant reporters Reporters reporters = null; if (allReporters) { reporters = Reporters.GetAll(); } else { reporters = Reporters.FromMediaCategories(categories); } // Add officers if not int'l People officers = new People(); Dictionary<int, bool> officerLookup = new Dictionary<int, bool>(); if (!international) { int[] officerIds = Roles.GetAllDownwardRoles(1, 1); foreach (int officerId in officerIds) { officerLookup[officerId] = true; } } else { officerLookup[1] = true; } // Send press release //TODO: hardcoded geo ... using World Organization org = Organization.FromIdentity(orgIdForTemplate); Geography geo = Geography.Root; PressReleaseMail pressreleasemail = new PressReleaseMail(); pressreleasemail.pSubject = item.Title; pressreleasemail.pDate = DateTime.Now; pressreleasemail.pBodyContent = Blog2Mail(item.Content); pressreleasemail.pOrgName = org.MailPrefixInherited; if (allReporters) { pressreleasemail.pPostedToCategories = "Alla"; // TODO: TRANSLATE } else if (international) { pressreleasemail.pPostedToCategories = "International/English"; // TODO: THIS IS HARDCODED } else { pressreleasemail.pPostedToCategories = PressReleaseMail.GetConcatenatedCategoryString(categories); } OutboundMail newMail = pressreleasemail.CreateFunctionalOutboundMail(MailAuthorType.PressService, OutboundMail.PriorityHighest, org, geo); int recipientCount = 0; foreach (Reporter recipient in reporters) { if (!Formatting.ValidateEmailFormat(recipient.Email)) { continue; } ++recipientCount; newMail.AddRecipient(recipient); } foreach (int key in officerLookup.Keys) { Person recipient = Person.FromIdentity(key); if (!Formatting.ValidateEmailFormat(recipient.Mail)) { continue; } ++recipientCount; newMail.AddRecipient(recipient, true); } newMail.SetRecipientCount(recipientCount); newMail.SetResolved(); newMail.SetReadyForPickup(); } } catch (Exception ex) { ExceptionMail.Send(new Exception("PressReleaseChecker failed:" + ex.Message + "\r\nwhen checking " + readerUrl, ex)); } finally { reader.Close(); } }
public static void Send (string title, bool sendToAll, MediaCategories categories, string mailText, Reporters reporters) { string directory = "content" + Path.DirectorySeparatorChar + "pressreleasetemplate-1"; string htmlTemplate = "Failed to read HTML mail template."; using ( StreamReader reader = new StreamReader(directory + Path.DirectorySeparatorChar + "template.html", System.Text.Encoding.GetEncoding(1252))) { htmlTemplate = reader.ReadToEnd(); } /* using (StreamReader reader = new StreamReader(textTemplateFile, System.Text.Encoding.Default)) { textTemplate = reader.ReadToEnd(); }*/ // PREPARE DATE // assume Swedish System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("sv-SE"); string date = DateTime.Today.ToString("d MMMM yyyy", culture); string time = DateTime.Now.ToString("HH:mm"); string categoriesSentTo = "Alla kategorier"; if (!sendToAll) { categoriesSentTo = GetConcatenatedCategoryString(categories); } // PREPARE HTML VIEW: // Write in the title, intro, and body htmlTemplate = htmlTemplate. Replace("%TITLE%", HttpUtility.HtmlEncode(title.ToUpper())). Replace("%title%", HttpUtility.HtmlEncode(title)). Replace("%date%", HttpUtility.HtmlEncode(date)). Replace("%DATE%", HttpUtility.HtmlEncode(date.ToUpper())). Replace("%time%", HttpUtility.HtmlEncode(time)). Replace("%postedtocategories%", HttpUtility.HtmlEncode(categoriesSentTo)); string body = mailText; body = body. Replace("<", "({[("). Replace(">", ")}])"). Replace("\"", "quotQUOTquot"); body = HttpUtility.HtmlEncode(body); body = body. Replace("({[(", "<"). Replace(")}])", ">"). Replace("quotQUOTquot", "\""). Replace("&#", "&#"); htmlTemplate = htmlTemplate.Replace("%body%", body); // Embed any inline images directly into the message string newsletterIdentifier = DateTime.Now.ToString("yyyyMMddhhMMssfff") + "@piratpartiet.se"; // TODO: Read the replacements from a config file htmlTemplate = htmlTemplate.Replace("header-pp-logo.png", "cid:pplogo" + newsletterIdentifier); /* htmlTemplate = htmlTemplate.Replace("TopRight.png", "cid:topright" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("MiddleRight.png", "cid:middleright" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("BottomRight.png", "cid:bottomright" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("TopLeft.png", "cid:topleft" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("MiddleLeft.png", "cid:middleleft" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("BottomLeft.png", "cid:bottomleft" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("TopMiddle.png", "cid:topmiddle" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("BottomMiddle.png", "cid:bottommiddle" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("PPShield.png", "cid:ppshield" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("Rick.png", "cid:rick" + newsletterIdentifier); htmlTemplate = htmlTemplate.Replace("RFe-signature.gif", "cid:rick-signature" + newsletterIdentifier);*/ // MemoryStream memStream = new MemoryStream(); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType( MediaTypeNames.Text.Html)); htmlView.TransferEncoding = TransferEncoding.Base64; /* LinkedResource image = new LinkedResource(directory + Path.DirectorySeparatorChar + "header-pp-logo.png"); image.ContentId = "pplogo" + newsletterIdentifier; htmlView.LinkedResources.Add(image);*/ /* * -- DISABLED -- code writing a forum-style text file * // PREPARE FORUM FILE: string forumTemplate = textTemplate. Replace("%TITLE%", "[h1]" + title.ToUpper() + "[/h1]"). Replace("%title%", "[h1]" + title + "[/h1]"). Replace("%intro%", intro). Replace("%body%", mailBody); // Replace "<a href="http://link">Text</a>" with "Text (http://link)" Regex regexLinksForum = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline); forumTemplate = regexLinksForum.Replace(forumTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInForum)); using (StreamWriter writer = new StreamWriter(directory + "\\" + "forum.txt", false, System.Text.Encoding.Default)) { writer.WriteLine(forumTemplate); }*/ /* * -- DISABLED -- no text view * * // PREPARE TEXT VIEW: // Write in the title, intro, and body textTemplate = textTemplate. Replace("%TITLE%", title.ToUpper()). Replace("%title%", title). Replace("%intro%", intro). Replace("%body%", mailBody); // Replace "<a href="http://link">Text</a>" with "Text (http://link)" Regex regexLinks = new Regex("(?s)\\[a\\s+href=\\\"(?<link>[^\\\"]+)\\\"\\](?<description>[^\\[]+)\\[/a\\]", RegexOptions.Multiline); textTemplate = regexLinks.Replace(textTemplate, new MatchEvaluator(NewsletterTransmitter2.RewriteUrlsInText)); Regex regexHtmlCodes = new Regex("(?s)\\[[^\\[]+\\]", RegexOptions.Multiline); textTemplate = regexHtmlCodes.Replace(textTemplate, string.Empty); ContentType typeUnicode = new ContentType(MediaTypeNames.Text.Plain); typeUnicode.CharSet = "utf-8"; AlternateView textUnicodeView = AlternateView.CreateAlternateViewFromString(textTemplate, typeUnicode); ContentType typeIsoLatin1 = new ContentType(MediaTypeNames.Text.Plain); typeIsoLatin1.CharSet = "iso-8859-1"; AlternateView textHotmailView = new AlternateView(new MemoryStream(Encoding.Default.GetBytes(textTemplate)), typeIsoLatin1); * * */ foreach (Reporter reporter in reporters) { //Console.Write (recipient.Name + "(#" + recipient.Identity.ToString() + ")... "); try { SmtpClient client = new SmtpClient(Config.SmtpHost, Config.SmtpPort); client.Credentials = null; MailMessage message = new MailMessage( new MailAddress("*****@*****.**", "Piratpartiet Press"), new MailAddress(reporter.Email, reporter.Name, Encoding.UTF8)); message.Subject = "PP-Press: " + title; string individualBody = htmlTemplate; individualBody = individualBody. Replace("%reportername%", HttpUtility.HtmlEncode(reporter.Name)). Replace("%reporteremail%", HttpUtility.HtmlEncode(reporter.Email)). Replace("%reportercategories%", HttpUtility.HtmlEncode(GetConcatenatedCategoryString(reporter.MediaCategories))); message.Body = individualBody; message.BodyEncoding = Encoding.ASCII; message.IsBodyHtml = true; // COMPENSATE FOR MONO BUG -- put logo online instead of attached message.Body = message.Body.Replace("cid:pplogo" + newsletterIdentifier, "http://docs.piratpartiet.se/banners/newsletter-banner-pp-logo.png"); /* Attachment attachment = new Attachment(directory + Path.DirectorySeparatorChar + "header-pp-logo.png", "image/png"); attachment.ContentId = "pplogo" + newsletterIdentifier; attachment.ContentDisposition.Inline = true; message.Attachments.Add(attachment);*/ bool successOrPermanentFail = false; while (!successOrPermanentFail) { try { client.Send(message); successOrPermanentFail = true; } catch (SmtpException e) { if (!(e.ToString().StartsWith("System.Net.Mail.SmtpException: 4"))) { // This is NOT a temporary error (SMTP 4xx). Fail. successOrPermanentFail = true; throw e; } // Otherwise, sleep for a while and try again. System.Threading.Thread.Sleep(1000); } } //Console.WriteLine("ok"); //Console.WriteLine("ok"); } catch (Exception e) { //Console.WriteLine("FAIL! <" + recipient.Email + ">"); ExceptionMail.Send( new Exception("Error sending press release to " + reporter.Name + " <" + reporter.Email + ">:", e),true); } } }
// ------------------------------------------------------------------------------- // ------------------------------------------------------------------------------- /// <summary> /// Adds a media category object /// </summary> /// <param name="obj">RssMediaCategory object</param> // ------------------------------------------------------------------------------- // ------------------------------------------------------------------------------- public void AddMediaCategory(RssMediaCategory obj) { MediaCategories.Add(obj); }
// ------------------------------------------------------------------------------- // ------------------------------------------------------------------------------- /// <summary> /// This loads property of the RssMediaExtension object with the contents of the /// XElement /// </summary> /// <param name="el">Parent XElement</param> // ------------------------------------------------------------------------------- // ------------------------------------------------------------------------------- public void LoadEl(XElement el) { // process this switch only if element is in the media namespace if (el.Name.Namespace == RSS.MEDIA_NS) { switch (el.Name.LocalName) { case RssMediaRating.TAG_PARENT: RssMediaRating rating = new RssMediaRating(); rating.Load(el); MediaRatings.Add(rating); break; case RssMediaTitle.TAG_PARENT: MediaTitle = new RssMediaTitle(); MediaTitle.Load(el); break; case RssMediaDescription.TAG_PARENT: MediaDescription = new RssMediaDescription(); MediaDescription.Load(el); break; case RssMediaKeywords.TAG_PARENT: MediaKeywords = new RssMediaKeywords(); MediaKeywords.Load(el); break; case RssMediaThumbnail.TAG_PARENT: RssMediaThumbnail thumb = new RssMediaThumbnail(this); thumb.Load(el); MediaThumbnails.Add(thumb); break; case RssMediaCategory.TAG_PARENT: RssMediaCategory MediaCategory = new RssMediaCategory(); MediaCategory.Load(el); MediaCategories.Add(MediaCategory); break; case RssMediaHash.TAG_PARENT: RssMediaHash hash = new RssMediaHash(); hash.Load(el); MediaHashes.Add(hash); break; case RssMediaPlayer.TAG_PARENT: MediaPlayer = new RssMediaPlayer(); MediaPlayer.Load(el); break; case RssMediaCredit.TAG_PARENT: RssMediaCredit credit = new RssMediaCredit(); credit.Load(el); MediaCredits.Add(credit); break; case RssMediaCopyright.TAG_PARENT: MediaCopyright = new RssMediaCopyright(); MediaCopyright.Load(el); break; case RssMediaText.TAG_PARENT: RssMediaText txt = new RssMediaText(); txt.Load(el); MediaTexts.Add(txt); break; case RssMediaRestriction.TAG_PARENT: RssMediaRestriction restriction = new RssMediaRestriction(); restriction.Load(el); MediaRestrictions.Add(restriction); break; case RssMediaCommunity.TAG_PARENT: MediaCommunity = new RssMediaCommunity(); MediaCommunity.Load(el); break; case RssMediaComments.TAG_PARENT: MediaComments = new RssMediaComments(); MediaComments.Load(el); break; case RssMediaEmbed.TAG_PARENT: MediaEmbed = new RssMediaEmbed(); MediaEmbed.Load(el); break; case RssMediaResponses.TAG_PARENT: MediaResponses = new RssMediaResponses(); MediaResponses.Load(el); break; case RssMediaBacklinks.TAG_PARENT: MediaBacklinks = new RssMediaBacklinks(); MediaBacklinks.Load(el); break; case RssMediaStatus.TAG_PARENT: MediaStatus = new RssMediaStatus(); MediaStatus.Load(el); break; case RssMediaPrice.TAG_PARENT: RssMediaPrice price = new RssMediaPrice(); price.Load(el); MediaPrices.Add(price); break; case RssMediaLicense.TAG_PARENT: MediaLicense = new RssMediaLicense(); MediaLicense.Load(el); break; case RssMediaSubtitle.TAG_PARENT: RssMediaSubtitle subtitle = new RssMediaSubtitle(); subtitle.Load(el); MediaSubtitles.Add(subtitle); break; case RssMediaPeerLink.TAG_PARENT: MediaPeerLink = new RssMediaPeerLink(); MediaPeerLink.Load(el); break; case RssMediaRights.TAG_PARENT: MediaRights = new RssMediaRights(); MediaRights.Load(el); break; case RssMediaScenes.TAG_PARENT: MediaScenes = new RssMediaScenes(); MediaScenes.Load(el); break; case RssMediaLocation.TAG_PARENT: RssMediaLocation mediaLocation = new RssMediaLocation(); mediaLocation.Load(el); MediaLocations.Add(mediaLocation); break; } } // Dublin core terms namespace else if (el.Name.Namespace == RSS.DUBLIN_CORE_TERMS_NS) { switch (el.Name.LocalName) { case RssDublinCoreValid.TAG_PARENT: MediaValid = new RssDublinCoreValid(); MediaValid.Load(el); break; } } else if (el.Name.Namespace == RSS.GEORSS_NS) { } else if (el.Name.Namespace == RSS.GML_NS) { } }
public MediaManagerViewmodel(IEngine engine, IPreview preview) { _mediaManager = engine.MediaManager; _engine = engine; _preview = preview; if (preview != null) { PreviewViewmodel = new PreviewViewmodel(engine, preview); } MediaDirectories = new List <MediaDirectoryViewmodel>(); MediaDirectories.AddRange(_mediaManager.IngestDirectories.Where(d => d.ContainsImport()).Select(d => new MediaDirectoryViewmodel(d, true))); IArchiveDirectory archiveDirectory = _mediaManager.ArchiveDirectory; if (archiveDirectory != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(archiveDirectory)); } IAnimationDirectory animationDirectoryPri = _mediaManager.AnimationDirectoryPRI; if (animationDirectoryPri != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(animationDirectoryPri)); } IAnimationDirectory animationDirectorySec = _mediaManager.AnimationDirectorySEC; if (animationDirectorySec != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(animationDirectorySec)); } IServerDirectory serverDirectoryPri = _mediaManager.MediaDirectoryPRI; if (serverDirectoryPri != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(serverDirectoryPri)); } IServerDirectory serverDirectorySec = _mediaManager.MediaDirectorySEC; if (serverDirectorySec != null && serverDirectorySec != serverDirectoryPri) { MediaDirectories.Insert(1, new MediaDirectoryViewmodel(serverDirectorySec)); } _mediaCategory = MediaCategories.FirstOrDefault(); SelectedDirectory = MediaDirectories.FirstOrDefault(); if (_mediaManager.FileManager != null) { FileManagerViewmodel = new FileManagerViewmodel(_mediaManager.FileManager); } RecordersViewmodel = new RecordersViewmodel(_engine, _mediaManager.Recorders); RecordersViewmodel.PropertyChanged += _recordersViewmodel_PropertyChanged; ComposePlugins(); VideoPreview?.SetSource(RecordersViewmodel.Channel?.PreviewUrl); CommandSearch = new UICommand { ExecuteDelegate = _search, CanExecuteDelegate = _canSearch }; CommandClearFilters = new UICommand { ExecuteDelegate = _clearFilters, CanExecuteDelegate = _canClearFilters }; CommandDeleteSelected = new UICommand { ExecuteDelegate = _deleteSelected, CanExecuteDelegate = o => _isSomethingSelected() && engine.HaveRight(EngineRight.MediaDelete) }; CommandIngestSelectedToServer = new UICommand { ExecuteDelegate = _ingestSelectedToServer, CanExecuteDelegate = _canIngestSelectedToServer }; CommandMoveSelectedToArchive = new UICommand { ExecuteDelegate = _moveSelectedToArchive, CanExecuteDelegate = o => _selectedDirectory != null && _selectedDirectory.IsServerDirectory && _isSomethingSelected() && engine.HaveRight(EngineRight.MediaArchive) && engine.HaveRight(EngineRight.MediaDelete) }; CommandCopySelectedToArchive = new UICommand { ExecuteDelegate = _copySelectedToArchive, CanExecuteDelegate = o => _selectedDirectory != null && _selectedDirectory.IsServerDirectory && _isSomethingSelected() && engine.HaveRight(EngineRight.MediaArchive) }; CommandSweepStaleMedia = new UICommand { ExecuteDelegate = _sweepStaleMedia, CanExecuteDelegate = o => CurrentUser.IsAdmin }; CommandGetLoudness = new UICommand { ExecuteDelegate = _getLoudness, CanExecuteDelegate = o => _isSomethingSelected() && engine.HaveRight(EngineRight.MediaEdit) }; CommandExport = new UICommand { ExecuteDelegate = _export, CanExecuteDelegate = _canExport }; CommandRefresh = new UICommand { ExecuteDelegate = ob => _refreshMediaDirectory(_selectedDirectory?.Directory), CanExecuteDelegate = _canRefresh }; CommandSyncPriToSec = new UICommand { ExecuteDelegate = _syncSecToPri, CanExecuteDelegate = o => _selectedDirectory.IsServerDirectory && CurrentUser.IsAdmin }; CommandCloneAnimation = new UICommand { ExecuteDelegate = _cloneAnimation, CanExecuteDelegate = _canCloneAnimation }; CommandTogglePropertiesPanel = new UICommand { ExecuteDelegate = o => IsPropertiesPanelVisible = !IsPropertiesPanelVisible }; }
public MediaManagerViewmodel(IMediaManager mediaManager, IPreview preview) { _mediaManager = mediaManager; _preview = preview; if (preview != null) { PreviewViewmodel = new PreviewViewmodel(preview); } MediaDirectories = new List <MediaDirectoryViewmodel>(); MediaDirectories.AddRange(mediaManager.IngestDirectories.Where(d => d.ContainsImport()).Select(d => new MediaDirectoryViewmodel(d, true))); IArchiveDirectory archiveDirectory = mediaManager.ArchiveDirectory; if (archiveDirectory != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(archiveDirectory)); } IAnimationDirectory animationDirectoryPRI = mediaManager.AnimationDirectoryPRI; if (animationDirectoryPRI != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(animationDirectoryPRI)); } IAnimationDirectory animationDirectorySEC = mediaManager.AnimationDirectorySEC; if (animationDirectorySEC != null) { MediaDirectories.Insert(0, new MediaDirectoryViewmodel(animationDirectorySEC)); } IServerDirectory serverDirectoryPRI = mediaManager.MediaDirectoryPRI; MediaDirectoryViewmodel serverDirectoryPRIVm = new MediaDirectoryViewmodel(serverDirectoryPRI); if (serverDirectoryPRI != null) { MediaDirectories.Insert(0, serverDirectoryPRIVm); } IServerDirectory serverDirectorySEC = mediaManager.MediaDirectorySEC; if (serverDirectorySEC != null && serverDirectorySEC != serverDirectoryPRI) { MediaDirectories.Insert(1, new MediaDirectoryViewmodel(serverDirectorySEC)); } _mediaCategory = MediaCategories.FirstOrDefault(); SelectedDirectory = serverDirectoryPRIVm; if (mediaManager.FileManager != null) { FileManagerViewmodel = new FileManagerViewmodel(mediaManager.FileManager); } RecordersViewmodel = new RecordersViewmodel(mediaManager.Recorders); RecordersViewmodel.PropertyChanged += _recordersViewmodel_PropertyChanged; _previewDisplay = true; ComposePlugins(); VideoPreview?.SetSource(RecordersViewmodel.Channel?.PreviewUrl); CommandSearch = new UICommand { ExecuteDelegate = _search, CanExecuteDelegate = _canSearch }; CommandClearFilters = new UICommand { ExecuteDelegate = _clearFilters, CanExecuteDelegate = _canClearFilters }; CommandDeleteSelected = new UICommand { ExecuteDelegate = _deleteSelected, CanExecuteDelegate = _isSomethingSelected }; CommandIngestSelectedToServer = new UICommand { ExecuteDelegate = _ingestSelectedToServer, CanExecuteDelegate = _canIngestSelectedToServer }; CommandMoveSelectedToArchive = new UICommand { ExecuteDelegate = _moveSelectedToArchive, CanExecuteDelegate = o => _selectedDirectory != null && _selectedDirectory.IsServerDirectory && _isSomethingSelected(o) }; CommandCopySelectedToArchive = new UICommand { ExecuteDelegate = _copySelectedToArchive, CanExecuteDelegate = o => _selectedDirectory != null && _selectedDirectory.IsServerDirectory && _isSomethingSelected(o) }; CommandSweepStaleMedia = new UICommand { ExecuteDelegate = _sweepStaleMedia }; CommandGetLoudness = new UICommand { ExecuteDelegate = _getLoudness, CanExecuteDelegate = _isSomethingSelected }; CommandExport = new UICommand { ExecuteDelegate = _export, CanExecuteDelegate = _canExport }; CommandRefresh = new UICommand { ExecuteDelegate = ob => _refreshMediaDirectory(_selectedDirectory?.Directory), CanExecuteDelegate = o => _selectedDirectory?.IsIngestDirectory == true }; CommandSyncPriToSec = new UICommand { ExecuteDelegate = _syncSecToPri, CanExecuteDelegate = o => _selectedDirectory.IsServerDirectory }; CommandCloneAnimation = new UICommand { ExecuteDelegate = _cloneAnimation, CanExecuteDelegate = _canCloneAnimation }; }