saveToArozOS.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Chatspace - save a shared-space attachment into ArozOS storage (AGI)
  3. Copies a conversation's file/image item out of the shared space and
  4. into the calling user's own ArozOS file system, so members can keep a
  5. shared attachment in their personal storage instead of (or as well as)
  6. downloading it to their local computer.
  7. POST parameters (injected as VM globals by the AGI gateway):
  8. spaceid - the conversation's shared space ID
  9. itemid - the attachment item ID
  10. dest - optional destination folder vpath (default user:/Desktop)
  11. Response: {"ok": true, "path": "user:/Desktop/name.ext"} or
  12. {"error": "..."}.
  13. */
  14. requirelib("sharedspace");
  15. requirelib("filelib");
  16. function fail(message) {
  17. sendJSONResp(JSON.stringify({ error: message }));
  18. }
  19. //Ensure the destination folder exists, creating it when needed. Falls
  20. //back to the user root (which always exists) if creation fails.
  21. function ensureFolder(folder) {
  22. if (filelib.fileExists(folder) && filelib.isDir(folder)) {
  23. return folder;
  24. }
  25. try {
  26. if (filelib.mkdir(folder) && filelib.isDir(folder)) {
  27. return folder;
  28. }
  29. } catch (e) { }
  30. return "user:/";
  31. }
  32. function main() {
  33. if (typeof spaceid == "undefined" || String(spaceid) == "") {
  34. fail("Missing space ID");
  35. return;
  36. }
  37. if (typeof itemid == "undefined" || String(itemid) == "") {
  38. fail("Missing item ID");
  39. return;
  40. }
  41. var folder = (typeof dest == "undefined" || String(dest) == "") ? "user:/Desktop" : String(dest);
  42. folder = folder.replace(/\/+$/, ""); //drop any trailing slash
  43. folder = ensureFolder(folder);
  44. //Resolve the item's stored name (never trust a client-supplied name)
  45. var items = sharedspace.listItems(String(spaceid));
  46. if (items == null) {
  47. fail("Conversation not found");
  48. return;
  49. }
  50. var found = null;
  51. for (var i = 0; i < items.length; i++) {
  52. if (items[i].itemid == String(itemid)) {
  53. found = items[i];
  54. break;
  55. }
  56. }
  57. if (found == null || found.type == "text" || found.name == "") {
  58. fail("This message has no downloadable file");
  59. return;
  60. }
  61. var name = found.name;
  62. var destVpath = folder + "/" + name;
  63. var ok = sharedspace.saveFileTo(String(spaceid), String(itemid), destVpath);
  64. if (!ok) {
  65. fail("Could not save the file. Check that the folder exists and you can write to it.");
  66. return;
  67. }
  68. sendJSONResp(JSON.stringify({ ok: true, path: destVpath }));
  69. }
  70. main();