private void CreateDownloadedPost() { var item = ListViewPosts.SelectedItem as Post; if (item == null) { return; } string postId = item.PostID.ToString(); WeblogInfo weblogInfo = Model.ActiveWeblogInfo; var wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl, weblogInfo.Username, weblogInfo.Password); Post post = null; try { post = wrapper.GetPost(postId); } catch (Exception ex) { MessageBox.Show("Unable to download post.\r\n\r\n" + ex.Message); return; } Model.Addin.CreateDownloadedPostOnDisk(post, weblogInfo.Name); Close(); }
private async void ButtonValidatePassword_Click(object sender, RoutedEventArgs e) { WeblogInfo weblogInfo = Model.ActiveWeblogInfo; if (string.IsNullOrEmpty(weblogInfo.Username) || string.IsNullOrEmpty(weblogInfo.Password)) { StatusBar.ShowStatusError("Username and/or password are not set."); return; } var client = new MetaWebLogWordpressApiClient(weblogInfo); Model.PostList = new List <Post>(); StatusBar.ShowStatusProgress($"Checking for Weblog access..."); List <Post> posts = null; try { bool result = await Task.Run(() => { posts = client.GetRecentPosts(1).ToList(); return(true); }); StatusBar.ShowStatusSuccess("Password is valid", 5000); } catch (XmlRpcException ex) { StatusBar.ShowStatusError("Password is invalid: " + ex.Message); } catch (Exception ex) { StatusBar.ShowStatusError("Password is invalid: " + ex.Message); } }
public async Task DownloadMetaWeblogAndWordPressPosts() { WeblogInfo weblogInfo = Model.ActiveWeblogInfo; if (weblogInfo.Name == null) { StatusBar.ShowStatusError("Please select a Weblog configuration to list posts for."); return; } var client = new MetaWebLogWordpressApiClient(weblogInfo); Model.Configuration.LastWeblogAccessed = weblogInfo.Name; Model.PostList = new List <Post>(); StatusBar.ShowStatusProgress($"Downloading last {Model.NumberOfPostsToRetrieve} posts..."); List <Post> posts = null; try { bool result = await Task.Run(() => { posts = client.GetRecentPosts(Model.NumberOfPostsToRetrieve).ToList(); return(false); }); } catch (XmlRpcException ex) { string message = ex.Message; if (message == "Not Found") { message = $"Invalid Blog API Url:\r\n{weblogInfo.ApiUrl}"; } MessageBox.Show($"Unable to download posts:\r\n{message}", mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Warning); return; } catch (Exception ex) { MessageBox.Show($"Unable to download posts:\r\n{ex.Message}", mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Warning); return; } for (int i = 0; i < posts.Count; i++) { var post = posts[i]; post.mt_excerpt = StringUtils.TextAbstract(post.mt_excerpt, 220); } WindowUtilities.DoEvents(); Dispatcher.Invoke(() => { StatusBar.ShowStatusSuccess($"{posts.Count} posts downloaded."); Model.PostList = posts; }); }
public WeblogAddinModel() { ActiveWeblogInfo = new WeblogInfo() { Name = "New Weblog", Type = WeblogTypes.MetaWeblogApi }; }
private async Task CreateDownloadedPost() { var item = ListViewPosts.SelectedItem as Post; if (item == null) { return; } StatusBar.ShowStatusProgress("Downloading Weblog post '" + item.Title + "'"); string postId = item.PostId.ToString(); WeblogInfo weblogInfo = Model.ActiveWeblogInfo; Post post = null; if (weblogInfo.Type == WeblogTypes.MetaWeblogApi) { var wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl, weblogInfo.Username, mmApp.DecryptString(weblogInfo.Password), weblogInfo.BlogId); try { post = await Task.Run(() => wrapper.GetPost(postId)); } catch (Exception ex) { StatusBar.ShowStatus(); MessageBox.Show("Unable to download post.\r\n\r\n" + ex.Message); return; } } else { var wrapper = new WordPressWrapper(weblogInfo.ApiUrl, weblogInfo.Username, mmApp.DecryptString(weblogInfo.Password)); try { post = wrapper.GetPost(postId); } catch (Exception ex) { StatusBar.ShowStatus(); MessageBox.Show("Unable to download post.\r\n\r\n" + ex.Message); return; } } Model.Addin.CreateDownloadedPostOnDisk(post, weblogInfo.Name); Close(); StatusBar.ShowStatus(); }
public WeblogAddinModel() { ActiveWeblogInfo = new WeblogInfo() { Name = "New Weblog", Type = WeblogTypes.MetaWeblogApi }; NumberOfPostsToRetrieve = 20; }
/// <summary> /// Returns a Post by Id /// </summary> /// <param name="postId"></param> /// <param name="weblogInfo"></param> /// <returns></returns> public Post GetPost(string postId, WeblogInfo weblogInfo) { if (weblogInfo.Type == WeblogTypes.MetaWeblogApi || weblogInfo.Type == WeblogTypes.Wordpress) { MetaWebLogWordpressApiClient client; client = new MetaWebLogWordpressApiClient(weblogInfo); return(client.GetPost(postId)); } // Medium doesn't support post retrieval so return null return(null); }
private async void Button_DownloadPosts_Click(object sender, RoutedEventArgs e) { WeblogInfo weblogInfo = Model.ActiveWeblogInfo; if (weblogInfo.Type == WeblogTypes.MetaWeblogApi || weblogInfo.Type == WeblogTypes.Wordpress) { await DownloadMetaWeblogAndWordPressPosts(); } else if (weblogInfo.Type == WeblogTypes.LocalJekyll) { await DownloadJekyllPosts(); } else { StatusBar.ShowStatusError($"The Weblog {weblogInfo.Name} doesn't support downloading of posts."); } }
private async void Button_DownloadPosts_Click(object sender, RoutedEventArgs e) { WeblogInfo weblogInfo = Model.ActiveWeblogInfo; var wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl, weblogInfo.Username, weblogInfo.DecryptPassword(weblogInfo.Password), weblogInfo.BlogId); Model.Configuration.LastWeblogAccessed = weblogInfo.Name; Dispatcher.Invoke(() => { Model.PostList = new List<Post>(); SetStatusIcon(FontAwesomeIcon.Download, Colors.Orange,true); ShowStatus("Downloading last " + Model.NumberOfPostsToRetrieve + " posts..."); }); WindowUtilities.DoEvents(); List<Post> posts = null; try { bool result = await Task.Run(() => { posts = wrapper.GetRecentPosts(Model.NumberOfPostsToRetrieve).ToList(); return false; }); } catch (XmlRpcException ex) { string message = ex.Message; if (message == "Not Found") message = "Invalid Blog API Url:\r\n" + weblogInfo.ApiUrl; MessageBox.Show("Unable to download posts:\r\n" + message,mmApp.ApplicationName, MessageBoxButton.OK,MessageBoxImage.Warning); return; } catch(Exception ex) { MessageBox.Show("Unable to download posts:\r\n" + ex.Message,mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Warning); return; } for (int i = 0; i < posts.Count; i++) { var post = posts[i]; post.mt_excerpt = StringUtils.TextAbstract(post.mt_excerpt, 220); } WindowUtilities.DoEvents(); Dispatcher.Invoke(() => { ShowStatus(posts.Count + " posts downloaded.",5000); SetStatusIcon(); Model.PostList = posts; }); }
/// <summary> /// Strips the Markdown Meta data from the message and populates /// the post structure with the meta data values. /// </summary> /// <param name="markdown"></param> /// <param name="post"></param> /// <param name="weblogInfo"></param> /// <returns></returns> public static WeblogPostMetadata GetPostConfigFromMarkdown(string markdown, Post post, WeblogInfo weblogInfo) { var meta = new WeblogPostMetadata() { RawMarkdownBody = markdown, MarkdownBody = markdown, WeblogName = WeblogAddinConfiguration.Current.LastWeblogAccessed, CustomFields = new Dictionary <string, CustomField>() }; // check for title in first line and remove it // since the body shouldn't render the title var lines = StringUtils.GetLines(markdown, 40); if (lines.Length > 2 && lines[0] == "---") { var block = mmFileUtils.ExtractString(meta.MarkdownBody, "---", "\n---", returnDelimiters: true); if (!string.IsNullOrEmpty(block)) { meta = WeblogPostMetadata.GetPostYamlConfigFromMarkdown(markdown, post, weblogInfo); meta.RawMarkdownBody = markdown; if (string.IsNullOrEmpty(meta.WeblogName)) { meta.WeblogName = WeblogAddinConfiguration.Current.LastWeblogAccessed; } meta.MarkdownBody = meta.MarkdownBody.Replace(block, "").Trim(); // update to what's left lines = StringUtils.GetLines(meta.MarkdownBody, 10); } } if (lines.Length > 0 && lines[0].StartsWith("# ")) { if (!meta.DontStripH1Header && weblogInfo.Type != WeblogTypes.Medium) // medium wants the header in the text { meta.MarkdownBody = meta.MarkdownBody.Replace(lines[0], "").Trim(); } if (string.IsNullOrEmpty(meta.Title)) { meta.Title = lines[0].Trim().Substring(2); } } string config = StringUtils.ExtractString(markdown, "<!-- Post Configuration -->", "<!-- End Post Configuration -->", caseSensitive: false, allowMissingEndDelimiter: true, returnDelimiters: true); if (string.IsNullOrEmpty(config)) { return(meta); } // strip the config section meta.MarkdownBody = meta.MarkdownBody.Replace(config, ""); string title = StringUtils.ExtractString(config, "\n<title>", "</title>").Trim(); if (string.IsNullOrEmpty(meta.Title)) { meta.Title = title; } meta.Abstract = StringUtils.ExtractString(config, "\n<abstract>", "\n</abstract>").Trim(); meta.Keywords = StringUtils.ExtractString(config, "\n<keywords>", "\n</keywords>").Trim(); meta.Categories = StringUtils.ExtractString(config, "\n<categories>", "\n</categories>").Trim(); meta.PostId = StringUtils.ExtractString(config, "\n<postid>", "</postid>").Trim(); string strIsDraft = StringUtils.ExtractString(config, "\n<isDraft>", "</isDraft>").Trim(); if (strIsDraft != null && strIsDraft == "True") { meta.PostStatus = "draft"; } string weblogName = StringUtils.ExtractString(config, "\n<weblog>", "</weblog>").Trim(); if (!string.IsNullOrEmpty(weblogName)) { meta.WeblogName = weblogName; } string inferFeaturedImage = StringUtils.ExtractString(config, "\n<inferFeaturedImage>", "</inferFeaturedImage>"); if (!string.IsNullOrEmpty(inferFeaturedImage)) { meta.DontInferFeaturedImage = inferFeaturedImage != "False" && inferFeaturedImage != "false"; } string featuredImageUrl = StringUtils.ExtractString(config, "\n<featuredImage>", "</featuredImage>"); if (!string.IsNullOrEmpty(featuredImageUrl)) { meta.FeaturedImageUrl = featuredImageUrl.Trim(); } string featuredImageId = StringUtils.ExtractString(config, "\n<featuredImageId>", "</featuredImageId>"); if (!string.IsNullOrEmpty(featuredImageId)) { meta.FeaturedImageId = featuredImageId.Trim(); } string customFieldsString = StringUtils.ExtractString(config, "\n<customFields>", "</customFields>", returnDelimiters: true); if (!string.IsNullOrEmpty(customFieldsString)) { try { var dom = new XmlDocument(); dom.LoadXml(customFieldsString); foreach (XmlNode child in dom.DocumentElement.ChildNodes) { if (child.NodeType == XmlNodeType.Element) { var key = child.FirstChild.InnerText; var value = child.ChildNodes[1].InnerText; string id = null; if (child.ChildNodes.Count > 2) { id = child.ChildNodes[2].InnerText; } meta.CustomFields.Add(key, new CustomField { Key = key, Value = value, Id = id }); } } } catch { } } post.Title = meta.Title; post.Categories = meta.Categories.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); post.Tags = meta.Keywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); post.mt_excerpt = meta.Abstract; post.mt_keywords = meta.Keywords; return(meta); }
/// <summary> /// Strips the Markdown Meta data from the message and populates /// the post structure with the meta data values. /// </summary> /// <param name="markdown"></param> /// <param name="post"></param> /// <param name="weblogInfo"></param> public static WeblogPostMetadata GetPostYamlConfigFromMarkdown(string markdown, Post post, WeblogInfo weblogInfo) { var meta = new WeblogPostMetadata() { RawMarkdownBody = markdown, MarkdownBody = markdown, WeblogName = WeblogAddinConfiguration.Current.LastWeblogAccessed, CustomFields = new Dictionary <string, CustomField>() }; if (string.IsNullOrEmpty(markdown)) { return(meta); } markdown = markdown.Trim(); if (!markdown.StartsWith("---\n") && !markdown.StartsWith("---\r")) { return(meta); } string extractedYaml = null; //var match = YamlExtractionRegex.Match(markdown); var match = YamlExtractionRegex.Match(markdown); if (match.Success) { extractedYaml = match.Value; } //var extractedYaml = StringUtils.ExtractString(markdown.TrimStart(), "---\n", "\n---\n",returnDelimiters: true); if (string.IsNullOrEmpty(extractedYaml)) { return(meta); } var yaml = StringUtils.ExtractString(markdown, "---", "\n---", returnDelimiters: false).Trim(); var input = new StringReader(yaml); var deserializer = new DeserializerBuilder() .IgnoreUnmatchedProperties() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); WeblogPostMetadata yamlMeta = null; try { yamlMeta = deserializer.Deserialize <WeblogPostMetadata>(input); } catch { return(meta); } if (yamlMeta == null) { return(meta); } if (meta.CustomFields == null) { meta.CustomFields = new Dictionary <string, CustomField>(); } meta = yamlMeta; meta.MarkdownBody = markdown.Replace(extractedYaml, ""); meta.RawMarkdownBody = markdown; post.Title = meta.Title; if (!string.IsNullOrEmpty(meta.Categories)) { post.Categories = meta.Categories.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } if (!string.IsNullOrEmpty(meta.Keywords)) { post.Tags = meta.Keywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } post.mt_excerpt = meta.Abstract; post.mt_keywords = meta.Keywords; if (meta.CustomFields != null) { post.CustomFields = meta.CustomFields.Values.ToArray(); } return(meta); }
private async Task CreateDownloadedPost() { var item = ListViewPosts.SelectedItem as Post; if (item == null) { return; } WeblogInfo weblogInfo = Model.ActiveWeblogInfo; StatusBar.ShowStatusProgress("Downloading Weblog post '" + item.Title + "'"); string postId = item.PostId?.ToString(); Post post = null; if (weblogInfo.Type == WeblogTypes.MetaWeblogApi) { var wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl, weblogInfo.Username, mmApp.DecryptString(weblogInfo.Password), weblogInfo.BlogId); try { post = await Task.Run(() => wrapper.GetPost(postId)); } catch (Exception ex) { StatusBar.ShowStatusError("Unable to download post.\r\n\r\n" + ex.Message); return; } Model.Addin.CreateDownloadedPostOnDisk(post, weblogInfo.Name); } else if (weblogInfo.Type == WeblogTypes.Wordpress) { var wrapper = new WordPressWrapper(weblogInfo.ApiUrl, weblogInfo.Username, mmApp.DecryptString(weblogInfo.Password)); try { post = wrapper.GetPost(postId); } catch (Exception ex) { StatusBar.ShowStatus(); StatusBar.ShowStatusError("Unable to download post.\r\n\r\n" + ex.Message); return; } Model.Addin.CreateDownloadedPostOnDisk(post, weblogInfo.Name); } else if (weblogInfo.Type == WeblogTypes.LocalJekyll) { var pub = new LocalJekyllPublisher(null, weblogInfo, null); post = pub.GetPost(postId); if (post == null) { StatusBar.ShowStatusError("Unable to import post from Jekyll."); return; } string outputFile = pub.CreateDownloadedPostOnDisk(post, weblogInfo.Name); mmApp.Model.Window.OpenTab(outputFile); mmApp.Model.Window.ShowFolderBrowser(folder: Path.GetDirectoryName(outputFile)); } Close(); StatusBar.ShowStatusSuccess("Post has been imported into Markdown Monster Web log Posts."); }
/// <summary> /// High level method that sends posts to the Weblog /// /// </summary> /// <returns></returns> public bool SendPost(WeblogTypes type = WeblogTypes.Unknown, bool sendAsDraft = false) { var editor = Model.ActiveEditor; if (editor == null) { return(false); } var doc = editor.MarkdownDocument; ActivePost = new Post() { DateCreated = DateTime.Now }; // start by retrieving the current Markdown from the editor string markdown = editor.GetMarkdown(); // Retrieve Meta data from post and clean up the raw markdown // so we render without the config data var meta = GetPostConfigFromMarkdown(markdown); string html = doc.RenderHtml(meta.MarkdownBody, WeblogAddinConfiguration.Current.RenderLinksOpenExternal); var config = WeblogAddinConfiguration.Current; var kv = config.Weblogs.FirstOrDefault(kvl => kvl.Value.Name == meta.WeblogName); if (kv.Equals(default(KeyValuePair <string, WeblogInfo>))) { MessageBox.Show("Invalid Weblog configuration selected.", "Weblog Posting Failed", MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } WeblogInfo weblogInfo = kv.Value; if (type == WeblogTypes.Unknown) { type = weblogInfo.Type; } MetaWeblogWrapper wrapper; if (type == WeblogTypes.MetaWeblogApi) { wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl, weblogInfo.Username, weblogInfo.DecryptPassword(weblogInfo.Password), weblogInfo.BlogId); } else { wrapper = new WordPressWrapper(weblogInfo.ApiUrl, weblogInfo.Username, weblogInfo.DecryptPassword(weblogInfo.Password)); } string body; try { body = SendImages(html, doc.Filename, wrapper, meta); } catch (Exception ex) { mmApp.Log($"Error sending images to Weblog at {weblogInfo.ApiUrl}: ", ex); return(false); } if (body == null) { return(false); } ActivePost.Body = body; ActivePost.PostID = meta.PostId; var customFields = new List <CustomField>(); customFields.Add( new CustomField() { ID = "mt_markdown", Key = "mt_markdown", Value = meta.MarkdownBody }); if (!string.IsNullOrEmpty(meta.FeaturedImageUrl)) { customFields.Add( new CustomField() { ID = "wp_post_thumbnail", Key = "wp_post_thumbnail", Value = meta.FeaturedImageUrl }); } ActivePost.CustomFields = customFields.ToArray(); bool isNewPost = IsNewPost(ActivePost.PostID); try { if (!isNewPost) { wrapper.EditPost(ActivePost, !sendAsDraft); } else { ActivePost.PostID = wrapper.NewPost(ActivePost, !sendAsDraft); } } catch (Exception ex) { mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: ", ex); MessageBox.Show($"Error sending post to Weblog: " + ex.Message, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); mmApp.Log(ex); return(false); } meta.PostId = ActivePost.PostID.ToString(); // retrieve the raw editor markdown markdown = editor.GetMarkdown(); meta.RawMarkdownBody = markdown; // add the meta configuration to it markdown = SetConfigInMarkdown(meta); // write it back out to editor editor.SetMarkdown(markdown); // preview post if (!string.IsNullOrEmpty(weblogInfo.PreviewUrl)) { var url = weblogInfo.PreviewUrl.Replace("{0}", ActivePost.PostID.ToString()); ShellUtils.GoUrl(url); } else { try { var postRaw = wrapper.GetPostRaw(ActivePost.PostID); var link = postRaw.link; if (!string.IsNullOrEmpty(link) && (link.StartsWith("http://") || link.StartsWith("https://"))) { ShellUtils.GoUrl(link); } else { // just go to the base domain - assume posts are listed there ShellUtils.GoUrl(new Uri(weblogInfo.ApiUrl).GetLeftPart(UriPartial.Authority)); } } catch { } } return(true); }
/// <summary> /// High level method that sends posts to the Weblog /// /// </summary> /// <returns></returns> public bool SendPost(WeblogInfo weblogInfo, bool sendAsDraft = false) { var editor = Model.ActiveEditor; if (editor == null) { return(false); } var doc = editor.MarkdownDocument; WeblogModel.ActivePost = new Post() { DateCreated = DateTime.Now }; // start by retrieving the current Markdown from the editor string markdown = editor.GetMarkdown(); // Retrieve Meta data from post and clean up the raw markdown // so we render without the config data var meta = WeblogPostMetadata.GetPostConfigFromMarkdown(markdown, WeblogModel.ActivePost, weblogInfo); string html = doc.RenderHtml(meta.MarkdownBody, WeblogAddinConfiguration.Current.RenderLinksOpenExternal); WeblogModel.ActivePost.Body = html; WeblogModel.ActivePost.PostId = meta.PostId; WeblogModel.ActivePost.PostStatus = meta.PostStatus; // Custom Field Processing: // Add custom fields from existing post // then add or update our custom fields var customFields = new Dictionary <string, CustomField>(); // load existing custom fields from post online if possible if (!string.IsNullOrEmpty(meta.PostId)) { var existingPost = GetPost(meta.PostId, weblogInfo); if (existingPost != null && meta.CustomFields != null && existingPost.CustomFields != null) { customFields = existingPost.CustomFields .ToDictionary(cf => cf.Key, cf => cf); } } // add custom fields from Weblog configuration if (weblogInfo.CustomFields != null) { foreach (var kvp in weblogInfo.CustomFields) { if (!customFields.ContainsKey(kvp.Key)) { AddOrUpdateCustomField(customFields, kvp.Key, kvp.Value); } } } // add custom fields from Meta data if (meta.CustomFields != null) { foreach (var kvp in meta.CustomFields) { AddOrUpdateCustomField(customFields, kvp.Key, kvp.Value.Value); } } if (!string.IsNullOrEmpty(markdown)) { AddOrUpdateCustomField(customFields, "mt_markdown", markdown); } WeblogModel.ActivePost.CustomFields = customFields.Values.ToArray(); var config = WeblogAddinConfiguration.Current; var kv = config.Weblogs.FirstOrDefault(kvl => kvl.Value.Name == meta.WeblogName); if (kv.Equals(default(KeyValuePair <string, WeblogInfo>))) { MessageBox.Show("Invalid Weblog configuration selected.", "Weblog Posting Failed", MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } weblogInfo = kv.Value; var type = weblogInfo.Type; if (type == WeblogTypes.Unknown) { type = weblogInfo.Type; } string basePath = Path.GetDirectoryName(doc.Filename); string postUrl = null; if (type == WeblogTypes.MetaWeblogApi || type == WeblogTypes.Wordpress) { MetaWebLogWordpressApiClient client; client = new MetaWebLogWordpressApiClient(weblogInfo); // if values are already configured don't overwrite them again client.DontInferFeaturedImage = meta.DontInferFeaturedImage; client.FeaturedImageUrl = meta.FeaturedImageUrl; client.FeatureImageId = meta.FeaturedImageId; if (!client.PublishCompletePost(WeblogModel.ActivePost, basePath, sendAsDraft, markdown)) { mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage); MessageBox.Show("Error sending post to Weblog: " + client.ErrorMessage, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } var post = client.GetPost(WeblogModel.ActivePost.PostId); if (post != null) { postUrl = post.Url; } } if (type == WeblogTypes.Medium) { var client = new MediumApiClient(weblogInfo); var result = client.PublishCompletePost(WeblogModel.ActivePost, basePath, sendAsDraft); if (result == null) { mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage); MessageBox.Show($"Error sending post to Weblog: " + client.ErrorMessage, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } // this is null postUrl = client.PostUrl; } meta.PostId = WeblogModel.ActivePost.PostId.ToString(); // retrieve the raw editor markdown markdown = editor.GetMarkdown(); meta.RawMarkdownBody = markdown; // add the meta configuration to it markdown = meta.SetPostYaml(); // write it back out to editor editor.SetMarkdown(markdown, updateDirtyFlag: true); try { // preview post if (!string.IsNullOrEmpty(weblogInfo.PreviewUrl)) { var url = weblogInfo.PreviewUrl.Replace("{0}", WeblogModel.ActivePost.PostId.ToString()); ShellUtils.GoUrl(url); } else { if (!string.IsNullOrEmpty(postUrl)) { ShellUtils.GoUrl(postUrl); } else { ShellUtils.GoUrl(new Uri(weblogInfo.ApiUrl).GetLeftPart(UriPartial.Authority)); } } } catch { mmApp.Log("Failed to display Weblog Url after posting: " + weblogInfo.PreviewUrl ?? postUrl ?? weblogInfo.ApiUrl); } return(true); }
/// <summary> /// High level method that sends posts to the Weblog /// /// </summary> /// <returns></returns> public bool SendPost(WeblogTypes type = WeblogTypes.MetaWeblogApi, bool sendAsDraft = false) { var editor = Model.ActiveEditor; if (editor == null) { return(false); } var doc = editor.MarkdownDocument; ActivePost = new Post() { DateCreated = DateTime.Now }; // start by retrieving the current Markdown from the editor string markdown = editor.GetMarkdown(); // Retrieve Meta data from post and clean up the raw markdown // so we render without the config data var meta = GetPostConfigFromMarkdown(markdown); string html = doc.RenderHtml(meta.MarkdownBody, WeblogAddinConfiguration.Current.RenderLinksOpenExternal); var config = WeblogAddinConfiguration.Current; var kv = config.Weblogs.FirstOrDefault(kvl => kvl.Value.Name == meta.WeblogName); if (kv.Equals(default(KeyValuePair <string, WeblogInfo>))) { MessageBox.Show("Invalid Weblog configuration selected.", "Weblog Posting Failed", MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } WeblogInfo weblogInfo = kv.Value; MetaWeblogWrapper wrapper; if (type == WeblogTypes.MetaWeblogApi) { wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl, weblogInfo.Username, weblogInfo.Password, weblogInfo.BlogId) as MetaWeblogWrapper; } else { wrapper = new WordPressWrapper(weblogInfo.ApiUrl, weblogInfo.Username, weblogInfo.Password) as MetaWeblogWrapper; } string body = SendImages(html, doc.Filename, wrapper); if (body == null) { return(false); } ActivePost.Body = body; ActivePost.PostID = meta.PostId; ActivePost.CustomFields = new CustomField[1] { new CustomField() { ID = "mt_markdown", Key = "mt_markdown", Value = meta.MarkdownBody } }; bool isNewPost = IsNewPost(ActivePost.PostID); try { if (!isNewPost) { wrapper.EditPost(ActivePost, !sendAsDraft); } else { ActivePost.PostID = wrapper.NewPost(ActivePost, !sendAsDraft); } } catch (Exception ex) { MessageBox.Show("Error sending post to Weblog: " + ex.Message, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); mmApp.Log(ex); return(false); } meta.PostId = ActivePost.PostID.ToString(); // retrieve the raw editor markdown markdown = editor.GetMarkdown(); meta.RawMarkdownBody = markdown; // add the meta configuration to it markdown = SetConfigInMarkdown(meta); // write it back out to editor editor.SetMarkdown(markdown); // preview post if (!string.IsNullOrEmpty(weblogInfo.PreviewUrl)) { var url = weblogInfo.PreviewUrl.Replace("{0}", ActivePost.PostID.ToString()); ShellUtils.GoUrl(url); } return(true); }
/// <summary> /// High level method that sends posts to the Weblog /// /// </summary> /// <returns></returns> public bool SendPost(WeblogInfo weblogInfo, bool sendAsDraft = false) { var editor = Model.ActiveEditor; if (editor == null) { return(false); } var doc = editor.MarkdownDocument; ActivePost = new Post() { DateCreated = DateTime.Now }; // start by retrieving the current Markdown from the editor string markdown = editor.GetMarkdown(); // Retrieve Meta data from post and clean up the raw markdown // so we render without the config data var meta = GetPostConfigFromMarkdown(markdown, weblogInfo); string html = doc.RenderHtml(meta.MarkdownBody, WeblogAddinConfiguration.Current.RenderLinksOpenExternal); ActivePost.Body = html; ActivePost.PostID = meta.PostId; var customFields = new List <CustomField>(); if (!string.IsNullOrEmpty(markdown)) { customFields.Add(new CustomField() { ID = "mt_markdown", Key = "mt_markdown", Value = markdown }); } if (weblogInfo.CustomFields != null) { foreach (var kvp in weblogInfo.CustomFields) { customFields.Add(new CustomField { ID = kvp.Key, Key = kvp.Key, Value = kvp.Value }); } } if (meta.CustomFields != null) { foreach (var kvp in meta.CustomFields) { customFields.Add(new CustomField { Key = kvp.Key, ID = kvp.Key, Value = kvp.Value }); } } ActivePost.CustomFields = customFields.ToArray(); var config = WeblogAddinConfiguration.Current; var kv = config.Weblogs.FirstOrDefault(kvl => kvl.Value.Name == meta.WeblogName); if (kv.Equals(default(KeyValuePair <string, WeblogInfo>))) { MessageBox.Show("Invalid Weblog configuration selected.", "Weblog Posting Failed", MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } weblogInfo = kv.Value; var type = weblogInfo.Type; if (type == WeblogTypes.Unknown) { type = weblogInfo.Type; } string basePath = Path.GetDirectoryName(doc.Filename); string postUrl = null; if (type == WeblogTypes.MetaWeblogApi || type == WeblogTypes.Wordpress) { MetaWebLogWordpressApiClient client; client = new MetaWebLogWordpressApiClient(weblogInfo); // if values are already configured don't overwrite them again client.FeaturedImageUrl = meta.FeaturedImageUrl; client.FeatureImageId = meta.FeatureImageId; if (!client.PublishCompletePost(ActivePost, basePath, sendAsDraft, markdown)) { mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage); MessageBox.Show($"Error sending post to Weblog: " + client.ErrorMessage, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } postUrl = client.GetPostUrl(ActivePost.PostID); } if (type == WeblogTypes.Medium) { var client = new MediumApiClient(weblogInfo); var result = client.PublishCompletePost(ActivePost, basePath, sendAsDraft); if (result == null) { mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage); MessageBox.Show($"Error sending post to Weblog: " + client.ErrorMessage, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); return(false); } // this is null postUrl = client.PostUrl; } meta.PostId = ActivePost.PostID.ToString(); // retrieve the raw editor markdown markdown = editor.GetMarkdown(); meta.RawMarkdownBody = markdown; // add the meta configuration to it markdown = SetConfigInMarkdown(meta); // write it back out to editor editor.SetMarkdown(markdown); // preview post if (!string.IsNullOrEmpty(weblogInfo.PreviewUrl)) { var url = weblogInfo.PreviewUrl.Replace("{0}", ActivePost.PostID.ToString()); ShellUtils.GoUrl(url); } else { if (postUrl != null) { ShellUtils.GoUrl(postUrl); } else { ShellUtils.GoUrl(new Uri(weblogInfo.ApiUrl).GetLeftPart(UriPartial.Authority)); } } return(true); }