publish.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Publish.js
  3. This script publish the blog post object to a static HTML into the webroot
  4. Require paramter:
  5. filepath //The filepath of the post object
  6. webroot //The webroot of the current ArozOS user
  7. */
  8. requirelib("filelib");
  9. requirelib("appdata");
  10. includes("config.js");
  11. includes("helper.js");
  12. includes("indexManager.js");
  13. //Inject content into template
  14. function applyTemplate(templateFilepath, templateObjects){
  15. var templateContent = appdata.readFile(templateFilepath);
  16. if (templateContent == false){
  17. return false;
  18. }
  19. for (var i = 0; i < templateObjects.length; i++){
  20. var thisObject = templateObjects[i];
  21. templateContent = templateContent.split("{{" + thisObject.key + "}}").join(thisObject.value);
  22. }
  23. return templateContent;
  24. }
  25. //Main function to publish the file to webroot
  26. function publish(filepath, webroot){
  27. //Check if the blog post object exists
  28. if (!filelib.fileExists(filepath)){
  29. retrunErrorObject("Given post not exists: " + filepath);
  30. return
  31. }
  32. //Get its content. Validate it correctless
  33. var content = filelib.readFile(filepath);
  34. if (typeof(content) == "undefined" || typeof(content) == "null" || content == ""){
  35. retrunErrorObject("Invalid blog post object");
  36. return
  37. }
  38. //Get the modification time of the file as blog date
  39. var modtime = filelib.mtime(filepath, false);
  40. var blogInfo = loadBlogInfo();
  41. var blogObject = JSON.parse(content);
  42. //Apply template
  43. var renderedPage = applyTemplate("Blog/template/post.html", [
  44. {key: "blog_title", value: blogInfo[0]},
  45. {key: "blog_subtitle", value: blogInfo[1]},
  46. {key: "post_date", value: modtime},
  47. {key: "post_title", value: blogObject.Title},
  48. {key: "post_tags", value: blogObject.Tags.join(", ")},
  49. {key: "post_content", value: blogObject.Content},
  50. {key: "footer", value: loadFooter()}
  51. ]);
  52. //Create the posts folder if not exists
  53. if (!filelib.fileExists(webroot + "/blog/posts/")){
  54. filelib.mkdir(webroot + "/blog/posts/");
  55. }
  56. //Write out to the user web root
  57. webroot = filepathClean(webroot);
  58. var postObjectName = filepath.split("/").pop();
  59. postObjectName = postObjectName.replace(".json", "");
  60. var targetPostLocation = webroot + "/blog/posts/" + postObjectName + ".html";
  61. filelib.writeFile(targetPostLocation, renderedPage);
  62. //Update the index file
  63. injectTitleIntoPostList(webroot, postObjectName);
  64. }
  65. if (typeof(runAsFunc) == "undefined"){
  66. publish(filepath, webroot);
  67. }