<commit_before>﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using JetBrains.Annotations;
using Orchard.Blogs.Drivers;
using Orchard.Blogs.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.Core.Common.Models;
using Orchard.Core.Routable.Models;
using Orchard.Core.XmlRpc;
using Orchard.Core.XmlRpc.Models;
using Orchard.Environment.Extensions;
using Orchard.Logging;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Blogs.Extensions;

namespace Orchard.Blogs.Services {
    [UsedImplicitly]
    [OrchardFeature("Remote Blog Publishing")]
    public class XmlRpcHandler : IXmlRpcHandler {
        private readonly IBlogService _blogService;
        private readonly IBlogPostService _blogPostService;
        private readonly IContentManager _contentManager;
        private readonly IAuthorizationService _authorizationService;
        private readonly IMembershipService _membershipService;
        private readonly RouteCollection _routeCollection;

        public XmlRpcHandler(IBlogService blogService, IBlogPostService blogPostService, IContentManager contentManager,
            IAuthorizationService authorizationService, IMembershipService membershipService,
            RouteCollection routeCollection) {
            _blogService = blogService;
            _blogPostService = blogPostService;
            _contentManager = contentManager;
            _authorizationService = authorizationService;
            _membershipService = membershipService;
            _routeCollection = routeCollection;
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public void Process(XmlRpcContext context) {
            var urlHelper = new UrlHelper(context.ControllerContext.RequestContext, _routeCollection);

            if (context.Request.MethodName == "blogger.getUsersBlogs") {
                var result = MetaWeblogGetUserBlogs(urlHelper,
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value));

                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.getRecentPosts") {
                var result = MetaWeblogGetRecentPosts(urlHelper,
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    Convert.ToInt32(context.Request.Params[3].Value));

                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.newPost") {
                var result = MetaWeblogNewPost(
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    (XRpcStruct)context.Request.Params[3].Value,
                    Convert.ToBoolean(context.Request.Params[4].Value));

                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.getPost") {
                var result = MetaWeblogGetPost(
                    urlHelper,
                    Convert.ToInt32(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value));
                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.editPost") {
                var result = MetaWeblogEditPost(
                    Convert.ToInt32(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    (XRpcStruct)context.Request.Params[3].Value,
                    Convert.ToBoolean(context.Request.Params[4].Value));
                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "blogger.deletePost") {
                var result = MetaWeblogDeletePost(
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    Convert.ToString(context.Request.Params[3].Value),
                    Convert.ToBoolean(context.Request.Params[4].Value));
                context.Response = new XRpcMethodResponse().Add(result);
            }
        }

        private XRpcArray MetaWeblogGetUserBlogs(UrlHelper urlHelper,
            string appkey,
            string userName,
            string password) {

            var user = _membershipService.ValidateUser(userName, password);
            _authorizationService.CheckAccess(StandardPermissions.AccessFrontEnd, user, null);

            var array = new XRpcArray();
            foreach (var blog in _blogService.Get()) {
                array.Add(new XRpcStruct()
                              .Set("url", urlHelper.AbsoluteAction(() => urlHelper.Blog(blog.Slug)))
                              .Set("blogid", blog.Id)
                              .Set("blogName", blog.Name));
            }
            return array;
        }

        private XRpcArray MetaWeblogGetRecentPosts(
            UrlHelper urlHelper,
            string blogId,
            string userName,
            string password,
            int numberOfPosts) {

            var user = _membershipService.ValidateUser(userName, password);
            _authorizationService.CheckAccess(StandardPermissions.AccessFrontEnd, user, null);

            var blog = _contentManager.Get<BlogPart>(Convert.ToInt32(blogId));
            if (blog == null)
                throw new ArgumentException();

            var array = new XRpcArray();
            foreach (var blogPost in _blogPostService.Get(blog).Take(numberOfPosts)) {
                array.Add(CreateBlogStruct(blogPost, urlHelper));
            }
            return array;
        }

        private int MetaWeblogNewPost(
            string blogId,
            string userName,
            string password,
            XRpcStruct content,
            bool publish) {

            var user = _membershipService.ValidateUser(userName, password);
            _authorizationService.CheckAccess(Permissions.EditBlogPost, user, null);

            var blog = _contentManager.Get<BlogPart>(Convert.ToInt32(blogId));
            if (blog == null)
                throw new ArgumentException();

            var title = content.Optional<string>("title");
            var description = content.Optional<string>("description");
            var slug = content.Optional<string>("wp_slug");

            var blogPost = _contentManager.New<BlogPostPart>(BlogPostPartDriver.ContentType.Name);
            
            // BodyPart
            if (blogPost.Is<BodyPart>()) {
                blogPost.As<BodyPart>().Text = description;
            }

            //RoutePart
            if (blogPost.Is<RoutePart>()) {
                blogPost.As<RoutePart>().Title = title;
                blogPost.As<RoutePart>().Slug = slug;
                blogPost.As<RoutePart>().Path = blogPost.As<RoutePart>().GetPathFromSlug(slug);
            }

            //CommonPart
            if (blogPost.Is<ICommonPart>()) {
                blogPost.As<ICommonPart>().Owner = user;
                blogPost.As<ICommonPart>().Container = blog;
            }

            _contentManager.Create(blogPost.ContentItem, VersionOptions.Draft);

            if (publish)
                _blogPostService.Publish(blogPost);<commit_msg>Getting the slug and path of a blog post set when created from live writer.<commit_after>﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using JetBrains.Annotations;
using Orchard.Blogs.Drivers;
using Orchard.Blogs.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.Core.Common.Models;
using Orchard.Core.Routable.Models;
using Orchard.Core.Routable.Services;
using Orchard.Core.XmlRpc;
using Orchard.Core.XmlRpc.Models;
using Orchard.Environment.Extensions;
using Orchard.Logging;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Blogs.Extensions;

namespace Orchard.Blogs.Services {
    [UsedImplicitly]
    [OrchardFeature("Remote Blog Publishing")]
    public class XmlRpcHandler : IXmlRpcHandler {
        private readonly IBlogService _blogService;
        private readonly IBlogPostService _blogPostService;
        private readonly IContentManager _contentManager;
        private readonly IAuthorizationService _authorizationService;
        private readonly IMembershipService _membershipService;
        private readonly IRoutableService _routableService;
        private readonly RouteCollection _routeCollection;

        public XmlRpcHandler(IBlogService blogService, IBlogPostService blogPostService, IContentManager contentManager,
            IAuthorizationService authorizationService, IMembershipService membershipService, IRoutableService routableService,
            RouteCollection routeCollection) {
            _blogService = blogService;
            _blogPostService = blogPostService;
            _contentManager = contentManager;
            _authorizationService = authorizationService;
            _membershipService = membershipService;
            _routableService = routableService;
            _routeCollection = routeCollection;
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public void Process(XmlRpcContext context) {
            var urlHelper = new UrlHelper(context.ControllerContext.RequestContext, _routeCollection);

            if (context.Request.MethodName == "blogger.getUsersBlogs") {
                var result = MetaWeblogGetUserBlogs(urlHelper,
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value));

                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.getRecentPosts") {
                var result = MetaWeblogGetRecentPosts(urlHelper,
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    Convert.ToInt32(context.Request.Params[3].Value));

                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.newPost") {
                var result = MetaWeblogNewPost(
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    (XRpcStruct)context.Request.Params[3].Value,
                    Convert.ToBoolean(context.Request.Params[4].Value));

                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.getPost") {
                var result = MetaWeblogGetPost(
                    urlHelper,
                    Convert.ToInt32(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value));
                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "metaWeblog.editPost") {
                var result = MetaWeblogEditPost(
                    Convert.ToInt32(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    (XRpcStruct)context.Request.Params[3].Value,
                    Convert.ToBoolean(context.Request.Params[4].Value));
                context.Response = new XRpcMethodResponse().Add(result);
            }

            if (context.Request.MethodName == "blogger.deletePost") {
                var result = MetaWeblogDeletePost(
                    Convert.ToString(context.Request.Params[0].Value),
                    Convert.ToString(context.Request.Params[1].Value),
                    Convert.ToString(context.Request.Params[2].Value),
                    Convert.ToString(context.Request.Params[3].Value),
                    Convert.ToBoolean(context.Request.Params[4].Value));
                context.Response = new XRpcMethodResponse().Add(result);
            }
        }

        private XRpcArray MetaWeblogGetUserBlogs(UrlHelper urlHelper,
            string appkey,
            string userName,
            string password) {

            var user = _membershipService.ValidateUser(userName, password);
            _authorizationService.CheckAccess(StandardPermissions.AccessFrontEnd, user, null);

            var array = new XRpcArray();
            foreach (var blog in _blogService.Get()) {
                array.Add(new XRpcStruct()
                              .Set("url", urlHelper.AbsoluteAction(() => urlHelper.Blog(blog.Slug)))
                              .Set("blogid", blog.Id)
                              .Set("blogName", blog.Name));
            }
            return array;
        }

        private XRpcArray MetaWeblogGetRecentPosts(
            UrlHelper urlHelper,
            string blogId,
            string userName,
            string password,
            int numberOfPosts) {

            var user = _membershipService.ValidateUser(userName, password);
            _authorizationService.CheckAccess(StandardPermissions.AccessFrontEnd, user, null);

            var blog = _contentManager.Get<BlogPart>(Convert.ToInt32(blogId));
            if (blog == null)
                throw new ArgumentException();

            var array = new XRpcArray();
            foreach (var blogPost in _blogPostService.Get(blog).Take(numberOfPosts)) {
                array.Add(CreateBlogStruct(blogPost, urlHelper));
            }
            return array;
        }

        private int MetaWeblogNewPost(
            string blogId,
            string userName,
            string password,
            XRpcStruct content,
            bool publish) {

            var user = _membershipService.ValidateUser(userName, password);
            _authorizationService.CheckAccess(Permissions.EditBlogPost, user, null);

            var blog = _contentManager.Get<BlogPart>(Convert.ToInt32(blogId));
            if (blog == null)
                throw new ArgumentException();

            var title = content.Optional<string>("title");
            var description = content.Optional<string>("description");
            var slug = content.Optional<string>("wp_slug");

            var blogPost = _contentManager.New<BlogPostPart>(BlogPostPartDriver.ContentType.Name);
            
            // BodyPart
            if (blogPost.Is<BodyPart>()) {
                blogPost.As<BodyPart>().Text = description;
            }

            //CommonPart
            if (blogPost.Is<ICommonPart>()) {
                blogPost.As<ICommonPart>().Owner = user;
                blogPost.As<ICommonPart>().Container = blog;
            }

            //RoutePart
            if (blogPost.Is<RoutePart>()) {
                blogPost.As<RoutePart>().Title = title;
                blogPost.As<RoutePart>().Slug = slug;
                _routableService.FillSlug(blogPost.As<RoutePart>());
                blogPost.As<RoutePart>().Path = blogPost.As<RoutePart>().GetPathFromSlug(blogPost.As<RoutePart>().Slug);
            }

            _contentManager.Create(blogPost.ContentItem, VersionOptions.Draft);

            if (publish)
                _blogPostService.Publish(blogPost);
{'fraction_non_alphanumeric': 0.09527272727272727, 'fraction_numerical': 0.004242424242424243, 'mean_word_length': 2.1081182896967414, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4669251', 'n_tokens_mistral': 4253, 'n_tokens_neox': 4033, 'n_words': 698}