PageRenderTime 36ms CodeModel.GetById 2ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/DotNetSlave.BusinessLogic/API/MetaWeblog/MetaWeblogHandler.cs

#
C# | 967 lines | 557 code | 108 blank | 302 comment | 61 complexity | ee5ea7281f13d6223233759b65a2ac54 MD5 | raw file
  1namespace BlogEngine.Core.API.MetaWeblog
  2{
  3    using System;
  4    using System.Collections.Generic;
  5    using System.IO;
  6    using System.Linq;
  7    using System.Web;
  8    using System.Web.Security;
  9
 10    /// <summary>
 11    /// HTTP Handler for MetaWeblog API
 12    /// </summary>
 13    internal class MetaWeblogHandler : IHttpHandler
 14    {
 15        #region Properties
 16
 17        /// <summary>
 18        ///     Gets a value indicating whether another request can use the <see cref = "T:System.Web.IHttpHandler"></see> instance.
 19        /// </summary>
 20        /// <value></value>
 21        /// <returns>true if the <see cref = "T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.</returns>
 22        public bool IsReusable
 23        {
 24            get
 25            {
 26                return false;
 27            }
 28        }
 29
 30        #endregion
 31
 32        #region Implemented Interfaces
 33
 34        #region IHttpHandler
 35
 36        /// <summary>
 37        /// Process the HTTP Request.  Create XMLRPC request, find method call, process it and create response object and sent it back.
 38        /// This is the heart of the MetaWeblog API
 39        /// </summary>
 40        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
 41        public void ProcessRequest(HttpContext context)
 42        {
 43            try
 44            {
 45                var rootUrl = Utils.AbsoluteWebRoot.ToString();
 46                    
 47                // context.Request.Url.ToString().Substring(0, context.Request.Url.ToString().IndexOf("metaweblog.axd"));
 48                var input = new XMLRPCRequest(context);
 49                var output = new XMLRPCResponse(input.MethodName);
 50
 51                Security.ImpersonateUser(input.UserName, input.Password);
 52
 53                // After user credentials have been set, we can use the normal Security
 54                // class to authorize individual requests.
 55                if (!Security.IsAuthenticated)
 56                {
 57                    throw new MetaWeblogException("11", "User authentication failed");
 58                }
 59
 60                switch (input.MethodName)
 61                {
 62                    case "metaWeblog.newPost":
 63                        output.PostID = this.NewPost(
 64                            input.BlogID, input.UserName, input.Password, input.Post, input.Publish);
 65                        break;
 66                    case "metaWeblog.editPost":
 67                        output.Completed = this.EditPost(
 68                            input.PostID, input.UserName, input.Password, input.Post, input.Publish);
 69                        break;
 70                    case "metaWeblog.getPost":
 71                        output.Post = this.GetPost(input.PostID, input.UserName, input.Password);
 72                        break;
 73                    case "metaWeblog.newMediaObject":
 74                        output.MediaInfo = this.NewMediaObject(
 75                            input.BlogID, input.UserName, input.Password, input.MediaObject, context);
 76                        break;
 77                    case "metaWeblog.getCategories":
 78                        output.Categories = this.GetCategories(input.BlogID, input.UserName, input.Password, rootUrl);
 79                        break;
 80                    case "metaWeblog.getRecentPosts":
 81                        output.Posts = this.GetRecentPosts(
 82                            input.BlogID, input.UserName, input.Password, input.NumberOfPosts);
 83                        break;
 84                    case "blogger.getUsersBlogs":
 85                    case "metaWeblog.getUsersBlogs":
 86                        output.Blogs = this.GetUserBlogs(input.AppKey, input.UserName, input.Password, rootUrl);
 87                        break;
 88                    case "blogger.deletePost":
 89                        output.Completed = this.DeletePost(
 90                            input.AppKey, input.PostID, input.UserName, input.Password, input.Publish);
 91                        break;
 92                    case "blogger.getUserInfo":
 93
 94                        // Not implemented.  Not planned.
 95                        throw new MetaWeblogException("10", "The method GetUserInfo is not implemented.");
 96                    case "wp.newPage":
 97                        output.PageID = this.NewPage(
 98                            input.BlogID, input.UserName, input.Password, input.Page, input.Publish);
 99                        break;
100                    case "wp.getPageList":
101                    case "wp.getPages":
102                        output.Pages = this.GetPages(input.BlogID, input.UserName, input.Password);
103                        break;
104                    case "wp.getPage":
105                        output.Page = this.GetPage(input.BlogID, input.PageID, input.UserName, input.Password);
106                        break;
107                    case "wp.editPage":
108                        output.Completed = this.EditPage(
109                            input.BlogID, input.PageID, input.UserName, input.Password, input.Page, input.Publish);
110                        break;
111                    case "wp.deletePage":
112                        output.Completed = this.DeletePage(input.BlogID, input.PageID, input.UserName, input.Password);
113                        break;
114                    case "wp.getAuthors":
115                        output.Authors = this.GetAuthors(input.BlogID, input.UserName, input.Password);
116                        break;
117                    case "wp.getTags":
118                        output.Keywords = this.GetKeywords(input.BlogID, input.UserName, input.Password);
119                        break;
120                }
121
122                output.Response(context);
123            }
124            catch (MetaWeblogException mex)
125            {
126                var output = new XMLRPCResponse("fault");
127                var fault = new MWAFault { faultCode = mex.Code, faultString = mex.Message };
128                output.Fault = fault;
129                output.Response(context);
130            }
131            catch (Exception ex)
132            {
133                var output = new XMLRPCResponse("fault");
134                var fault = new MWAFault { faultCode = "0", faultString = ex.Message };
135                output.Fault = fault;
136                output.Response(context);
137            }
138        }
139
140        #endregion
141
142        #endregion
143
144        #region Methods
145
146        /// <summary>
147        /// Deletes the page.
148        /// </summary>
149        /// <param name="blogId">
150        /// The blog id.
151        /// </param>
152        /// <param name="pageId">
153        /// The page id.
154        /// </param>
155        /// <param name="userName">
156        /// The user name.
157        /// </param>
158        /// <param name="password">
159        /// The password.
160        /// </param>
161        /// <returns>
162        /// The delete page.
163        /// </returns>
164        /// <exception cref="MetaWeblogException">
165        /// </exception>
166        internal bool DeletePage(string blogId, string pageId, string userName, string password)
167        {
168            try
169            {
170                var page = Page.GetPage(new Guid(pageId));
171                if (!page.CanUserDelete)
172                {
173                    throw new MetaWeblogException("11", "User authentication failed");
174                }
175                page.Delete();
176                page.Save();
177            }
178            catch (Exception ex)
179            {
180                throw new MetaWeblogException("15", string.Format("DeletePage failed.  Error: {0}", ex.Message));
181            }
182
183            return true;
184        }
185
186        /// <summary>
187        /// blogger.deletePost method
188        /// </summary>
189        /// <param name="appKey">
190        /// Key from application.  Outdated methodology that has no use here.
191        /// </param>
192        /// <param name="postId">
193        /// post guid in string format
194        /// </param>
195        /// <param name="userName">
196        /// login username
197        /// </param>
198        /// <param name="password">
199        /// login password
200        /// </param>
201        /// <param name="publish">
202        /// mark as published?
203        /// </param>
204        /// <returns>
205        /// Whether deletion was successful or not.
206        /// </returns>
207        internal bool DeletePost(string appKey, string postId, string userName, string password, bool publish)
208        {
209            try
210            {
211                var post = Post.GetPost(new Guid(postId));
212
213                if (!post.CanUserDelete)
214                {
215                    throw new MetaWeblogException("11", "User authentication failed");
216                }
217
218                post.Delete();
219                post.Save();
220            }
221            catch (Exception ex)
222            {
223                throw new MetaWeblogException("12", string.Format("DeletePost failed.  Error: {0}", ex.Message));
224            }
225
226            return true;
227        }
228
229        /// <summary>
230        /// Edits the page.
231        /// </summary>
232        /// <param name="blogId">
233        /// The blog id.
234        /// </param>
235        /// <param name="pageId">
236        /// The page id.
237        /// </param>
238        /// <param name="userName">
239        /// The user name.
240        /// </param>
241        /// <param name="password">
242        /// The password.
243        /// </param>
244        /// <param name="mwaPage">
245        /// The m page.
246        /// </param>
247        /// <param name="publish">
248        /// The publish.
249        /// </param>
250        /// <returns>
251        /// The edit page.
252        /// </returns>
253        internal bool EditPage(
254            string blogId, string pageId, string userName, string password, MWAPage mwaPage, bool publish)
255        {
256            var page = Page.GetPage(new Guid(pageId));
257
258            if (!page.CanUserEdit)
259            {
260                throw new MetaWeblogException("11", "User authentication failed");
261            }
262
263            if (!page.IsPublished && publish)
264            {
265                if (!page.CanPublish())
266                {
267                    throw new MetaWeblogException("11", "Not authorized to publish this Page.");
268                }
269            }
270
271            page.Title = mwaPage.title;
272            page.Content = mwaPage.description;
273            page.Keywords = mwaPage.mt_keywords;
274            page.ShowInList = publish;
275            page.IsPublished = publish;
276            if (mwaPage.pageParentID != "0")
277            {
278                page.Parent = new Guid(mwaPage.pageParentID);
279            }
280
281            page.Save();
282
283            return true;
284        }
285
286        /// <summary>
287        /// metaWeblog.editPost method
288        /// </summary>
289        /// <param name="postId">
290        /// post guid in string format
291        /// </param>
292        /// <param name="userName">
293        /// login username
294        /// </param>
295        /// <param name="password">
296        /// login password
297        /// </param>
298        /// <param name="sentPost">
299        /// struct with post details
300        /// </param>
301        /// <param name="publish">
302        /// mark as published?
303        /// </param>
304        /// <returns>
305        /// 1 if successful
306        /// </returns>
307        internal bool EditPost(string postId, string userName, string password, MWAPost sentPost, bool publish)
308        {
309            var post = Post.GetPost(new Guid(postId));
310
311            if (!post.CanUserEdit)
312            {
313                throw new MetaWeblogException("11", "User authentication failed");
314            }
315
316            string author = String.IsNullOrEmpty(sentPost.author) ? userName : sentPost.author;
317
318            if (!post.IsPublished && publish)
319            {
320                if (!post.CanPublish(author))
321                {
322                    throw new MetaWeblogException("11", "Not authorized to publish this Post.");
323                }
324            }
325
326            post.Author = author;
327            post.Title = sentPost.title;
328            post.Content = sentPost.description;
329            post.IsPublished = publish;
330            post.Slug = sentPost.slug;
331            post.Description = sentPost.excerpt;
332
333            if (sentPost.commentPolicy != string.Empty)
334            {
335                post.HasCommentsEnabled = sentPost.commentPolicy == "1";
336            }
337
338            post.Categories.Clear();
339            foreach (var item in sentPost.categories)
340            {
341                Category cat;
342                if (LookupCategoryGuidByName(item, out cat))
343                {
344                    post.Categories.Add(cat);
345                }
346                else
347                {
348                    // Allowing new categories to be added.  (This breaks spec, but is supported via WLW)
349                    using (var newcat = new Category(item, string.Empty))
350                    {
351                        newcat.Save();
352                        post.Categories.Add(newcat);
353                    }
354                }
355            }
356
357            post.Tags.Clear();
358            foreach (var item in sentPost.tags.Where(item => item != null && item.Trim() != string.Empty))
359            {
360                post.Tags.Add(item);
361            }
362
363            if (sentPost.postDate != new DateTime())
364            {
365                post.DateCreated = sentPost.postDate.AddHours(-BlogSettings.Instance.Timezone);
366            }
367
368            post.Save();
369
370            return true;
371        }
372
373        /// <summary>
374        /// Gets authors.
375        /// </summary>
376        /// <param name="blogId">
377        /// The blog id.
378        /// </param>
379        /// <param name="userName">
380        /// The user name.
381        /// </param>
382        /// <param name="password">
383        /// The password.
384        /// </param>
385        /// <returns>
386        /// A list of authors.
387        /// </returns>
388        internal List<MWAAuthor> GetAuthors(string blogId, string userName, string password)
389        {
390            var authors = new List<MWAAuthor>();
391
392            if (Security.IsAuthorizedTo(Rights.EditOtherUsers))
393            {
394                int total;
395                
396                var users = Membership.Provider.GetAllUsers(0, 999, out total);
397
398                authors.AddRange(
399                    users.Cast<MembershipUser>().Select(
400                        user =>
401                        new MWAAuthor
402                            {
403                                user_id = user.UserName,
404                                user_login = user.UserName,
405                                display_name = user.UserName,
406                                user_email = user.Email,
407                                meta_value = string.Empty
408                            }));
409            }
410            else
411            {
412                // If not able to administer others, just add that user to the options.
413                var single = Membership.GetUser(userName);
414                if (single != null)
415                {
416                    var temp = new MWAAuthor
417                        {
418                            user_id = single.UserName,
419                            user_login = single.UserName,
420                            display_name = single.UserName,
421                            user_email = single.Email,
422                            meta_value = string.Empty
423                        };
424                    authors.Add(temp);
425                }
426            }
427
428            return authors;
429        }
430
431        /// <summary>
432        /// metaWeblog.getCategories method
433        /// </summary>
434        /// <param name="blogId">
435        /// always 1000 in BlogEngine since it is a singlar blog instance
436        /// </param>
437        /// <param name="userName">
438        /// login username
439        /// </param>
440        /// <param name="password">
441        /// login password
442        /// </param>
443        /// <param name="rootUrl">
444        /// The root URL.
445        /// </param>
446        /// <returns>
447        /// array of category structs
448        /// </returns>
449        internal List<MWACategory> GetCategories(string blogId, string userName, string password, string rootUrl)
450        {
451            if (!Security.IsAuthorizedTo(Rights.CreateNewPosts))
452                return new List<MWACategory>();
453
454            return Category.Categories.Select(cat => new MWACategory
455                {
456                    title = cat.Title, description = cat.Title, htmlUrl = cat.AbsoluteLink.ToString(), rssUrl = cat.FeedAbsoluteLink.ToString()
457                }).ToList();
458        }
459
460        /// <summary>
461        /// wp.getTags method
462        /// </summary>
463        /// <param name="blogId">The blog id.</param>
464        /// <param name="userName">Name of the user.</param>
465        /// <param name="password">The password.</param>
466        /// <returns>list of tags</returns>
467        internal List<string> GetKeywords(string blogId, string userName, string password)
468        {
469            var keywords = new List<string>();
470
471            if (!Security.IsAuthorizedTo(Rights.CreateNewPosts))
472                return keywords;
473
474            foreach (var tag in
475                Post.Posts.Where(post => post.IsVisible).SelectMany(post => post.Tags.Where(tag => !keywords.Contains(tag))))
476            {
477                keywords.Add(tag);
478            }
479
480            keywords.Sort();
481
482            return keywords;
483        }
484
485        /// <summary>
486        /// wp.getPage method
487        /// </summary>
488        /// <param name="blogId">
489        /// blogID in string format
490        /// </param>
491        /// <param name="pageId">
492        /// page guid in string format
493        /// </param>
494        /// <param name="userName">
495        /// login username
496        /// </param>
497        /// <param name="password">
498        /// login password
499        /// </param>
500        /// <returns>
501        /// struct with post details
502        /// </returns>
503        internal MWAPage GetPage(string blogId, string pageId, string userName, string password)
504        {
505            var sendPage = new MWAPage();
506            var page = Page.GetPage(new Guid(pageId));
507
508            if (!page.IsVisible)
509            {
510                throw new MetaWeblogException("11", "User authentication failed");
511            }
512
513            sendPage.pageID = page.Id.ToString();
514            sendPage.title = page.Title;
515            sendPage.description = page.Content;
516            sendPage.mt_keywords = page.Keywords;
517            sendPage.pageDate = page.DateCreated;
518            sendPage.link = page.AbsoluteLink.AbsoluteUri;
519            sendPage.mt_convert_breaks = "__default__";
520            sendPage.pageParentID = page.Parent.ToString();
521
522            return sendPage;
523        }
524
525        /// <summary>
526        /// wp.getPages method
527        /// </summary>
528        /// <param name="blogId">
529        /// blogID in string format
530        /// </param>
531        /// <param name="userName">
532        /// login username
533        /// </param>
534        /// <param name="password">
535        /// login password
536        /// </param>
537        /// <returns>
538        /// a list of pages
539        /// </returns>
540        internal List<MWAPage> GetPages(string blogId, string userName, string password)
541        {
542            return Page.Pages.Where(p => p.IsVisible).Select(page => new MWAPage
543                {
544                    pageID = page.Id.ToString(), title = page.Title, description = page.Content, mt_keywords = page.Keywords, pageDate = page.DateCreated, link = page.AbsoluteLink.AbsoluteUri, mt_convert_breaks = "__default__", pageParentID = page.Parent.ToString()
545                }).ToList();
546        }
547
548        /// <summary>
549        /// metaWeblog.getPost method
550        /// </summary>
551        /// <param name="postId">
552        /// post guid in string format
553        /// </param>
554        /// <param name="userName">
555        /// login username
556        /// </param>
557        /// <param name="password">
558        /// login password
559        /// </param>
560        /// <returns>
561        /// struct with post details
562        /// </returns>
563        internal MWAPost GetPost(string postId, string userName, string password)
564        {
565            var sendPost = new MWAPost();
566            var post = Post.GetPost(new Guid(postId));
567
568            if (!post.IsVisible)
569            {
570                throw new MetaWeblogException("11", "User authentication failed");
571            }
572
573            sendPost.postID = post.Id.ToString();
574            sendPost.postDate = post.DateCreated;
575            sendPost.title = post.Title;
576            sendPost.description = post.Content;
577            sendPost.link = post.AbsoluteLink.AbsoluteUri;
578            sendPost.slug = post.Slug;
579            sendPost.excerpt = post.Description;
580            sendPost.commentPolicy = post.HasCommentsEnabled ? "1" : "0";
581            sendPost.publish = post.IsPublished;
582
583            var cats = post.Categories.Select(t => Category.GetCategory(t.Id).ToString()).ToList();
584
585            sendPost.categories = cats;
586
587            var tags = post.Tags.ToList();
588
589            sendPost.tags = tags;
590
591            return sendPost;
592        }
593
594        /// <summary>
595        /// metaWeblog.getRecentPosts method
596        /// </summary>
597        /// <param name="blogId">
598        /// always 1000 in BlogEngine since it is a singlar blog instance
599        /// </param>
600        /// <param name="userName">
601        /// login username
602        /// </param>
603        /// <param name="password">
604        /// login password
605        /// </param>
606        /// <param name="numberOfPosts">
607        /// number of posts to return
608        /// </param>
609        /// <returns>
610        /// array of post structs
611        /// </returns>
612        internal List<MWAPost> GetRecentPosts(string blogId, string userName, string password, int numberOfPosts)
613        {
614            var sendPosts = new List<MWAPost>();
615            var posts = Post.Posts.Where(p => p.IsVisible).ToList();
616
617            // Set End Point
618            var stop = numberOfPosts;
619            if (stop > posts.Count)
620            {
621                stop = posts.Count;
622            }
623
624            foreach (var post in posts.GetRange(0, stop))
625            {
626                var tempPost = new MWAPost
627                    {
628                        postID = post.Id.ToString(),
629                        postDate = post.DateCreated,
630                        title = post.Title,
631                        description = post.Content,
632                        link = post.AbsoluteLink.AbsoluteUri,
633                        slug = post.Slug,
634                        excerpt = post.Description,
635                        commentPolicy = post.HasCommentsEnabled ? string.Empty : "0",
636                        publish = post.IsPublished
637                    };
638
639                var tempCats = post.Categories.Select(t => Category.GetCategory(t.Id).ToString()).ToList();
640
641                tempPost.categories = tempCats;
642
643                var tempTags = post.Tags.ToList();
644
645                tempPost.tags = tempTags;
646
647                sendPosts.Add(tempPost);
648            }
649
650            return sendPosts;
651        }
652
653        /// <summary>
654        /// blogger.getUsersBlogs method
655        /// </summary>
656        /// <param name="appKey">
657        /// Key from application.  Outdated methodology that has no use here.
658        /// </param>
659        /// <param name="userName">
660        /// login username
661        /// </param>
662        /// <param name="password">
663        /// login password
664        /// </param>
665        /// <param name="rootUrl">
666        /// The root URL.
667        /// </param>
668        /// <returns>
669        /// array of blog structs
670        /// </returns>
671        internal List<MWABlogInfo> GetUserBlogs(string appKey, string userName, string password, string rootUrl)
672        {
673            var blogs = new List<MWABlogInfo>();
674
675            var temp = new MWABlogInfo { url = rootUrl, blogID = "1000", blogName = BlogSettings.Instance.Name };
676            blogs.Add(temp);
677
678            return blogs;
679        }
680
681        /// <summary>
682        /// metaWeblog.newMediaObject method
683        /// </summary>
684        /// <param name="blogId">
685        /// always 1000 in BlogEngine since it is a singlar blog instance
686        /// </param>
687        /// <param name="userName">
688        /// login username
689        /// </param>
690        /// <param name="password">
691        /// login password
692        /// </param>
693        /// <param name="mediaObject">
694        /// struct with media details
695        /// </param>
696        /// <param name="request">
697        /// The HTTP request.
698        /// </param>
699        /// <returns>
700        /// struct with url to media
701        /// </returns>
702        internal MWAMediaInfo NewMediaObject(
703            string blogId, string userName, string password, MWAMediaObject mediaObject, HttpContext request)
704        {
705            if (!Security.IsAuthorizedTo(AuthorizationCheck.HasAny, new Rights[]
706                {
707                    Rights.CreateNewPosts,
708                    Rights.CreateNewPages,
709                    Rights.EditOwnPosts,
710                    Rights.EditOwnPages,
711                    Rights.EditOtherUsersPosts,
712                    Rights.EditOtherUsersPages
713                }))
714            {
715                throw new MetaWeblogException("11", "User authentication failed");
716            }    
717
718            var mediaInfo = new MWAMediaInfo();
719
720            var rootPath = string.Format("{0}files/", Blog.CurrentInstance.StorageLocation);
721            var serverPath = request.Server.MapPath(rootPath);
722            var saveFolder = serverPath;
723            var fileName = mediaObject.name;
724            var mediaFolder = string.Empty;
725
726            // Check/Create Folders & Fix fileName
727            if (mediaObject.name.LastIndexOf('/') > -1)
728            {
729                mediaFolder = mediaObject.name.Substring(0, mediaObject.name.LastIndexOf('/'));
730                saveFolder += mediaFolder;
731                mediaFolder += "/";
732                saveFolder = saveFolder.Replace('/', Path.DirectorySeparatorChar);
733                fileName = mediaObject.name.Substring(mediaObject.name.LastIndexOf('/') + 1);
734            }
735            else
736            {
737                if (saveFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
738                {
739                    saveFolder = saveFolder.Substring(0, saveFolder.Length - 1);
740                }
741            }
742
743            if (!Directory.Exists(saveFolder))
744            {
745                Directory.CreateDirectory(saveFolder);
746            }
747
748            saveFolder += Path.DirectorySeparatorChar;
749
750            if (File.Exists(saveFolder + fileName))
751            {
752                // Find unique fileName
753                for (var count = 1; count < 30000; count++)
754                {
755                    var tempFileName = fileName.Insert(fileName.LastIndexOf('.'), string.Format("_{0}", count));
756                    if (File.Exists(saveFolder + tempFileName))
757                    {
758                        continue;
759                    }
760
761                    fileName = tempFileName;
762                    break;
763                }
764            }
765
766            // Save File
767            using (var fs = new FileStream(saveFolder + fileName, FileMode.Create))
768            using (var bw = new BinaryWriter(fs))
769            {
770                bw.Write(mediaObject.bits);
771                bw.Close();
772            }
773
774            // Set Url
775            var rootUrl = Utils.AbsoluteWebRoot.ToString();
776            if (BlogSettings.Instance.RequireSslMetaWeblogApi)
777            {
778                rootUrl = rootUrl.Replace("https://", "http://");
779            }
780
781            var mediaType = mediaObject.type;
782            if (mediaType.IndexOf('/') > -1)
783            {
784                mediaType = mediaType.Substring(0, mediaType.IndexOf('/'));
785            }
786
787            switch (mediaType)
788            {
789                case "image":
790                case "notsent":
791                    // If there wasn't a type, let's pretend it is an image.  (Thanks Zoundry.  This is for you.)
792                    rootUrl += "image.axd?picture=";
793                    break;
794                default:
795                    rootUrl += "file.axd?file=";
796                    break;
797            }
798
799            mediaInfo.url = rootUrl + mediaFolder + fileName;
800            return mediaInfo;
801        }
802
803        /// <summary>
804        /// wp.newPage method
805        /// </summary>
806        /// <param name="blogId">blogID in string format</param>
807        /// <param name="userName">login username</param>
808        /// <param name="password">login password</param>
809        /// <param name="mwaPage">The mwa page.</param>
810        /// <param name="publish">if set to <c>true</c> [publish].</param>
811        /// <returns>The new page.</returns>
812        internal string NewPage(string blogId, string userName, string password, MWAPage mwaPage, bool publish)
813        {
814            if (!Security.IsAuthorizedTo(Rights.CreateNewPages))
815            {
816                throw new MetaWeblogException("11", "User authentication failed");
817            }
818
819            var page = new Page
820                {
821                    Title = mwaPage.title,
822                    Content = mwaPage.description,
823                    Description = string.Empty,
824                    Keywords = mwaPage.mt_keywords
825                };
826
827            if (publish)
828            {
829                if (!page.CanPublish())
830                {
831                    throw new MetaWeblogException("11", "Not authorized to publish this Page.");
832                }
833            }
834
835            if (mwaPage.pageDate != new DateTime())
836            {
837                page.DateCreated = mwaPage.pageDate;
838            }
839
840            page.ShowInList = publish;
841            page.IsPublished = publish;
842            if (mwaPage.pageParentID != "0")
843            {
844                page.Parent = new Guid(mwaPage.pageParentID);
845            }
846
847            page.Save();
848
849            return page.Id.ToString();
850        }
851
852        /// <summary>
853        /// metaWeblog.newPost method
854        /// </summary>
855        /// <param name="blogId">
856        /// always 1000 in BlogEngine since it is a singlar blog instance
857        /// </param>
858        /// <param name="userName">
859        /// login username
860        /// </param>
861        /// <param name="password">
862        /// login password
863        /// </param>
864        /// <param name="sentPost">
865        /// struct with post details
866        /// </param>
867        /// <param name="publish">
868        /// mark as published?
869        /// </param>
870        /// <returns>
871        /// postID as string
872        /// </returns>
873        internal string NewPost(string blogId, string userName, string password, MWAPost sentPost, bool publish)
874        {
875            if (!Security.IsAuthorizedTo(Rights.CreateNewPosts))
876            {
877                throw new MetaWeblogException("11", "User authentication failed");
878            }
879
880            string author = String.IsNullOrEmpty(sentPost.author) ? userName : sentPost.author;
881
882            var post = new Post
883                {
884                    Author = author,
885                    Title = sentPost.title,
886                    Content = sentPost.description,
887                    IsPublished = publish,
888                    Slug = sentPost.slug,
889                    Description = sentPost.excerpt
890                };
891
892            if (publish)
893            {
894                if (!post.CanPublish(author))
895                {
896                    throw new MetaWeblogException("11", "Not authorized to publish this Post.");
897                }
898            }
899
900            if (sentPost.commentPolicy != string.Empty)
901            {
902                post.HasCommentsEnabled = sentPost.commentPolicy == "1";
903            }
904
905            post.Categories.Clear();
906            foreach (var item in sentPost.categories)
907            {
908                Category cat;
909                if (LookupCategoryGuidByName(item, out cat))
910                {
911                    post.Categories.Add(cat);
912                }
913                else
914                {
915                    // Allowing new categories to be added.  (This breaks spec, but is supported via WLW)
916                    var newcat = new Category(item, string.Empty);
917                    newcat.Save();
918                    post.Categories.Add(newcat);
919                }
920            }
921
922            post.Tags.Clear();
923            foreach (var item in sentPost.tags.Where(item => item != null && item.Trim() != string.Empty))
924            {
925                post.Tags.Add(item);
926            }
927
928            if (sentPost.postDate != new DateTime())
929            {
930                post.DateCreated = sentPost.postDate;
931            }
932
933            post.Save();
934
935            return post.Id.ToString();
936        }
937
938        /// <summary>
939        /// Returns Category Guid from Category name.
940        /// </summary>
941        /// <remarks>
942        /// Reverse dictionary lookups are ugly.
943        /// </remarks>
944        /// <param name="name">
945        /// The category name.
946        /// </param>
947        /// <param name="cat">
948        /// The category.
949        /// </param>
950        /// <returns>
951        /// Whether the category was found or not.
952        /// </returns>
953        private static bool LookupCategoryGuidByName(string name, out Category cat)
954        {
955            cat = new Category();
956            foreach (var item in Category.Categories.Where(item => item.Title == name))
957            {
958                cat = item;
959                return true;
960            }
961
962            return false;
963        }
964
965        #endregion
966    }
967}