publish.agi 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. publish.agi
  3. Write a generated static site into a target folder, creating the folder (and
  4. any subfolders the file list needs) first. Used both by Publish, which
  5. targets a subfolder of the user's Personal Site web root, and by
  6. Export To Folder.
  7. Media files are NOT handled here - filelib does text I/O only, so binaries
  8. are copied by the front end through /system/file_system/fileOpr.
  9. POST parameters:
  10. target virtual path of the destination folder
  11. files JSON array of { path, content }, path relative to target
  12. Responds with { "ok": true, "written": n } or an error.
  13. */
  14. requirelib("filelib");
  15. function dirOf(p) {
  16. var i = p.lastIndexOf("/");
  17. if (i <= 0) { return ""; }
  18. return p.substring(0, i);
  19. }
  20. function joinPath(a, b) {
  21. if (a.charAt(a.length - 1) == "/") { a = a.substring(0, a.length - 1); }
  22. if (b.charAt(0) == "/") { b = b.substring(1); }
  23. return a + "/" + b;
  24. }
  25. function main() {
  26. if (typeof (target) == "undefined" || target == "") {
  27. sendJSONResp(JSON.stringify({ error: "Missing target folder" }));
  28. return;
  29. }
  30. var list = [];
  31. if (typeof (files) != "undefined" && files != "") {
  32. try {
  33. list = JSON.parse(files);
  34. } catch (e) {
  35. sendJSONResp(JSON.stringify({ error: "Could not parse the file list" }));
  36. return;
  37. }
  38. }
  39. if (!filelib.fileExists(target)) {
  40. filelib.mkdir(target);
  41. if (!filelib.fileExists(target)) {
  42. sendJSONResp(JSON.stringify({ error: "Could not create " + target }));
  43. return;
  44. }
  45. } else if (!filelib.isDir(target)) {
  46. sendJSONResp(JSON.stringify({ error: "The publish target is a file, not a folder" }));
  47. return;
  48. }
  49. var written = 0;
  50. var failed = [];
  51. for (var i = 0; i < list.length; i++) {
  52. var rel = String(list[i].path || "");
  53. if (rel == "" || rel.indexOf("..") >= 0) {
  54. failed.push(rel);
  55. continue;
  56. }
  57. var sub = dirOf(rel);
  58. if (sub != "") {
  59. var subdir = joinPath(target, sub);
  60. if (!filelib.fileExists(subdir)) {
  61. filelib.mkdir(subdir);
  62. }
  63. }
  64. var dest = joinPath(target, rel);
  65. var ok = filelib.writeFile(dest, String(list[i].content || ""));
  66. if (ok === false) {
  67. failed.push(rel);
  68. } else {
  69. written++;
  70. }
  71. }
  72. if (failed.length > 0) {
  73. sendJSONResp(JSON.stringify({
  74. error: "Could not write " + failed.length + " file(s): " + failed.join(", ")
  75. }));
  76. return;
  77. }
  78. sendJSONResp(JSON.stringify({ ok: true, written: written, target: target }));
  79. }
  80. main();