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