ao_module.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. /*
  2. ArOZ Online Module Javascript Wrapper
  3. This is a wrapper for module developers to access system API easier and need not to dig through the source code.
  4. Basically: Write less do more (?)
  5. WARNING! SOME FUNCTION ARE NOT COMPATIBILE WITH PREVIOUS VERSION OF AO_MODULE.JS.
  6. PLEASE REFER TO THE SYSTEM DOCUMENTATION FOR MORE INFORMATION.
  7. *** Please include this javascript file with relative path instead of absolute path.
  8. E.g. ../script/ao_module.js (OK)
  9. /script/ao_module.js (NOT OK)
  10. */
  11. var ao_module_virtualDesktop = false;
  12. try{
  13. ao_module_virtualDesktop = !(!parent.isDesktopMode);
  14. }catch(ex){
  15. //Running ArozOS inside iframe for some reason
  16. console.log("CORS Access Error. Entering compatibility mode with virtual desktop mode disabled.");
  17. }
  18. var ao_root = null;
  19. //Get the current windowID if in Virtual Desktop Mode, return false if VDI is not detected
  20. var ao_module_windowID = false;
  21. var ao_module_parentID = false;
  22. var ao_module_callback = false;
  23. var ao_module_ime = false;
  24. if (ao_module_virtualDesktop)ao_module_windowID = $(window.frameElement).parent().parent().attr("windowId");
  25. if (ao_module_virtualDesktop)ao_module_parentID = $(window.frameElement).parent().parent().attr("parent");
  26. if (ao_module_virtualDesktop)ao_module_callback = $(window.frameElement).parent().parent().attr("callback");
  27. if (ao_module_virtualDesktop)ao_module_parentURL = $(window.frameElement).parent().find("iframe").attr("src");
  28. ao_root = ao_module_getAORootFromScriptPath();
  29. /*
  30. Event bindings
  31. The following events are required for ao_module to operate normally
  32. under Web Desktop Mode.
  33. */
  34. document.addEventListener("DOMContentLoaded", function() {
  35. if (ao_module_virtualDesktop){
  36. if (parent.window.ime == null){
  37. return;
  38. }
  39. //Add window focus handler
  40. document.addEventListener("mousedown", function(event) {
  41. //When click on this document, focus this
  42. ao_module_focus();
  43. if (event.target.tagName == "INPUT" || event.target.tagName == "TEXTAREA"){
  44. }else{
  45. if (parent.window.ime.focus != null){
  46. if (ao_module_ime){
  47. //This is clicking on ime windows. Do not change focus
  48. }else{
  49. parent.window.ime.focus = null;
  50. }
  51. }
  52. }
  53. }, true);
  54. //Add IME registration handler
  55. var inputFields = document.querySelectorAll("input,textarea");
  56. for (var i = 0; i < inputFields.length; i++){
  57. if ($(inputFields[i]).attr("type") != undefined){
  58. var thisType = $(inputFields[i]).attr("type");
  59. if ((thisType == "text" || thisType =="search" || thisType =="url")){
  60. //Supported types of input
  61. ao_module_bindCustomIMEEvents(inputFields[i]);
  62. }else{
  63. //Not supported type of inputs
  64. }
  65. }else{
  66. //text area
  67. ao_module_bindCustomIMEEvents(inputFields[i]);
  68. }
  69. }
  70. }
  71. /*
  72. //Load html2canvas
  73. if ($){
  74. $.getScript(ao_root + "script/html2canvas.min.js", function() {
  75. console.log("Html2canvas loaded")
  76. });
  77. }
  78. */
  79. });
  80. /*
  81. Startup Section Script
  82. These functions handle the startup of an ao_module and adapt them into the
  83. standard arozos desktop eco-system api
  84. */
  85. //Function handle to bind custom IME events
  86. function ao_module_bindCustomIMEEvents(object){
  87. parent.bindObjectToIMEEvents(object);
  88. }
  89. function ao_module_screenshot(callback){
  90. html2canvas(document.querySelector("body")).then(screenshot => {
  91. return callback(screenshot);
  92. });
  93. }
  94. //Get the ao_root from script includsion path
  95. function ao_module_getAORootFromScriptPath(){
  96. var possibleRoot = "";
  97. $("script").each(function(){
  98. if (this.hasAttribute("src") && $(this).attr("src").includes("ao_module.js")){
  99. var tmp = $(this).attr("src");
  100. tmp = tmp.split("script/ao_module.js");
  101. possibleRoot = tmp[0];
  102. }
  103. });
  104. return possibleRoot;
  105. }
  106. //Get the input filename and filepath from the window hash paramter
  107. function ao_module_loadInputFiles(){
  108. try{
  109. if (window.location.hash.length == 0){
  110. return null;
  111. }
  112. var inputFileInfo = window.location.hash.substring(1,window.location.hash.length);
  113. inputFileInfo = JSON.parse(decodeURIComponent(inputFileInfo));
  114. if (inputFileInfo.length == 0){
  115. return null;
  116. }
  117. return inputFileInfo
  118. }catch{
  119. return null;
  120. }
  121. }
  122. //Set the ao_module window to fixed size (not allowing resize)
  123. function ao_module_setFixedWindowSize(){
  124. if (!ao_module_virtualDesktop){
  125. return;
  126. }
  127. parent.setFloatWindowResizePolicy(ao_module_windowID, false);
  128. }
  129. //Restore a float window to be resizble
  130. function ao_module_setResizableWindowSize(){
  131. if (!ao_module_virtualDesktop){
  132. return;
  133. }
  134. parent.setFloatWindowResizePolicy(ao_module_windowID, true);
  135. }
  136. //Update the window size of the given float window object
  137. function ao_module_setWindowSize(width, height){
  138. if (!ao_module_virtualDesktop){
  139. return;
  140. }
  141. parent.setFloatWindowSize(ao_module_windowID, width, height)
  142. }
  143. //Set the minimum size the user can resize this float window to, in px.
  144. //Pass 0 (or leave out) a dimension to drop back to the default minimum.
  145. //A window smaller than the new minimum grows to fit it.
  146. function ao_module_setWindowMinSize(width=0, height=0){
  147. if (!ao_module_virtualDesktop || typeof parent.setFloatWindowMinSize != "function"){
  148. return;
  149. }
  150. parent.setFloatWindowMinSize(ao_module_windowID, width, height);
  151. }
  152. //Update the floatWindow title
  153. function ao_module_setWindowTitle(newTitle){
  154. if (!ao_module_virtualDesktop){
  155. document.title = newTitle;
  156. return;
  157. }
  158. parent.setFloatWindowTitle(ao_module_windowID, newTitle);
  159. }
  160. //Set new window theme, default dark, support {dark/white}
  161. function ao_module_setWindowTheme(newtheme="dark"){
  162. if (!ao_module_virtualDesktop){
  163. return;
  164. }
  165. parent.setFloatWindowTheme(ao_module_windowID, newtheme);
  166. }
  167. // ao_module_getSystemThemeColor(callback) => Get the global theme color of current system, and return the color value in callback function.
  168. // The value is the raw preference: "darkTheme" or "whiteTheme" (not "dark" / "light" like ao_module_onThemeChanged).
  169. // The backend answers "whiteTheme" for a user who has not picked a theme yet.
  170. function ao_module_getSystemThemeColor(callback){
  171. $.get("../../system/file_system/preference?key=file_explorer/theme",function(data){
  172. callback(data);
  173. });
  174. }
  175. // ao_module_setSystemThemeColor(color, callback) => Set the global theme color of current system, and return the result in callback function if provided.
  176. function ao_module_setSystemThemeColor(color, callback=undefined){
  177. $.ajax({
  178. url:"../../system/file_system/preference?key=file_explorer/theme&value=" + color,
  179. success: function(data){
  180. if (data.error !== undefined){
  181. console.log(data);
  182. }
  183. if (callback !== undefined){
  184. callback(data);
  185. }
  186. }
  187. });
  188. }
  189. //Check if there are any windows with the same path.
  190. //If yes, replace its hash content and reload to the new one and close the current floatWindow
  191. function ao_module_makeSingleInstance(){
  192. $(window.parent.document).find(".floatWindow").each(function(){
  193. if ($(this).attr("windowid") == ao_module_windowID){
  194. return
  195. }
  196. var currentPath = window.location.pathname;
  197. if ("/" + $(this).find("iframe").attr('src').split("#").shift() == currentPath){
  198. //Another instance already running. Replace it with the current path
  199. $(this).find("iframe").attr('src', window.location.pathname.substring(1) + window.location.hash);
  200. $(this).find("iframe")[0].contentWindow.location.reload();
  201. //Move the other instant to top
  202. var targetfw = parent.getFloatWindowByID($(this).attr("windowid"))
  203. parent.MoveFloatWindowToTop(targetfw);
  204. //Close the instance
  205. ao_module_close();
  206. return true
  207. }
  208. });
  209. return false
  210. }
  211. //Use for cross frame communication, example:
  212. //let targetOpeningInstances = ao_module_getInstanceByPath("NotepadA/index.html")
  213. function ao_module_getInstanceByPath(matchingPath){
  214. let targetInstance = "";
  215. $(window.parent.document).find(".floatWindow").each(function(){
  216. if ($(this).attr("windowid") == ao_module_windowID){
  217. return
  218. }
  219. let thisfwPath = $(this).find("iframe").attr('src').split("#").shift();
  220. if (thisfwPath == matchingPath){
  221. targetInstance = $(this).attr("windowid");
  222. }
  223. });
  224. if (targetInstance == ""){
  225. return null;
  226. }
  227. return parent.getFloatWindowByID(targetInstance);
  228. }
  229. //Close the current window
  230. function ao_module_close(){
  231. ao_module_closeHandler();
  232. }
  233. //Close handler for WebApp special handling of ao_module_close()
  234. function ao_module_closeHandler(){
  235. if (!ao_module_virtualDesktop){
  236. window.close('','_parent','');
  237. window.location.href = ao_root + "SystemAO/closeTabInsturction.html";
  238. return;
  239. }
  240. parent.closeFwProcess(ao_module_windowID);
  241. }
  242. //Focus this floatWindow
  243. function ao_module_focus(){
  244. parent.MoveFloatWindowToTop(parent.getFloatWindowByID(ao_module_windowID));
  245. }
  246. //Set the floatWindow to top most mode
  247. function ao_module_setTopMost(){
  248. parent.PinFloatWindowToTopMostMode(parent.getFloatWindowByID(ao_module_windowID));
  249. }
  250. //Unset the floatWindow top most mode
  251. function ao_module_unsetTopMost(){
  252. parent.UnpinFloatWindowFromTopMostMode(parent.getFloatWindowByID(ao_module_windowID));
  253. }
  254. //Popup a file selection window for upload
  255. //callback(files) must be a window scoped global function of the calling window.
  256. //do not use inline callback function like ao_module_selectFiles(function(files){...}) as it will not work,
  257. //instead, define a global function first and then pass the function name as string to the callback parameter, e.g. ao_module_selectFiles("myCallbackFunction", "file", "*", true);
  258. function ao_module_selectFiles(callback, fileType="file", accept="*", allowMultiple=false){
  259. var input = document.createElement('input');
  260. input.type = fileType;
  261. input.multiple = allowMultiple;
  262. input.accept = accept;
  263. input.onchange = e => {
  264. var files = e.target.files;
  265. callback(files);
  266. }
  267. input.click();
  268. }
  269. //Open a path with File Manager, optional highligh filename
  270. function ao_module_openPath(path, filename=undefined){
  271. //Trim away the last / if exists
  272. if (path.substr(path.length - 1, 1) == "/"){
  273. path = path.substr(0, path.length - 1);
  274. }
  275. if (filename == undefined){
  276. if (ao_module_virtualDesktop){
  277. parent.newFloatWindow({
  278. url: "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(path),
  279. appicon: "SystemAO/file_system/img/small_icon.png",
  280. width:1080,
  281. height:580,
  282. title: "File Manager"
  283. });
  284. }else{
  285. window.open(ao_root + "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(path))
  286. }
  287. }else{
  288. var fileObject = [{
  289. filepath: path + "/" + filename,
  290. filename: filename,
  291. }];
  292. if (ao_module_virtualDesktop){
  293. parent.newFloatWindow({
  294. url: "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(JSON.stringify(fileObject)),
  295. appicon: "SystemAO/file_system/img/small_icon.png",
  296. width:1080,
  297. height:580,
  298. title: "File Manager"
  299. });
  300. }else{
  301. window.open(ao_root + "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(JSON.stringify(fileObject)))
  302. }
  303. }
  304. }
  305. /*
  306. ao_module_requestSchedulerPermission(options, callback)
  307. Show a permission dialog asking the user to allow the calling app to register
  308. a background scheduled task on their behalf.
  309. options = {
  310. appName: "My App", // Display name of the requesting app
  311. appIcon: "MyApp/img/icon.png", // Optional icon path (relative to web root)
  312. taskName: "MyApp_DailySync", // Unique task identifier (max 32 chars)
  313. scriptName: "cron.agi", // Filename inside the app folder (next to init.agi); defaults to "cron.agi"
  314. interval: 86400, // Execution interval in seconds
  315. base: 0, // Base unix timestamp (0 = now)
  316. description: "Daily sync task" // Optional description shown in popup
  317. }
  318. callback(result):
  319. result.allowed => true if the user approved and the scheduler was registered
  320. result.taskName => the task name that was registered
  321. */
  322. function ao_module_requestSchedulerPermission(options, callback) {
  323. if (!options || !options.taskName) {
  324. console.error("[ao_module] requestSchedulerPermission: missing required options (taskName)");
  325. if (typeof callback === 'function') callback({allowed: false, error: "invalid options"});
  326. return;
  327. }
  328. if (!options.scriptName) options.scriptName = "cron.agi";
  329. if (!options.appName) options.appName = document.title || "Application";
  330. if (!options.interval) options.interval = 86400;
  331. if (!options.base) options.base = Math.floor(Date.now() / 1000);
  332. if (!options.description) options.description = "";
  333. var callbackFnName = "_spCallback_" + Date.now();
  334. window[callbackFnName] = function(result) {
  335. delete window[callbackFnName];
  336. if (typeof callback === 'function') callback(result);
  337. };
  338. var encoded = encodeURIComponent(JSON.stringify(options));
  339. var url = "SystemAO/arsm/scheduler_permission.html#" + encoded;
  340. if (ao_module_virtualDesktop) {
  341. ao_module_newfw({
  342. url: url,
  343. width: 400,
  344. height: 480,
  345. appicon: "SystemAO/arsm/img/scheduler.png",
  346. title: "Scheduler Permission",
  347. parent: ao_module_windowID,
  348. callback: callbackFnName
  349. });
  350. } else {
  351. // Non-desktop mode: open popup window and poll localStorage
  352. var listenerKey = "spResult_" + Date.now();
  353. var popupWin = window.open(ao_root + url, "_blank", "width=400,height=480");
  354. var pollInterval = setInterval(function() {
  355. var stored = localStorage.getItem(listenerKey);
  356. if (stored !== null && stored !== undefined) {
  357. clearInterval(pollInterval);
  358. localStorage.removeItem(listenerKey);
  359. try {
  360. var result = JSON.parse(stored);
  361. if (typeof callback === 'function') callback(result);
  362. } catch(e) {
  363. if (typeof callback === 'function') callback({allowed: false});
  364. }
  365. }
  366. if (popupWin && popupWin.closed) {
  367. clearInterval(pollInterval);
  368. if (typeof callback === 'function') callback({allowed: false});
  369. }
  370. }, 300);
  371. }
  372. }
  373. //Open a particular tab using System Setting module. Require
  374. //1) Setting Group
  375. //2) Setting Name
  376. function ao_module_openSetting(group, name){
  377. var requestObject = {
  378. group: group,
  379. name: name
  380. }
  381. requestObject = encodeURIComponent(JSON.stringify(requestObject));
  382. var openURL = "SystemAO/system_setting/index.html#" + requestObject;
  383. if (ao_module_virtualDesktop){
  384. ao_module_newfw({
  385. url: openURL,
  386. width: 1080,
  387. height: 580,
  388. appicon: "SystemAO/system_setting/img/small_icon.png",
  389. title: "System Setting"
  390. });
  391. }else{
  392. window.open(ao_root + openURL)
  393. }
  394. }
  395. /*
  396. ao_module_newfw(launchConfig) => Create a new floatWindow object from the given paramters
  397. Most basic usage: (With auto assign UID, size and location)
  398. ao_module_newfw({
  399. url: "Dummy/index.html",
  400. title: "Dummy Module",
  401. appicon: "Dummy/img/icon.png"
  402. });
  403. Example usage that involve all configs:
  404. ao_module_newfw({
  405. url: "Dummy/index.html",
  406. uid: "CustomUUID",
  407. width: 1024,
  408. height: 768,
  409. appicon: "Dummy/img/icon.png",
  410. title: "Dummy Module",
  411. left: 100,
  412. top: 100,
  413. minWidth: 400, //optional, smallest width the user can resize to
  414. minHeight: 300, //optional, smallest height the user can resize to
  415. parent: ao_module_windowID,
  416. callback: "childCallbackHandler"
  417. });
  418. */
  419. function ao_module_newfw(launchConfig){
  420. if (launchConfig["parent"] == undefined){
  421. launchConfig["parent"] = ao_module_windowID;
  422. }
  423. if (ao_module_virtualDesktop){
  424. parent.newFloatWindow(launchConfig);
  425. }else{
  426. window.open(ao_root + launchConfig.url);
  427. }
  428. }
  429. /*
  430. ao_module_startFileOperation(oprConfig)
  431. Start a move / copy / zip / unzip operation and show it in the system wide
  432. file operation dialog. There is only ever one of those dialogs open: when it
  433. is already running the operation is handed over to it instead of opening
  434. another window with another status connection.
  435. Example:
  436. ao_module_startFileOperation({
  437. opr: "copy", //move / copy / zip / unzip / unzipAndOpen
  438. src: ["user:/Desktop/test.txt"], //Source file list
  439. dest: "user:/Documents/", //Destination folder
  440. overwriteMode: "ask", //skip / overwrite / keep / ask (optional)
  441. callbackWindowID: ao_module_windowID, //Window to notify when done (optional)
  442. callbackFunction: "refreshList()" //Function to call on that window (optional)
  443. });
  444. */
  445. function ao_module_startFileOperation(oprConfig){
  446. if (ao_module_virtualDesktop){
  447. parent.startFileOperation(oprConfig);
  448. return;
  449. }
  450. //Standalone mode. Reuse the named window opened by the previous operation.
  451. var dialogURL = ao_root + "SystemAO/file_system/file_operation.html#" + encodeURIComponent(JSON.stringify(oprConfig));
  452. var existingDialog = null;
  453. try {
  454. existingDialog = window.open("", "arozFileOperationDialog");
  455. } catch(ex) {
  456. existingDialog = null;
  457. }
  458. if (existingDialog != null && typeof existingDialog.addFileOperation == "function"){
  459. existingDialog.addFileOperation(oprConfig);
  460. existingDialog.focus();
  461. return;
  462. }
  463. window.open(dialogURL, "arozFileOperationDialog", "width=500,height=470");
  464. }
  465. /*
  466. File Selector Path Memory
  467. Remembers the directory the user last worked in for each web app, so the file
  468. selector re-opens where the user left off instead of at the hardcoded path the
  469. app was written with. Everything lives in ONE localStorage entry
  470. (ao_module_fs_pathmemory) shaped like:
  471. {
  472. "version": 1,
  473. "scopes": {
  474. "Cine Studio": {
  475. "last": "user:/Desktop/myworkspace/", //Last dir used anywhere in this app
  476. "actions": {"export": "user:/Desktop/out/"},//Last dir used per action
  477. "ts": 1700000000000 //For LRU eviction
  478. }
  479. }
  480. }
  481. The scope name defaults to the web app folder name (e.g. "Cine Studio") and can
  482. be overridden with ao_module_setPathMemoryScope() for apps that want to share or
  483. split their memory.
  484. */
  485. var ao_module_pathMemoryStorageKey = "ao_module_fs_pathmemory";
  486. var ao_module_pathMemoryDefaultAction = "default";
  487. var ao_module_pathMemoryMaxScopes = 64; //Evict least recently used scopes past this
  488. var ao_module_pathMemoryScopeOverride = null;
  489. //Override the auto-derived path memory scope of this window, e.g. "Office"
  490. function ao_module_setPathMemoryScope(scopeName){
  491. if (typeof(scopeName) == "string" && scopeName.trim() != ""){
  492. ao_module_pathMemoryScopeOverride = scopeName.trim();
  493. }else{
  494. ao_module_pathMemoryScopeOverride = null;
  495. }
  496. }
  497. //Get the path memory scope of this window. Derived from the web app folder name
  498. //by trimming the ArozOS web root prefix off the current pathname using ao_root.
  499. function ao_module_getPathMemoryScope(){
  500. if (ao_module_pathMemoryScopeOverride != null){
  501. return ao_module_pathMemoryScopeOverride;
  502. }
  503. try{
  504. var segments = (window.location.pathname || "").split("/").filter(function(s){
  505. return s.length > 0;
  506. });
  507. //Drop the trailing filename, if the URL carries one
  508. if (segments.length > 0 && segments[segments.length - 1].indexOf(".") > 0){
  509. segments.pop();
  510. }
  511. //ao_root ("../../") tells us how deep this page sits inside the web root,
  512. //so the app folder survives ArozOS being hosted under a sub-path
  513. var depth = ((ao_root || "").match(/\.\.\//g) || []).length;
  514. if (depth > 0 && segments.length >= depth){
  515. segments = segments.slice(segments.length - depth);
  516. }
  517. if (segments.length > 0){
  518. return decodeURIComponent(segments[0]);
  519. }
  520. }catch(ex){
  521. //Malformed URL. Fall through to the shared scope
  522. }
  523. return "default";
  524. }
  525. //Read the whole path memory object out of localStorage
  526. function ao_module_readPathMemory(){
  527. try{
  528. var raw = localStorage.getItem(ao_module_pathMemoryStorageKey);
  529. if (raw == null || raw == ""){
  530. return {version: 1, scopes: {}};
  531. }
  532. var parsed = JSON.parse(raw);
  533. if (parsed == null || typeof(parsed) != "object" || typeof(parsed.scopes) != "object" || parsed.scopes == null){
  534. return {version: 1, scopes: {}};
  535. }
  536. return parsed;
  537. }catch(ex){
  538. //Corrupted entry. Start over rather than breaking the file selector
  539. return {version: 1, scopes: {}};
  540. }
  541. }
  542. //Write the whole path memory object back, evicting the oldest scopes if needed
  543. function ao_module_writePathMemory(memory){
  544. try{
  545. var names = Object.keys(memory.scopes);
  546. if (names.length > ao_module_pathMemoryMaxScopes){
  547. names.sort(function(a, b){
  548. return (memory.scopes[a].ts || 0) - (memory.scopes[b].ts || 0);
  549. });
  550. var overflow = names.length - ao_module_pathMemoryMaxScopes;
  551. for (var i = 0; i < overflow; i++){
  552. delete memory.scopes[names[i]];
  553. }
  554. }
  555. localStorage.setItem(ao_module_pathMemoryStorageKey, JSON.stringify(memory));
  556. }catch(ex){
  557. //Storage full or blocked (private mode). Path memory is best effort only
  558. console.log("[ao_module] Unable to save file selector path memory: " + ex);
  559. }
  560. }
  561. /*
  562. ao_module_getLastUsedPath(actionKey, scopeName)
  563. Return the directory this app last used, or "" if nothing has been recorded yet.
  564. Passing an actionKey returns that action's directory and falls back to the app
  565. wide one; passing false as the actionKey returns the app wide one directly.
  566. */
  567. function ao_module_getLastUsedPath(actionKey=ao_module_pathMemoryDefaultAction, scopeName=undefined){
  568. var scope = ao_module_readPathMemory().scopes[scopeName || ao_module_getPathMemoryScope()];
  569. if (scope == undefined){
  570. return "";
  571. }
  572. if (actionKey !== false && actionKey != undefined && scope.actions != undefined &&
  573. typeof(scope.actions[actionKey]) == "string"){
  574. return scope.actions[actionKey];
  575. }
  576. return (typeof(scope.last) == "string") ? scope.last : "";
  577. }
  578. /*
  579. ao_module_setLastUsedPath(path, actionKey, scopeName)
  580. Record a directory as the last used one for this app. The file selector calls
  581. this by itself, apps only need it when they open files through another route
  582. (e.g. a drag and drop or a hardcoded recent-file list) and want the selector to
  583. follow along.
  584. */
  585. function ao_module_setLastUsedPath(path, actionKey=ao_module_pathMemoryDefaultAction, scopeName=undefined){
  586. if (typeof(path) != "string" || path.trim() == ""){
  587. return false;
  588. }
  589. path = path.trim();
  590. if (path.substr(path.length - 1, 1) != "/"){
  591. path = path + "/";
  592. }
  593. var memory = ao_module_readPathMemory();
  594. var name = scopeName || ao_module_getPathMemoryScope();
  595. if (memory.scopes[name] == undefined){
  596. memory.scopes[name] = {last: "", actions: {}};
  597. }
  598. if (memory.scopes[name].actions == undefined){
  599. memory.scopes[name].actions = {};
  600. }
  601. memory.scopes[name].last = path;
  602. memory.scopes[name].ts = new Date().getTime();
  603. if (actionKey !== false && actionKey != undefined && actionKey != ""){
  604. memory.scopes[name].actions[actionKey] = path;
  605. }
  606. ao_module_writePathMemory(memory);
  607. return true;
  608. }
  609. //Forget the last used path of one action, or of the whole app when actionKey is false
  610. function ao_module_clearLastUsedPath(actionKey=false, scopeName=undefined){
  611. var memory = ao_module_readPathMemory();
  612. var name = scopeName || ao_module_getPathMemoryScope();
  613. if (memory.scopes[name] == undefined){
  614. return false;
  615. }
  616. if (actionKey === false || actionKey == undefined || actionKey == ""){
  617. delete memory.scopes[name];
  618. }else if (memory.scopes[name].actions != undefined){
  619. delete memory.scopes[name].actions[actionKey];
  620. }
  621. ao_module_writePathMemory(memory);
  622. return true;
  623. }
  624. //Strip the object name off a returned filepath to get the directory holding it.
  625. //Folder selections are already a directory and are kept as-is, so re-opening the
  626. //selector lands inside the folder the user picked last time.
  627. function ao_module_pathMemoryDirOf(filepath, type){
  628. if (typeof(filepath) != "string" || filepath == ""){
  629. return "";
  630. }
  631. if (type == "folder"){
  632. return (filepath.substr(filepath.length - 1, 1) == "/") ? filepath : filepath + "/";
  633. }
  634. var cutpoint = filepath.lastIndexOf("/");
  635. if (cutpoint < 0){
  636. return "";
  637. }
  638. return filepath.substring(0, cutpoint + 1);
  639. }
  640. /*
  641. File Selector
  642. Open a file selector and return selected item back to the current window
  643. Tips: Unlike the beta version, you can use this function in both Virtual Desktop Mode and normal mode.
  644. Possible selection type:
  645. type => {file / folder / all / new}
  646. Example usage:
  647. ao_module_openFileSelector(fileSelected, "user:/Desktop", "file",true);
  648. function fileSelected(filedata){
  649. for (var i=0; i < filedata.length; i++){
  650. var filename = filedata[i].filename;
  651. var filepath = filedata[i].filepath;
  652. //Do something here
  653. }
  654. }
  655. If you want to create a new file or folder object, you can use the following options paramters
  656. option = {
  657. defaultName: "newfile.txt", //Default filename used in new operation
  658. fnameOverride: "myfunction", //For those defined with window.myfunction
  659. filter: ["mp3","aac","ogg","flac","wav"] //File extension filter
  660. }
  661. Path memory (see the File Selector Path Memory section above)
  662. The directory the user confirms is remembered per web app, and the next selector
  663. opened by the same app starts there instead of at the "root" argument. The root
  664. argument stays in effect as the fallback for the first ever call and for when the
  665. remembered directory no longer exists. Additional options controlling this:
  666. option = {
  667. force_path_overwrite: true, //Ignore the per-action memory and always open at
  668. //the directory this app last used, whatever the
  669. //action was. Use it for context free entry points
  670. //("New Project", "New File"), not for Save As /
  671. //Export where the caller passes a meaningful root
  672. path_memory_key: "export", //Bucket the memory per action instead of sharing
  673. //one per app. Defaults to "default"
  674. disable_path_memory: true //Opt out completely: open exactly at "root" and
  675. //record nothing
  676. }
  677. */
  678. var ao_module_fileSelectionListener;
  679. var ao_module_fileSelectorWindow;
  680. function ao_module_openFileSelector(callback,root="user:/", type="file",allowMultiple=false, options=undefined){
  681. if (options === null){
  682. options = undefined;
  683. }
  684. //Resolve where this selector should open, honoring the path memory of this app
  685. var actionKey = ao_module_pathMemoryDefaultAction;
  686. var forceOverwrite = false;
  687. var memoryDisabled = false;
  688. if (options != undefined){
  689. if (typeof(options.path_memory_key) == "string" && options.path_memory_key != ""){
  690. actionKey = options.path_memory_key;
  691. }
  692. forceOverwrite = (options.force_path_overwrite === true);
  693. memoryDisabled = (options.disable_path_memory === true);
  694. }
  695. var effectiveRoot = root;
  696. if (!memoryDisabled){
  697. //force_path_overwrite ignores what this action did last and jumps straight to
  698. //wherever the app was last used, as a new project has no relation to the
  699. //previous action. Otherwise the per-action memory wins, then the app wide one.
  700. var rememberedPath = forceOverwrite ?
  701. ao_module_getLastUsedPath(false) :
  702. ao_module_getLastUsedPath(actionKey);
  703. if (rememberedPath != ""){
  704. effectiveRoot = rememberedPath;
  705. }
  706. }
  707. var initInfo = {
  708. root: effectiveRoot,
  709. //Where the selector should land if the remembered directory has been
  710. //renamed or deleted since it was recorded
  711. fallbackRoot: root,
  712. type: type,
  713. allowMultiple: allowMultiple,
  714. listenerUUID: "",
  715. options: options
  716. }
  717. var initInfoEncoded = encodeURIComponent(JSON.stringify(initInfo))
  718. //Resolve the caller's callback into something we can invoke ourselves, so that the
  719. //confirmed directory can be recorded before the app gets to see the selection
  720. var invokeUserCallback;
  721. if (options != undefined && typeof(options.fnameOverride) != "undefined"){
  722. var overrideName = options.fnameOverride;
  723. invokeUserCallback = function(files){
  724. if (typeof(window[overrideName]) == "function"){
  725. window[overrideName](files);
  726. }else{
  727. console.log("[ao_module] File selector callback not found: " + overrideName);
  728. }
  729. };
  730. }else if (typeof callback === "string"){
  731. // Caller passed the function name as a string
  732. var callbackName = callback;
  733. invokeUserCallback = function(files){
  734. if (typeof(window[callbackName]) == "function"){
  735. window[callbackName](files);
  736. }else{
  737. console.log("[ao_module] File selector callback not found: " + callbackName);
  738. }
  739. };
  740. }else if (typeof callback === "function"){
  741. invokeUserCallback = callback;
  742. }else{
  743. invokeUserCallback = function(){};
  744. }
  745. //Wrap the callback so the confirmed directory becomes this app's last used path
  746. var handleSelection = function(files){
  747. if (!memoryDisabled && Array.isArray(files) && files.length > 0){
  748. try{
  749. var usedDir = ao_module_pathMemoryDirOf(files[0].filepath, type);
  750. if (usedDir != ""){
  751. ao_module_setLastUsedPath(usedDir, actionKey);
  752. }
  753. }catch(ex){
  754. console.log("[ao_module] Unable to record file selector path: " + ex);
  755. }
  756. }
  757. invokeUserCallback(files);
  758. };
  759. if (ao_module_virtualDesktop){
  760. //The desktop evals the callback name inside this iframe after selection, so the
  761. //wrapper has to be reachable as a window scoped function of this window
  762. var callbackname = "_aoFs_" + new Date().getTime() + "_" + Math.floor(Math.random() * 100000);
  763. window[callbackname] = function(files){
  764. try{
  765. handleSelection(files);
  766. }finally{
  767. delete window[callbackname];
  768. }
  769. };
  770. parent.newFloatWindow({
  771. url: "SystemAO/file_system/file_selector.html#" + initInfoEncoded,
  772. //Sized so the sidebar, file list and details pane all fit without the
  773. //footer controls wrapping onto a second row
  774. width: 960,
  775. height: 620,
  776. appicon: "SystemAO/file_system/img/selector.png",
  777. title: "Open",
  778. parent: ao_module_windowID,
  779. callback: callbackname
  780. });
  781. }else{
  782. //Create a return listener base on localStorage
  783. let listenerUUID = "fileSelector_" + new Date().getTime();
  784. ao_module_fileSelectionListener = setInterval(function(){
  785. if (localStorage.getItem(listenerUUID) === undefined || localStorage.getItem(listenerUUID)=== null){
  786. //Not ready
  787. }else{
  788. //File ready!
  789. var selectedFiles = JSON.parse(localStorage.getItem(listenerUUID));
  790. localStorage.removeItem(listenerUUID);
  791. setTimeout(function(){
  792. localStorage.removeItem(listenerUUID);
  793. },500);
  794. if(selectedFiles == "&&selection_canceled&&"){
  795. //Selection canceled. Return empty array
  796. handleSelection([]);
  797. }else{
  798. //Files Selected
  799. handleSelection(selectedFiles);
  800. }
  801. clearInterval(ao_module_fileSelectionListener);
  802. ao_module_fileSelectorWindow.close();
  803. }
  804. },1000);
  805. //Open the file selector in a new tab
  806. initInfo.listenerUUID = listenerUUID;
  807. initInfoEncoded = encodeURIComponent(JSON.stringify(initInfo))
  808. ao_module_fileSelectorWindow = window.open(ao_root + "SystemAO/file_system/file_selector.html#" + initInfoEncoded,);
  809. }
  810. }
  811. //Check if there is parent to callback
  812. function ao_module_hasParentCallback(){
  813. if (ao_module_virtualDesktop){
  814. //Check if parent callback exists
  815. var thisFw;
  816. $(parent.window.document.body).find(".floatWindow").each(function(){
  817. if ($(this).attr('windowid') == ao_module_windowID){
  818. thisFw = $(this);
  819. }
  820. });
  821. var parentWindowID = thisFw.attr("parent");
  822. var parentCallback = thisFw.attr("callback");
  823. if (parentWindowID == "" || parentCallback == ""){
  824. //No parent window defined
  825. return false;
  826. }
  827. //Check if parent windows is alive
  828. var parentWindow = undefined;
  829. $(parent.window.document.body).find(".floatWindow").each(function(){
  830. if ($(this).attr('windowid') == parentWindowID){
  831. parentWindow = $(this);
  832. }
  833. });
  834. if (parentWindow == undefined){
  835. //parent window not exists
  836. return false;
  837. }
  838. //Parent callback is set and ready to callback
  839. return true;
  840. }else{
  841. return false
  842. }
  843. }
  844. //Callback to parent with results
  845. function ao_module_parentCallback(data=""){
  846. if (ao_module_virtualDesktop){
  847. var thisFw;
  848. $(parent.window.document.body).find(".floatWindow").each(function(){
  849. if ($(this).attr('windowid') == ao_module_windowID){
  850. thisFw = $(this);
  851. }
  852. });
  853. var parentWindowID = thisFw.attr("parent");
  854. var parentCallback = thisFw.attr("callback");
  855. if (parentWindowID == "" || parentCallback == ""){
  856. //No parent window defined
  857. console.log("Undefined parent window ID or callback name");
  858. return false;
  859. }
  860. var parentWindow = undefined;
  861. $(parent.window.document.body).find(".floatWindow").each(function(){
  862. if ($(this).attr('windowid') == parentWindowID){
  863. parentWindow = $(this);
  864. }
  865. });
  866. if (parentWindow == undefined){
  867. //parent window not exists
  868. console.log("Parent Window not exists!")
  869. return false;
  870. }
  871. $(parentWindow).find('iframe')[0].contentWindow.eval(parentCallback + "(" + JSON.stringify(data) + ");")
  872. //Focus the parent windows
  873. parent.MoveFloatWindowToTop(parentWindow);
  874. return true;
  875. }else{
  876. console.log("[ao_module] WARNING! Invalid call to parentCallback under non-virtualDesktop mode");
  877. return false;
  878. }
  879. }
  880. function ao_module_agirun(scriptpath, data, callback, failedcallback = undefined, timeout=0){
  881. let devmode = (typeof AGI_DEV !== 'undefined' && AGI_DEV === true);
  882. let url = ao_root + "system/ajgi/interface?script=" + scriptpath;
  883. if (devmode) {
  884. url += "&agi_devmode=true";
  885. }
  886. $.ajax({
  887. url: url,
  888. method: "POST",
  889. data: data,
  890. success: function(data){
  891. if (typeof(callback) != "undefined"){
  892. callback(data);
  893. }
  894. },
  895. error: function(xhr){
  896. if (devmode) {
  897. try {
  898. let errInfo = JSON.parse(xhr.responseText);
  899. console.error("[AGI Dev] Error in script: " + scriptpath);
  900. console.error("[AGI Dev] Message: " + errInfo.message);
  901. if (errInfo.stacktrace && errInfo.stacktrace !== errInfo.message) {
  902. console.error("[AGI Dev] Stack Trace:\n" + errInfo.stacktrace);
  903. }
  904. } catch(e) {
  905. console.error("[AGI Dev] Error in script: " + scriptpath + "\n" + xhr.responseText);
  906. }
  907. }
  908. if (typeof(failedcallback) != "undefined"){
  909. failedcallback(xhr);
  910. }
  911. },
  912. timeout: timeout
  913. });
  914. }
  915. function ao_module_uploadFile(file, targetPath, callback=undefined, progressCallback=undefined, failedcallback=undefined) {
  916. let url = ao_root + 'system/file_system/upload'
  917. let formData = new FormData()
  918. let xhr = new XMLHttpRequest()
  919. formData.append('file', file);
  920. formData.append('path', targetPath);
  921. xhr.open('POST', url, true);
  922. xhr.upload.addEventListener("progress", function(e) {
  923. if (progressCallback !== undefined){
  924. progressCallback((e.loaded * 100.0 / e.total) || 100);
  925. }
  926. });
  927. xhr.addEventListener('readystatechange', function(e) {
  928. if (xhr.readyState == 4 && xhr.status == 200) {
  929. if (callback !== undefined){
  930. callback(e.target.response);
  931. }
  932. }
  933. else if (xhr.readyState == 4 && xhr.status != 200) {
  934. if (failedcallback !== undefined){
  935. failedcallback(xhr.status);
  936. }
  937. }
  938. })
  939. xhr.send(formData);
  940. }
  941. /*
  942. ao_module_storage, allow key-value storage per module settings.
  943. WARNING: NOT CROSS USER READ-WRITABLE
  944. ao_module_storage.setStorage(moduleName, configName,configValue);
  945. ao_module_storage.loadStorage(moduleName, configName);
  946. */
  947. if (typeof window.ao_module_storage === 'undefined') {
  948. window.ao_module_storage = class {
  949. static setStorage(moduleName, configName,configValue){
  950. $.ajax({
  951. type: 'GET',
  952. url: ao_root + "system/file_system/preference",
  953. data: {key: moduleName + "/" + configName,value:configValue},
  954. success: function(data){},
  955. async:true
  956. });
  957. return true;
  958. }
  959. static loadStorage(moduleName, configName, callback=undefined){
  960. var result = "";
  961. if (callback == undefined){
  962. //Do not use async
  963. $.ajax({
  964. type: 'GET',
  965. url: ao_root + "system/file_system/preference",
  966. data: {key: moduleName + "/" + configName},
  967. success: function(data){
  968. if (data.error !== undefined){
  969. result = "";
  970. }else{
  971. result = data;
  972. }
  973. },
  974. error: function(data){result = "";},
  975. async:false,
  976. timeout: 3000
  977. });
  978. return result;
  979. }else{
  980. //Use sync method
  981. $.ajax({
  982. type: 'GET',
  983. url: ao_root + "system/file_system/preference",
  984. data: {key: moduleName + "/" + configName},
  985. success: function(data){
  986. if (data.error !== undefined){
  987. callback("");
  988. }else{
  989. callback(data);
  990. }
  991. },
  992. error: function(evt){
  993. callback("");
  994. },
  995. timeout: 30000
  996. });
  997. }
  998. }
  999. }
  1000. }
  1001. /*
  1002. ao_module_onThemeChanged(callback)
  1003. Register a callback that fires whenever the ArozOS system theme changes.
  1004. The callback receives one string argument: "dark" or "light".
  1005. Works in two modes:
  1006. - Virtual Desktop (float-window): the desktop calls window.desktopThemeChanged
  1007. on every iframe after a theme switch.
  1008. - Standalone tab: listens for a localStorage event written by desktop.html or
  1009. file_explorer.html when the user toggles the theme.
  1010. Example:
  1011. ao_module_onThemeChanged(function(theme) {
  1012. document.documentElement.setAttribute("data-theme", theme);
  1013. });
  1014. */
  1015. var _ao_theme_ls_key = 'ao_system_theme';
  1016. var _ao_theme_ls_bound = false;
  1017. function ao_module_onThemeChanged(callback) {
  1018. // VDI broadcast path: desktop.html calls desktopThemeChanged on each iframe
  1019. window.desktopThemeChanged = function(theme) {
  1020. callback(theme);
  1021. };
  1022. // Standalone/cross-tab path: other windows write ao_system_theme to localStorage
  1023. if (!_ao_theme_ls_bound) {
  1024. _ao_theme_ls_bound = true;
  1025. window.addEventListener('storage', function(e) {
  1026. if (e.key !== _ao_theme_ls_key || !e.newValue) return;
  1027. try {
  1028. var evt = JSON.parse(e.newValue);
  1029. if (evt && evt.theme && typeof window.desktopThemeChanged === 'function') {
  1030. window.desktopThemeChanged(evt.theme);
  1031. }
  1032. } catch(ex) {}
  1033. });
  1034. }
  1035. }
  1036. /*
  1037. ao_module_toggleSystemTheme()
  1038. Toggle the system-wide ArozOS theme between dark and light.
  1039. All webapps that have called ao_module_onThemeChanged will be notified.
  1040. In Virtual Desktop Mode this delegates to the desktop's own toggle, which
  1041. also persists the preference. In standalone mode it reads the saved preference,
  1042. flips it, persists it, then broadcasts the change via localStorage.
  1043. */
  1044. function ao_module_toggleSystemTheme() {
  1045. if (ao_module_virtualDesktop) {
  1046. try {
  1047. parent.toggleDesktopTheme();
  1048. } catch(e) {
  1049. console.log("[ao_module] toggleSystemTheme: cannot reach parent desktop", e);
  1050. }
  1051. return;
  1052. }
  1053. // Standalone: read -> flip -> save -> broadcast
  1054. $.get(ao_root + "system/file_system/preference?key=file_explorer/theme", function(data) {
  1055. var isDark = (data === 'darkTheme');
  1056. var newPref = isDark ? 'whiteTheme' : 'darkTheme';
  1057. var newTheme = isDark ? 'light' : 'dark';
  1058. $.get(ao_root + "system/file_system/preference?key=file_explorer/theme&value=" + newPref, function() {
  1059. _ao_theme_broadcast(newTheme);
  1060. });
  1061. });
  1062. }
  1063. // Write the theme event to localStorage (notifies other tabs) and call the
  1064. // local callback if one has been registered via ao_module_onThemeChanged.
  1065. function _ao_theme_broadcast(theme) {
  1066. try {
  1067. localStorage.setItem(_ao_theme_ls_key, JSON.stringify({theme: theme, ts: Date.now()}));
  1068. } catch(e) {}
  1069. if (typeof window.desktopThemeChanged === 'function') {
  1070. window.desktopThemeChanged(theme);
  1071. }
  1072. }
  1073. if (typeof window.ao_module_codec === 'undefined') {
  1074. window.ao_module_codec = class {
  1075. //Decode umfilename into standard filename in utf-8, which umfilename usually start with "inith"
  1076. //Example: ao_module_codec.decodeUmFilename(umfilename_here);
  1077. static decodeUmFilename(umfilename){
  1078. if (umfilename.includes("inith")){
  1079. var data = umfilename.split(".");
  1080. if (data.length == 1){
  1081. //This is a filename without extension
  1082. data = data[0].replace("inith","");
  1083. var decodedname = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(data));
  1084. if (decodedname != "false"){
  1085. //This is a umfilename
  1086. return decodedname;
  1087. }else{
  1088. //This is not a umfilename
  1089. return umfilename;
  1090. }
  1091. }else{
  1092. //This is a filename with extension
  1093. var extension = data.pop();
  1094. var filename = data[0];
  1095. filename = filename.replace("inith",""); //Javascript replace only remove the first instances (i.e. the first inith in filename)
  1096. var decodedname = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(filename));
  1097. if (decodedname != "false"){
  1098. //This is a umfilename
  1099. return decodedname + "." + extension;
  1100. }else{
  1101. //This is not a umfilename
  1102. return umfilename;
  1103. }
  1104. }
  1105. }else{
  1106. //This is not umfilename as it doesn't have the inith prefix
  1107. return umfilename;
  1108. }
  1109. }
  1110. //Encode filename to UMfilename
  1111. //Example: ao_module_codec.encodeUMFilename("test.stl");
  1112. static encodeUMFilename(filename){
  1113. if (filename.substring(0,5) != "inith"){
  1114. //Check if the filename include extension.
  1115. if (filename.includes(".")){
  1116. //Filename with extension. pop it out first.
  1117. var info = filename.split(".");
  1118. var ext = info.pop();
  1119. var filenameOnly = info.join(".");
  1120. var encodedFilename = "inith" + ao_module_codec.decode_utf8(ao_module_codec.bin2hex(filenameOnly)) + "." + ext;
  1121. return encodedFilename;
  1122. }else{
  1123. //Filename with no extension. Convert the whole name into UMfilename
  1124. var encodedFilename = "inith" + ao_module_codec.decode_utf8(ao_module_codec.bin2hex(filename));
  1125. return encodedFilename;
  1126. }
  1127. }else{
  1128. //This is already a UMfilename. return the raw filename.
  1129. return filename;
  1130. }
  1131. }
  1132. //Decode hexFoldername into standard foldername in utf-8, return the original name if it is not a hex foldername
  1133. //Example: ao_module_codec.decodeHexFoldername(hexFolderName_here);
  1134. static decodeHexFoldername(folderName, prefix=true){
  1135. var decodedFoldername = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(folderName));
  1136. if (decodedFoldername == "false"){
  1137. //This is not a hex encoded foldername
  1138. decodedFoldername = folderName;
  1139. }else{
  1140. //This is a hex encoded foldername
  1141. if (prefix){
  1142. decodedFoldername = "*" + decodedFoldername;
  1143. }else{
  1144. decodedFoldername =decodedFoldername;
  1145. }
  1146. }
  1147. return decodedFoldername;
  1148. }
  1149. //Encode foldername into hexfoldername
  1150. //Example: ao_module_codec.encodeHexFoldername("test");
  1151. static encodeHexFoldername(folderName){
  1152. var encodedFilename = "";
  1153. if (ao_module_codec.decodeHexFoldername(folderName) == folderName){
  1154. //This is not hex foldername. Encode it
  1155. encodedFilename = ao_module_codec.decode_utf8(ao_module_codec.bin2hex(folderName));
  1156. }else{
  1157. //This folder name already encoded. Return the original value
  1158. encodedFilename = folderName;
  1159. }
  1160. return encodedFilename;
  1161. }
  1162. static hex2bin(s){
  1163. var ret = []
  1164. var i = 0
  1165. var l
  1166. s += ''
  1167. for (l = s.length; i < l; i += 2) {
  1168. var c = parseInt(s.substr(i, 1), 16)
  1169. var k = parseInt(s.substr(i + 1, 1), 16)
  1170. if (isNaN(c) || isNaN(k)) return false
  1171. ret.push((c << 4) | k)
  1172. }
  1173. return String.fromCharCode.apply(String, ret)
  1174. }
  1175. static bin2hex(s){
  1176. var i
  1177. var l
  1178. var o = ''
  1179. var n
  1180. s += ''
  1181. for (i = 0, l = s.length; i < l; i++) {
  1182. n = s.charCodeAt(i)
  1183. .toString(16)
  1184. o += n.length < 2 ? '0' + n : n
  1185. }
  1186. return o
  1187. }
  1188. static decode_utf8(s) {
  1189. return decodeURIComponent(escape(s));
  1190. }
  1191. }
  1192. }
  1193. /**
  1194. ArOZ Online Module Utils for quick deploy of ArOZ Online WebApps
  1195. ao_module_utils.objectToAttr(object); //object to DOM attr
  1196. ao_module_utils.attrToObject(attr); //DOM attr to Object
  1197. ao_module_utils.getRandomUID(); //Get random UUID from timestamp
  1198. ao_module_utils.getIconFromExt(ext); //Get icon tag from file extension
  1199. ao_module_utils.stringToBlob(text, mimetype="text/plain") //Convert string to blob
  1200. ao_module_utils.blobToFile(blob, filename, mimetype="text/plain") //Convert blob to file
  1201. ao_module_utils.getDropFileInfo(dropEvent); //Get the filepath and filename list from file explorer drag drop
  1202. ao_module_utils.readFileFromFileObject(fileObject, successCallback, failedCallback=undefined) //Read file object as text
  1203. ao_module_utils.durationConverter(seconds) //Convert duration in seconds to Days / Hours / Minutes / Seconds
  1204. ao_module_utils.formatBytes(byte, decimals); //Format file byte size to human readable size
  1205. ao_module_utils.timeConverter(unix_timestamp); //Get human readable timestamp
  1206. ao_module_utils.getWebSocketEndpoint() //Build server websocket endpoint root, e.g. wss://192.168.1.100:8080/
  1207. ao_module_utils.formatBytes(bytes, decimalPlace=2) //Convert and rounds bytes into KB, MB, GB or TB
  1208. **/
  1209. if (typeof window.ao_module_utils === 'undefined') {
  1210. window.ao_module_utils = class {
  1211. //Two simple functions for converting any Javascript object into string that can be put into the attr value of an DOM object
  1212. static objectToAttr(object){
  1213. return encodeURIComponent(JSON.stringify(object));
  1214. }
  1215. static attrToObject(attr){
  1216. return JSON.parse(decodeURIComponent(attr));
  1217. }
  1218. //Get a random id for a new floatWindow, use with var uid = ao_module_utils.getRandomUID();
  1219. static getRandomUID(){
  1220. return new Date().getTime();
  1221. }
  1222. static stringToBlob(text, mimetype="text/plain"){
  1223. var blob = new Blob([text], { type: mimetype });
  1224. return blob
  1225. }
  1226. static blobToFile(blob, filename, mimetype="text/plain"){
  1227. var file = new File([blob], filename, {type: mimetype});
  1228. return file
  1229. }
  1230. //Get the icon of a file with given extension (ext), use with ao_module_utils.getIconFromExt("ext");
  1231. static getIconFromExt(ext){
  1232. var ext = ext.toLowerCase().trim();
  1233. var iconList={
  1234. md:"file text outline",
  1235. txt:"file text outline",
  1236. pdf:"file pdf outline",
  1237. doc:"file word outline",
  1238. docx:"file word outline",
  1239. odt:"file word outline",
  1240. xlsx:"file excel outline",
  1241. ods:"file excel outline",
  1242. ppt:"file powerpoint outline",
  1243. pptx:"file powerpoint outline",
  1244. odp:"file powerpoint outline",
  1245. jpg:"file image outline",
  1246. png:"file image outline",
  1247. jpeg:"file image outline",
  1248. gif:"file image outline",
  1249. odg:"file image outline",
  1250. psd:"file image outline",
  1251. zip:"file archive outline",
  1252. '7z':"file archive outline",
  1253. rar:"file archive outline",
  1254. tar:"file archive outline",
  1255. mp3:"file audio outline",
  1256. m4a:"file audio outline",
  1257. flac:"file audio outline",
  1258. wav:"file audio outline",
  1259. aac:"file audio outline",
  1260. mp4:"file video outline",
  1261. webm:"file video outline",
  1262. php:"file code outline",
  1263. html:"file code outline",
  1264. htm:"file code outline",
  1265. js:"file code outline",
  1266. css:"file code outline",
  1267. xml:"file code outline",
  1268. json:"file code outline",
  1269. csv:"file code outline",
  1270. odf:"file code outline",
  1271. bmp:"file image outline",
  1272. rtf:"file text outline",
  1273. wmv:"file video outline",
  1274. mkv:"file video outline",
  1275. ogg:"file audio outline",
  1276. stl:"cube",
  1277. obj:"cube",
  1278. "3ds":"cube",
  1279. fbx:"cube",
  1280. collada:"cube",
  1281. step:"cube",
  1282. iges:"cube",
  1283. gcode:"cube",
  1284. shortcut:"external square",
  1285. opus:"file audio outline",
  1286. agi: "file code outline",
  1287. apscene:"cubes"
  1288. };
  1289. var icon = "";
  1290. if (ext == ""){
  1291. icon = "folder outline";
  1292. }else{
  1293. icon = iconList[ext];
  1294. if (icon == undefined){
  1295. icon = "file outline"
  1296. }
  1297. }
  1298. return icon;
  1299. }
  1300. //Get the drop file properties {filepath: xxx, filename: xxx} from file drop events from file exploere
  1301. static getDropFileInfo(dropEvent){
  1302. if (dropEvent.dataTransfer.getData("filedata") !== ""){
  1303. var filelist = dropEvent.dataTransfer.getData("filedata");
  1304. filelist = JSON.parse(filelist);
  1305. return filelist;
  1306. }
  1307. return null;
  1308. }
  1309. static readFileFromFileObject(fileObject, successCallback, failedCallback=undefined){
  1310. let reader = new FileReader();
  1311. reader.readAsText(fileObject);
  1312. reader.onload = function() {
  1313. successCallback(reader.result);
  1314. };
  1315. reader.onerror = function() {
  1316. if (failedCallback != undefined){
  1317. failedCallback(reader.error);
  1318. }else{
  1319. console.log(reader.error);
  1320. }
  1321. };
  1322. }
  1323. static durationConverter(seconds){
  1324. var days = Math.floor(seconds / 86400);
  1325. seconds -= days * 86400;
  1326. var hours = Math.floor(seconds / 3600) % 24;
  1327. seconds -= hours * 3600;
  1328. var minutes = Math.floor(seconds / 60) % 60;
  1329. seconds -= minutes * 60;
  1330. var seconds = seconds % 60;
  1331. var resultDuration = "";
  1332. if (days > 0){
  1333. resultDuration += days + " Day";
  1334. if (days > 1){
  1335. resultDuration+= "s"
  1336. }
  1337. resultDuration += " "
  1338. }
  1339. if (hours > 0){
  1340. resultDuration += hours + " Hour"
  1341. if (hours > 1){
  1342. resultDuration += "s"
  1343. }
  1344. resultDuration += " "
  1345. }
  1346. if (minutes > 0){
  1347. resultDuration += minutes + " Minute"
  1348. if (minutes > 1){
  1349. resultDuration += "s"
  1350. }
  1351. resultDuration += " "
  1352. }
  1353. if (seconds > 0){
  1354. resultDuration += seconds + " Second"
  1355. if (seconds > 1){
  1356. resultDuration += "s"
  1357. }
  1358. resultDuration += " "
  1359. }
  1360. return resultDuration;
  1361. }
  1362. static timeConverter(UNIX_timestamp){
  1363. var a = new Date(UNIX_timestamp * 1000);
  1364. var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  1365. var year = a.getFullYear();
  1366. var month = months[a.getMonth()];
  1367. var date = a.getDate();
  1368. var hour = a.getHours().toString().padStart(2, "0");
  1369. var min = a.getMinutes().toString().padStart(2, "0");
  1370. var sec = a.getSeconds().toString().padStart(2, "0");
  1371. var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  1372. return time;
  1373. }
  1374. static getWebSocketEndpoint(){
  1375. let protocol = "wss://";
  1376. if (location.protocol !== 'https:') {
  1377. protocol = "ws://";
  1378. }
  1379. let port = window.location.port;
  1380. if (window.location.port == ""){
  1381. if (location.protocol !== 'https:') {
  1382. port = "80";
  1383. }else{
  1384. port = "443";
  1385. }
  1386. }
  1387. let wsept = (protocol + window.location.hostname + ":" + port);
  1388. return wsept;
  1389. }
  1390. static formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}
  1391. }
  1392. }
  1393. /*
  1394. Backend Programming Logic
  1395. These code are design to use with ao_backend.js for wrapping
  1396. AGI programming gateway content
  1397. */
  1398. function ao_module_backend(){
  1399. return {
  1400. timeout: 500,
  1401. start: function(libraryPath){
  1402. this.libpath = libraryPath;
  1403. //Initialize the parent objects
  1404. this.appdata.parent = this;
  1405. this.file.parent = this;
  1406. this.http.parent = this;
  1407. },
  1408. _agi_run: function(data, callback, failedcallback = undefined){
  1409. $.ajax({
  1410. url: ao_root + "system/ajgi/interface?script=" + this.libpath,
  1411. method: "POST",
  1412. data: data,
  1413. success: function(data){
  1414. if (typeof(callback) != "undefined"){
  1415. callback(data);
  1416. }
  1417. },
  1418. error: function(){
  1419. if (typeof(failedcallback) != "undefined"){
  1420. failedcallback();
  1421. }
  1422. console.log("Request failed");
  1423. },
  1424. timeout: this.timeout
  1425. })
  1426. },
  1427. appdata: {
  1428. readFile: function(filepath, callback=undefined){
  1429. this.parent._agi_run({
  1430. opr: "appdata.readFile",
  1431. filepath: filepath
  1432. }, callback)
  1433. },
  1434. listDir: function(filepath, callback=undefined){
  1435. this.parent._agi_run({
  1436. opr: "appdata.listDir",
  1437. filepath: filepath
  1438. }, callback)
  1439. },
  1440. },
  1441. file: {
  1442. writeFile: function(filepath, content, callback=undefined){
  1443. this.parent._agi_run({
  1444. opr: "file.writeFile",
  1445. filepath: filepath,
  1446. content: content,
  1447. }, callback)
  1448. },
  1449. readFile: function(filepath, callback=undefined){
  1450. this.parent._agi_run({
  1451. opr: "file.readFile",
  1452. filepath: filepath
  1453. }, callback)
  1454. },
  1455. deleteFile: function(filepath, callback=undefined){
  1456. this.parent._agi_run({
  1457. opr: "file.deleteFile",
  1458. filepath: filepath
  1459. }, callback)
  1460. },
  1461. readdir: function(filepath, callback=undefined){
  1462. this.parent._agi_run({
  1463. opr: "file.readdir",
  1464. filepath: filepath
  1465. }, callback)
  1466. },
  1467. walk: function(filepath, mode="all", callback=undefined){
  1468. this.parent._agi_run({
  1469. opr: "file.walk",
  1470. filepath: filepath,
  1471. mode: mode,
  1472. }, callback)
  1473. },
  1474. glob: function(wildcard, sort="user", callback=undefined){
  1475. this.parent._agi_run({
  1476. opr: "file.glob",
  1477. wildcard: wildcard,
  1478. sort: sort,
  1479. }, callback)
  1480. },
  1481. aglob: function(wildcard, sort="user", callback=undefined){
  1482. this.parent._agi_run({
  1483. opr: "file.aglob",
  1484. wildcard: wildcard,
  1485. sort: sort,
  1486. }, callback)
  1487. },
  1488. filesize: function(filepath, callback=undefined){
  1489. this.parent._agi_run({
  1490. opr: "file.filesize",
  1491. filepath: filepath
  1492. }, callback)
  1493. },
  1494. fileExists: function(filepath, callback=undefined){
  1495. this.parent._agi_run({
  1496. opr: "file.fileExists",
  1497. filepath: filepath
  1498. }, callback)
  1499. },
  1500. isDir: function(filepath, callback=undefined){
  1501. this.parent._agi_run({
  1502. opr: "file.isDir",
  1503. filepath: filepath
  1504. }, callback)
  1505. },
  1506. mkdir: function(filepath, callback=undefined){
  1507. this.parent._agi_run({
  1508. opr: "file.mkdir",
  1509. filepath: filepath
  1510. }, callback)
  1511. },
  1512. mtime: function(filepath, callback=undefined){
  1513. this.parent._agi_run({
  1514. opr: "file.mtime",
  1515. filepath: filepath
  1516. }, callback)
  1517. },
  1518. rootName: function(filepath, callback=undefined){
  1519. this.parent._agi_run({
  1520. opr: "file.rootName",
  1521. filepath: filepath
  1522. }, callback)
  1523. }
  1524. },
  1525. http: {
  1526. get: function(targetURL, callback=undefined){
  1527. this.parent._agi_run({
  1528. opr: "http.get",
  1529. targetURL: targetURL
  1530. }, callback)
  1531. },
  1532. post: function(targetURL, postdata="", callback=undefined){
  1533. this.parent._agi_run({
  1534. opr: "http.post",
  1535. targetURL: targetURL,
  1536. postdata: postdata
  1537. }, callback)
  1538. },
  1539. head: function(targetURL, header="", callback=undefined){
  1540. this.parent._agi_run({
  1541. opr: "http.head",
  1542. targetURL: targetURL,
  1543. header: header
  1544. }, callback)
  1545. },
  1546. download: function(targetURL, saveDir="tmp:/", saveFilename="", callback=undefined){
  1547. if (saveFilename == ""){
  1548. saveFilename = targetURL.split("/").pop();
  1549. saveFilename = decodeURIComponent(saveFilename);
  1550. }
  1551. this.parent._agi_run({
  1552. opr: "http.download",
  1553. targetURL: targetURL,
  1554. saveDir: saveDir,
  1555. saveFilename: saveFilename
  1556. }, callback)
  1557. },
  1558. }
  1559. }
  1560. }