コード例 #1
0
        /// <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;

            // 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);
                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 (Exception ex)
            {
                mmApp.Log("Failed to display Weblog Url after posting: " +
                          weblogInfo.PreviewUrl ?? postUrl ?? weblogInfo.ApiUrl);
            }

            return(true);
        }
コード例 #2
0
        private void DropDownButton_Click(object sender, RoutedEventArgs e)
        {
            StatusBar.ShowStatusProgress("Getting Blog listing information from service...");
            WindowUtilities.DoEvents();

            var context = Resources["BlogsContextMenu"] as ContextMenu;

            context.Items.Clear();

            IEnumerable <UserBlog> blogs = null;

            try
            {
                if (Model.ActiveWeblogInfo.Type == WeblogTypes.Medium)
                {
                    var client = new MediumApiClient(Model.ActiveWeblogInfo);
                    blogs = client.GetBlogs();
                    if (blogs == null)
                    {
                        StatusBar.ShowStatusError("Failed to get blog listing: " + client.ErrorMessage);
                    }
                }
                else if (Model.ActiveWeblogInfo.Type == WeblogTypes.MetaWeblogApi ||
                         Model.ActiveWeblogInfo.Type == WeblogTypes.Wordpress)
                {
                    var client = new MetaWebLogWordpressApiClient(Model.ActiveWeblogInfo);
                    blogs = client.GetBlogs();
                    if (blogs == null)
                    {
                        StatusBar.ShowStatusError("Failed to get blog listing: " + client.ErrorMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                StatusBar.ShowStatusError($"Failed to get blogs: {ex.Message}");
                return;
            }

            StatusBar.ShowStatusSuccess("Blogs retrieved.");

            if (blogs == null)
            {
                return;
            }

            string blogId = Model.ActiveWeblogInfo.BlogId as string;

            if (!string.IsNullOrEmpty(blogId) && !blogs.Any(b => blogId == b.BlogId as string))
            {
                context.Items.Add(new MenuItem {
                    Header = blogId, Tag = blogId
                });
            }

            foreach (var blog in blogs)
            {
                var item = new MenuItem()
                {
                    Header = blog.BlogName,
                    Tag    = blog.BlogId,
                };
                item.Click += (s, ea) =>
                {
                    var mitem = s as MenuItem;
                    if (mitem == null)
                    {
                        return;
                    }

                    Model.ActiveWeblogInfo.BlogId = mitem.Tag as string;
                    context.Items.Clear();
                };
                context.Items.Add(item);
            }
        }
コード例 #3
0
        /// <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);
        }
コード例 #4
0
        /// <summary>
        /// High level method that sends posts to the Weblog
        ///
        /// </summary>
        /// <returns></returns>
        public async Task <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.MarkdownDocument.CurrentText;

            // 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, usePragmaLines: false);

            WeblogModel.ActivePost.Body       = html;
            WeblogModel.ActivePost.PostId     = meta.PostId;
            WeblogModel.ActivePost.PostStatus = meta.PostStatus;
            WeblogModel.ActivePost.Permalink  = meta.Permalink;

            // 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)
                {
                    foreach (var kvp in existingPost.CustomFields)
                    {
                        if (!customFields.ContainsKey(kvp.Key))
                        {
                            AddOrUpdateCustomField(customFields, kvp.Key, kvp.Value);
                        }
                    }
                }
            }
            // add custom fields from Weblog configuration
            if (weblogInfo.CustomFields != null)
            {
                foreach (var kvp in weblogInfo.CustomFields)
                {
                    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(WeblogForm, "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 previewUrl = weblogInfo.PreviewUrl;
            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;

                var result = await Task.Run <bool>(() => client.PublishCompletePost(WeblogModel.ActivePost, basePath,
                                                                                    sendAsDraft, markdown));


                meta.FeaturedImageUrl = client.FeaturedImageUrl;
                meta.FeaturedImageId  = client.FeatureImageId;

                //if (!client.PublishCompletePost(WeblogModel.ActivePost, basePath,
                //    sendAsDraft, markdown))
                if (!result)
                {
                    mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage);
                    MessageBox.Show(WeblogForm, "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;
                    meta.Permalink = post.Permalink;
                    meta.PostId    = post.PostId?.ToString();
                    WeblogModel.ActivePost.PostId    = meta.PostId;
                    WeblogModel.ActivePost.Permalink = post.Permalink;
                }
            }
            if (type == WeblogTypes.Medium)
            {
                var client = new MediumApiClient(weblogInfo);
                var post   = client.PublishCompletePost(WeblogModel.ActivePost, basePath, sendAsDraft);
                if (post == null)
                {
                    mmApp.Log($"Error sending post to Weblog at {weblogInfo.ApiUrl}: " + client.ErrorMessage);
                    MessageBox.Show(WeblogForm, client.ErrorMessage,
                                    "Error Sending Post to Medium",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Exclamation);
                    return(false);
                }

                // this is null
                postUrl = client.PostUrl;
            }

            if (type == WeblogTypes.LocalJekyll)
            {
                var pub = new LocalJekyllPublisher(meta, weblogInfo, Model.ActiveDocument.Filename);
                pub.PublishPost(false);

                if (!string.IsNullOrEmpty(weblogInfo.LaunchCommand))
                {
                    if (!pub.BuildAndLaunchSite())
                    {
                        ShowStatusError(pub.ErrorMessage);
                        return(false);
                    }
                    previewUrl = null;
                    postUrl    = pub.GetPostUrl(weblogInfo.PreviewUrl ?? "http://localhost:4000/{0}");
                }
            }

            meta.PostId = WeblogModel.ActivePost.PostId?.ToString();

            // retrieve the raw editor markdown
            markdown             = editor.MarkdownDocument.CurrentText;
            meta.RawMarkdownBody = markdown;

            // add the meta configuration to it
            markdown = meta.SetPostYamlFromMetaData();

            // write it back out to editor
            editor.SetMarkdown(markdown, updateDirtyFlag: true, keepUndoBuffer: true);

            try
            {
                if (!string.IsNullOrEmpty(postUrl))
                {
                    ShellUtils.GoUrl(postUrl);
                }
                else if (!string.IsNullOrEmpty(previewUrl))
                {
                    var url = string.Format(previewUrl, WeblogModel.ActivePost.PostId);
                    ShellUtils.GoUrl(url);
                }
                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);
        }