ao_module.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 = !(!parent.isDesktopMode);
  12. var ao_root = null;
  13. //Get the current windowID if in Virtual Desktop Mode, return false if VDI is not detected
  14. var ao_module_windowID = false;
  15. var ao_module_parentID = false;
  16. var ao_module_callback = false;
  17. if (ao_module_virtualDesktop)ao_module_windowID = $(window.frameElement).parent().parent().attr("windowId");
  18. if (ao_module_virtualDesktop)ao_module_parentID = $(window.frameElement).parent().parent().attr("parent");
  19. if (ao_module_virtualDesktop)ao_module_callback = $(window.frameElement).parent().parent().attr("callback");
  20. if (ao_module_virtualDesktop)ao_module_parentURL = $(window.frameElement).parent().find("iframe").attr("src");
  21. ao_root = ao_module_getAORootFromScriptPath();
  22. /*
  23. Event bindings
  24. The following events are required for ao_module to operate normally
  25. under Web Desktop Mode.
  26. */
  27. document.addEventListener("DOMContentLoaded", function() {
  28. if (ao_module_virtualDesktop){
  29. //Add window focus handler
  30. document.addEventListener("mousedown", function(event) {
  31. //When click on this document, focus this
  32. ao_module_focus();
  33. if (event.target.tagName == "INPUT" || event.target.tagName == "TEXTAREA"){
  34. }else{
  35. if (parent.window.ime.focus != null){
  36. parent.window.ime.focus = null;
  37. }
  38. }
  39. }, true);
  40. //Add IME registration handler
  41. var inputFields = document.querySelectorAll("input,textarea");
  42. for (var i = 0; i < inputFields.length; i++){
  43. console.log(inputFields[i]);
  44. ao_module_bindCustomIMEEvents(inputFields[i]);
  45. }
  46. }
  47. });
  48. /*
  49. Startup Section Script
  50. These functions handle the startup of an ao_module and adapt them into the
  51. standard arozos desktop eco-system api
  52. */
  53. //Function handle to bind custom IME events
  54. function ao_module_bindCustomIMEEvents(object){
  55. parent.bindObjectToIMEEvents(object);
  56. }
  57. //Get the ao_root from script includsion path
  58. function ao_module_getAORootFromScriptPath(){
  59. var possibleRoot = "";
  60. $("script").each(function(){
  61. if (this.hasAttribute("src") && $(this).attr("src").includes("ao_module.js")){
  62. var tmp = $(this).attr("src");
  63. tmp = tmp.split("script/ao_module.js");
  64. possibleRoot = tmp[0];
  65. }
  66. });
  67. return possibleRoot;
  68. }
  69. //Get the input filename and filepath from the window hash paramter
  70. function ao_module_loadInputFiles(){
  71. try{
  72. if (window.location.hash.length == 0){
  73. return null;
  74. }
  75. var inputFileInfo = window.location.hash.substring(1,window.location.hash.length);
  76. inputFileInfo = JSON.parse(decodeURIComponent(inputFileInfo));
  77. return inputFileInfo
  78. }catch{
  79. return null;
  80. }
  81. }
  82. //Set the ao_module window to fixed size (not allowing resize)
  83. function ao_module_setFixedWindowSize(){
  84. if (!ao_module_virtualDesktop){
  85. return;
  86. }
  87. parent.setFloatWindowResizePolicy(ao_module_windowID, false);
  88. }
  89. //Restore a float window to be resizble
  90. function ao_module_setResizableWindowSize(){
  91. if (!ao_module_virtualDesktop){
  92. return;
  93. }
  94. parent.setFloatWindowResizePolicy(ao_module_windowID, true);
  95. }
  96. //Update the window size of the given float window object
  97. function ao_module_setWindowSize(width, height){
  98. if (!ao_module_virtualDesktop){
  99. return;
  100. }
  101. parent.setFloatWindowSize(ao_module_windowID, width, height)
  102. }
  103. //Update the floatWindow title
  104. function ao_module_setWindowTitle(newTitle){
  105. if (!ao_module_virtualDesktop){
  106. document.title = newTitle;
  107. return;
  108. }
  109. parent.setFloatWindowTitle(ao_module_windowID, newTitle);
  110. }
  111. //Set new window theme, default dark, support {dark/white}
  112. function ao_module_setWindowTheme(newtheme="dark"){
  113. if (!ao_module_virtualDesktop){
  114. return;
  115. }
  116. parent.setFloatWindowTheme(ao_module_windowID, newtheme);
  117. }
  118. //Check if there are any windows with the same path.
  119. //If yes, replace its hash content and reload to the new one and clise the current floatWindow
  120. function ao_module_makeSingleInstance(){
  121. $(window.parent.document).find(".floatWindow").each(function(){
  122. if ($(this).attr("windowid") == ao_module_windowID){
  123. return
  124. }
  125. var currentPath = window.location.pathname;
  126. if ("/" + $(this).find("iframe").attr('src').split("#").shift() == currentPath){
  127. //Another instance already running. Replace it with the current path
  128. $(this).find("iframe").attr('src', window.location.pathname.substring(1) + window.location.hash);
  129. $(this).find("iframe")[0].contentWindow.location.reload();
  130. //Move the other instant to top
  131. var targetfw = parent.getFloatWindowByID($(this).attr("windowid"))
  132. parent.MoveFloatWindowToTop(targetfw);
  133. //Close the instance
  134. ao_module_close();
  135. return true
  136. }
  137. });
  138. return false
  139. }
  140. //Close the current window
  141. function ao_module_close(){
  142. if (!ao_module_virtualDesktop){
  143. window.close('','_parent','');
  144. window.location.href = ao_root + "SystemAO/closeTabInsturction.html";
  145. return;
  146. }
  147. parent.closeFwProcess(ao_module_windowID);
  148. }
  149. //Focus this floatWindow
  150. function ao_module_focus(){
  151. parent.MoveFloatWindowToTop(parent.getFloatWindowByID(ao_module_windowID));
  152. }
  153. //Set the floatWindow to top most mode
  154. function ao_module_setTopMost(){
  155. parent.PinFloatWindowToTopMostMode(parent.getFloatWindowByID(ao_module_windowID));
  156. }
  157. //Unset the floatWindow top most mode
  158. function ao_module_unsetTopMost(){
  159. parent.UnpinFloatWindowFromTopMostMode(parent.getFloatWindowByID(ao_module_windowID));
  160. }
  161. //Popup a file selection window for uplaod
  162. function ao_module_selectFiles(callback, fileType="file", accept="*", allowMultiple=false){
  163. var input = document.createElement('input');
  164. input.type = fileType;
  165. input.multiple = allowMultiple;
  166. input.accept = accept;
  167. input.onchange = e => {
  168. var files = e.target.files;
  169. callback(files);
  170. }
  171. input.click();
  172. }
  173. //Open a path with File Manager, optional highligh filename
  174. function ao_module_openPath(path, filename=undefined){
  175. //Trim away the last / if exists
  176. if (path.substr(path.length - 1, 1) == "/"){
  177. path = path.substr(0, path.length - 1);
  178. }
  179. if (filename == undefined){
  180. if (ao_module_virtualDesktop){
  181. parent.newFloatWindow({
  182. url: "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(path),
  183. appicon: "SystemAO/file_system/img/small_icon.png",
  184. width:1080,
  185. height:580,
  186. title: "File Manager"
  187. });
  188. }else{
  189. window.open(ao_root + "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(path))
  190. }
  191. }else{
  192. var fileObject = [{
  193. filepath: path + "/" + filename,
  194. filename: filename,
  195. }];
  196. if (ao_module_virtualDesktop){
  197. parent.newFloatWindow({
  198. url: "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(JSON.stringify(fileObject)),
  199. appicon: "SystemAO/file_system/img/small_icon.png",
  200. width:1080,
  201. height:580,
  202. title: "File Manager"
  203. });
  204. }else{
  205. window.open(ao_root + "SystemAO/file_system/file_explorer.html#" + encodeURIComponent(JSON.stringify(fileObject)))
  206. }
  207. }
  208. }
  209. /*
  210. ao_module_newfw(launchConfig) => Create a new floatWindow object from the given paramters
  211. Most basic usage: (With auto assign UID, size and location)
  212. ao_module_newfw({
  213. url: "Dummy/index.html",
  214. title: "Dummy Module",
  215. appicon: "Dummy/img/icon.png"
  216. });
  217. Example usage that involve all configs:
  218. ao_module_newfw({
  219. url: "Dummy/index.html",
  220. uid: "CustomUUID",
  221. width: 1024,
  222. height: 768,
  223. appicon: "Dummy/img/icon.png",
  224. title: "Dummy Module",
  225. left: 100,
  226. top: 100,
  227. parent: ao_module_windowID,
  228. callback: "childCallbackHandler"
  229. });
  230. */
  231. function ao_module_newfw(launchConfig){
  232. if (launchConfig["parent"] == undefined){
  233. launchConfig["parent"] = ao_module_windowID;
  234. }
  235. if (ao_module_virtualDesktop){
  236. parent.newFloatWindow(launchConfig);
  237. }else{
  238. window.open(ao_root + launchConfig.url);
  239. }
  240. }
  241. /*
  242. File Selector
  243. Open a file selector and return selected item back to the current window
  244. Tips: Unlike the beta version, you can use this function in both Virtual Desktop Mode and normal mode.
  245. Possible selection type:
  246. type => {file / folder / all / new}
  247. Example usage:
  248. ao_module_openFileSelector(fileSelected, "user:/Desktop", "file",true);
  249. function fileSelected(filedata){
  250. for (var i=0; i < filedata.length; i++){
  251. var filename = filedata[i].filename;
  252. var filepath = filedata[i].filepath;
  253. //Do something here
  254. }
  255. }
  256. If you want to create a new file or folder object, you can use the following options paramters
  257. option = {
  258. defaultName: "newfile.txt", //Default filename used in new operation
  259. fnameOverride: "myfunction", //For those defined with window.myfunction
  260. filter: ["mp3","aac","ogg","flac","wav"] //File extension filter
  261. }
  262. */
  263. let ao_module_fileSelectionListener;
  264. let ao_module_fileSelectorWindow;
  265. function ao_module_openFileSelector(callback,root="user:/", type="file",allowMultiple=false, options=undefined){
  266. var initInfo = {
  267. root: root,
  268. type: type,
  269. allowMultiple: allowMultiple,
  270. listenerUUID: "",
  271. options: options
  272. }
  273. var initInfoEncoded = encodeURIComponent(JSON.stringify(initInfo))
  274. if (ao_module_virtualDesktop){
  275. var callbackname = callback.name;
  276. if (typeof(options) != "undefined" && typeof(options.fnameOverride) != "undefined"){
  277. callbackname = options.fnameOverride;
  278. }
  279. console.log(callbackname);
  280. parent.newFloatWindow({
  281. url: "SystemAO/file_system/file_selector.html#" + initInfoEncoded,
  282. width: 700,
  283. height: 440,
  284. appicon: "SystemAO/file_system/img/selector.png",
  285. title: "Open",
  286. parent: ao_module_windowID,
  287. callback: callbackname
  288. });
  289. }else{
  290. //Create a return listener base on localStorage
  291. let listenerUUID = "fileSelector_" + new Date().getTime();
  292. ao_module_fileSelectionListener = setInterval(function(){
  293. if (localStorage.getItem(listenerUUID) === undefined || localStorage.getItem(listenerUUID)=== null){
  294. //Not ready
  295. }else{
  296. //File ready!
  297. var selectedFiles = JSON.parse(localStorage.getItem(listenerUUID));
  298. console.log("Removing Localstorage Item " + listenerUUID);
  299. localStorage.removeItem(listenerUUID);
  300. setTimeout(function(){
  301. localStorage.removeItem(listenerUUID);
  302. },500);
  303. if(selectedFiles == "&&selection_canceled&&"){
  304. //Selection canceled. Returm empty array
  305. callback([]);
  306. }else{
  307. //Files Selected
  308. callback(selectedFiles);
  309. }
  310. clearInterval(ao_module_fileSelectionListener);
  311. ao_module_fileSelectorWindow.close();
  312. }
  313. },1000);
  314. //Open the file selector in a new tab
  315. initInfo.listenerUUID = listenerUUID;
  316. initInfoEncoded = encodeURIComponent(JSON.stringify(initInfo))
  317. ao_module_fileSelectorWindow = window.open(ao_root + "SystemAO/file_system/file_selector.html#" + initInfoEncoded,);
  318. }
  319. }
  320. //Check if there is parent to callback
  321. function ao_module_hasParentCallback(){
  322. if (ao_module_virtualDesktop){
  323. //Check if parent callback exists
  324. var thisFw;
  325. $(parent.window.document.body).find(".floatWindow").each(function(){
  326. if ($(this).attr('windowid') == ao_module_windowID){
  327. thisFw = $(this);
  328. }
  329. });
  330. var parentWindowID = thisFw.attr("parent");
  331. var parentCallback = thisFw.attr("callback");
  332. if (parentWindowID == "" || parentCallback == ""){
  333. //No parent window defined
  334. return false;
  335. }
  336. //Check if parent windows is alive
  337. var parentWindow = undefined;
  338. $(parent.window.document.body).find(".floatWindow").each(function(){
  339. if ($(this).attr('windowid') == parentWindowID){
  340. parentWindow = $(this);
  341. }
  342. });
  343. if (parentWindow == undefined){
  344. //parent window not exists
  345. return false;
  346. }
  347. //Parent callback is set and ready to callback
  348. return true;
  349. }else{
  350. return false
  351. }
  352. }
  353. //Callback to parent with results
  354. function ao_module_parentCallback(data=""){
  355. if (ao_module_virtualDesktop){
  356. var thisFw;
  357. $(parent.window.document.body).find(".floatWindow").each(function(){
  358. if ($(this).attr('windowid') == ao_module_windowID){
  359. thisFw = $(this);
  360. }
  361. });
  362. var parentWindowID = thisFw.attr("parent");
  363. var parentCallback = thisFw.attr("callback");
  364. if (parentWindowID == "" || parentCallback == ""){
  365. //No parent window defined
  366. console.log("Undefined parent window ID or callback name");
  367. return false;
  368. }
  369. var parentWindow = undefined;
  370. $(parent.window.document.body).find(".floatWindow").each(function(){
  371. if ($(this).attr('windowid') == parentWindowID){
  372. parentWindow = $(this);
  373. }
  374. });
  375. if (parentWindow == undefined){
  376. //parent window not exists
  377. console.log("Parent Window not exists!")
  378. return false;
  379. }
  380. $(parentWindow).find('iframe')[0].contentWindow.eval(parentCallback + "(" + JSON.stringify(data) + ");")
  381. //Focus the parent windows
  382. parent.MoveFloatWindowToTop(parentWindow);
  383. return true;
  384. }else{
  385. console.log("[ao_module] WARNING! Invalid call to parentCallback under non-virtualDesktop mode");
  386. return false;
  387. }
  388. }
  389. function ao_module_agirun(scriptpath, data, callback, failedcallback = undefined, timeout=0){
  390. $.ajax({
  391. url: ao_root + "system/ajgi/interface?script=" + scriptpath,
  392. method: "POST",
  393. data: data,
  394. success: function(data){
  395. if (typeof(callback) != "undefined"){
  396. callback(data);
  397. }
  398. },
  399. error: function(){
  400. if (typeof failedcallback != "undefined"){
  401. failedcallback();
  402. }
  403. },
  404. timeout: timeout
  405. });
  406. }
  407. function ao_module_uploadFile(file, targetPath, callback=undefined, progressCallback=undefined, failedcallback=undefined) {
  408. let url = ao_root + 'system/file_system/upload'
  409. let formData = new FormData()
  410. let xhr = new XMLHttpRequest()
  411. formData.append('file', file);
  412. formData.append('path', targetPath);
  413. xhr.open('POST', url, true);
  414. xhr.upload.addEventListener("progress", function(e) {
  415. if (progressCallback !== undefined){
  416. progressCallback((e.loaded * 100.0 / e.total) || 100);
  417. }
  418. });
  419. xhr.addEventListener('readystatechange', function(e) {
  420. if (xhr.readyState == 4 && xhr.status == 200) {
  421. if (callback !== undefined){
  422. callback(e.target.response);
  423. }
  424. }
  425. else if (xhr.readyState == 4 && xhr.status != 200) {
  426. if (failedcallback !== undefined){
  427. failedcallback(xhr.status);
  428. }
  429. }
  430. })
  431. xhr.send(formData);
  432. }
  433. /*
  434. ao_module_storage, allow key-value storage per module settings.
  435. WARNING: NOT CROSS USER READ-WRITABLE
  436. ao_module_storage.setStorage(moduleName, configName,configValue);
  437. ao_module_storage.loadStorage(moduleName, configName);
  438. */
  439. class ao_module_storage {
  440. static setStorage(moduleName, configName,configValue){
  441. $.ajax({
  442. type: 'GET',
  443. url: ao_root + "system/file_system/preference",
  444. data: {key: moduleName + "/" + configName,value:configValue},
  445. success: function(data){},
  446. async:true
  447. });
  448. return true;
  449. }
  450. static loadStorage(moduleName, configName){
  451. var result = "";
  452. $.ajax({
  453. type: 'GET',
  454. url: ao_root + "system/file_system/preference",
  455. data: {key: moduleName + "/" + configName},
  456. success: function(data){
  457. if (data.error !== undefined){
  458. result = "";
  459. }else{
  460. result = data;
  461. }
  462. },
  463. error: function(data){result = "";},
  464. async:false,
  465. timeout: 3000
  466. });
  467. return result;
  468. }
  469. }
  470. class ao_module_codec{
  471. //Decode umfilename into standard filename in utf-8, which umfilename usually start with "inith"
  472. //Example: ao_module_codec.decodeUmFilename(umfilename_here);
  473. static decodeUmFilename(umfilename){
  474. if (umfilename.includes("inith")){
  475. var data = umfilename.split(".");
  476. if (data.length == 1){
  477. //This is a filename without extension
  478. data = data[0].replace("inith","");
  479. var decodedname = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(data));
  480. if (decodedname != "false"){
  481. //This is a umfilename
  482. return decodedname;
  483. }else{
  484. //This is not a umfilename
  485. return umfilename;
  486. }
  487. }else{
  488. //This is a filename with extension
  489. var extension = data.pop();
  490. var filename = data[0];
  491. filename = filename.replace("inith",""); //Javascript replace only remove the first instances (i.e. the first inith in filename)
  492. var decodedname = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(filename));
  493. if (decodedname != "false"){
  494. //This is a umfilename
  495. return decodedname + "." + extension;
  496. }else{
  497. //This is not a umfilename
  498. return umfilename;
  499. }
  500. }
  501. }else{
  502. //This is not umfilename as it doesn't have the inith prefix
  503. return umfilename;
  504. }
  505. }
  506. //Encode filename to UMfilename
  507. //Example: ao_module_codec.encodeUMFilename("test.stl");
  508. static encodeUMFilename(filename){
  509. if (filename.substring(0,5) != "inith"){
  510. //Check if the filename include extension.
  511. if (filename.includes(".")){
  512. //Filename with extension. pop it out first.
  513. var info = filename.split(".");
  514. var ext = info.pop();
  515. var filenameOnly = info.join(".");
  516. var encodedFilename = "inith" + ao_module_codec.decode_utf8(ao_module_codec.bin2hex(filenameOnly)) + "." + ext;
  517. return encodedFilename;
  518. }else{
  519. //Filename with no extension. Convert the whole name into UMfilename
  520. var encodedFilename = "inith" + ao_module_codec.decode_utf8(ao_module_codec.bin2hex(filename));
  521. return encodedFilename;
  522. }
  523. }else{
  524. //This is already a UMfilename. return the raw filename.
  525. return filename;
  526. }
  527. }
  528. //Decode hexFoldername into standard foldername in utf-8, return the original name if it is not a hex foldername
  529. //Example: ao_module_codec.decodeHexFoldername(hexFolderName_here);
  530. static decodeHexFoldername(folderName, prefix=true){
  531. var decodedFoldername = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(folderName));
  532. if (decodedFoldername == "false"){
  533. //This is not a hex encoded foldername
  534. decodedFoldername = folderName;
  535. }else{
  536. //This is a hex encoded foldername
  537. if (prefix){
  538. decodedFoldername = "*" + decodedFoldername;
  539. }else{
  540. decodedFoldername =decodedFoldername;
  541. }
  542. }
  543. return decodedFoldername;
  544. }
  545. //Encode foldername into hexfoldername
  546. //Example: ao_module_codec.encodeHexFoldername("test");
  547. static encodeHexFoldername(folderName){
  548. var encodedFilename = "";
  549. if (ao_module_codec.decodeHexFoldername(folderName) == folderName){
  550. //This is not hex foldername. Encode it
  551. encodedFilename = ao_module_codec.decode_utf8(ao_module_codec.bin2hex(folderName));
  552. }else{
  553. //This folder name already encoded. Return the original value
  554. encodedFilename = folderName;
  555. }
  556. return encodedFilename;
  557. }
  558. static hex2bin(s){
  559. var ret = []
  560. var i = 0
  561. var l
  562. s += ''
  563. for (l = s.length; i < l; i += 2) {
  564. var c = parseInt(s.substr(i, 1), 16)
  565. var k = parseInt(s.substr(i + 1, 1), 16)
  566. if (isNaN(c) || isNaN(k)) return false
  567. ret.push((c << 4) | k)
  568. }
  569. return String.fromCharCode.apply(String, ret)
  570. }
  571. static bin2hex(s){
  572. var i
  573. var l
  574. var o = ''
  575. var n
  576. s += ''
  577. for (i = 0, l = s.length; i < l; i++) {
  578. n = s.charCodeAt(i)
  579. .toString(16)
  580. o += n.length < 2 ? '0' + n : n
  581. }
  582. return o
  583. }
  584. static decode_utf8(s) {
  585. return decodeURIComponent(escape(s));
  586. }
  587. }
  588. /**
  589. ArOZ Online Module Utils for quick deploy of ArOZ Online WebApps
  590. ao_module_utils.objectToAttr(object); //object to DOM attr
  591. ao_module_utils.attrToObject(attr); //DOM attr to Object
  592. ao_module_utils.getRandomUID(); //Get random UUID from timestamp
  593. ao_module_utils.getIconFromExt(ext); //Get icon tag from file extension
  594. ao_module_utils.getDropFileInfo(dropEvent); //Get the filepath and filename list from file explorer drag drop
  595. ao_module_utils.formatBytes(byte, decimals); //Format file byte size to human readable size
  596. **/
  597. class ao_module_utils{
  598. //Two simple functions for converting any Javascript object into string that can be put into the attr value of an DOM object
  599. static objectToAttr(object){
  600. return encodeURIComponent(JSON.stringify(object));
  601. }
  602. static attrToObject(attr){
  603. return JSON.parse(decodeURIComponent(attr));
  604. }
  605. //Get a random id for a new floatWindow, use with var uid = ao_module_utils.getRandomUID();
  606. static getRandomUID(){
  607. return new Date().getTime();
  608. }
  609. static stringToBlob(text, mimetype="text/plain"){
  610. var blob = new Blob([text], { type: mimetype });
  611. return blob
  612. }
  613. static blobToFile(blob, filename, mimetype="text/plain"){
  614. var file = new File([blob], filename, {type: mimetype});
  615. return file
  616. }
  617. //Get the icon of a file with given extension (ext), use with ao_module_utils.getIconFromExt("ext");
  618. static getIconFromExt(ext){
  619. var ext = ext.toLowerCase().trim();
  620. var iconList={
  621. md:"file text outline",
  622. txt:"file text outline",
  623. pdf:"file pdf outline",
  624. doc:"file word outline",
  625. docx:"file word outline",
  626. odt:"file word outline",
  627. xlsx:"file excel outline",
  628. ods:"file excel outline",
  629. ppt:"file powerpoint outline",
  630. pptx:"file powerpoint outline",
  631. odp:"file powerpoint outline",
  632. jpg:"file image outline",
  633. png:"file image outline",
  634. jpeg:"file image outline",
  635. gif:"file image outline",
  636. odg:"file image outline",
  637. psd:"file image outline",
  638. zip:"file archive outline",
  639. '7z':"file archive outline",
  640. rar:"file archive outline",
  641. tar:"file archive outline",
  642. mp3:"file audio outline",
  643. m4a:"file audio outline",
  644. flac:"file audio outline",
  645. wav:"file audio outline",
  646. aac:"file audio outline",
  647. mp4:"file video outline",
  648. webm:"file video outline",
  649. php:"file code outline",
  650. html:"file code outline",
  651. htm:"file code outline",
  652. js:"file code outline",
  653. css:"file code outline",
  654. xml:"file code outline",
  655. json:"file code outline",
  656. csv:"file code outline",
  657. odf:"file code outline",
  658. bmp:"file image outline",
  659. rtf:"file text outline",
  660. wmv:"file video outline",
  661. mkv:"file video outline",
  662. ogg:"file audio outline",
  663. stl:"cube",
  664. obj:"cube",
  665. "3ds":"cube",
  666. fbx:"cube",
  667. collada:"cube",
  668. step:"cube",
  669. iges:"cube",
  670. gcode:"cube",
  671. shortcut:"external square",
  672. opus:"file audio outline",
  673. apscene:"cubes"
  674. };
  675. var icon = "";
  676. if (ext == ""){
  677. icon = "folder outline";
  678. }else{
  679. icon = iconList[ext];
  680. if (icon == undefined){
  681. icon = "file outline"
  682. }
  683. }
  684. return icon;
  685. }
  686. //Get the drop file properties {filepath: xxx, filename: xxx} from file drop events from file exploere
  687. static getDropFileInfo(dropEvent){
  688. if (dropEvent.dataTransfer.getData("filedata") !== ""){
  689. var filelist = dropEvent.dataTransfer.getData("filedata");
  690. filelist = JSON.parse(filelist);
  691. return filelist;
  692. }
  693. }
  694. static readFileFromFileObject(fileObject, successCallback, failedCallback=undefined){
  695. let reader = new FileReader();
  696. reader.readAsText(fileObject);
  697. reader.onload = function() {
  698. successCallback(reader.result);
  699. };
  700. reader.onerror = function() {
  701. if (failedCallback != undefined){
  702. failedCallback(reader.error);
  703. }else{
  704. console.log(reader.error);
  705. }
  706. };
  707. }
  708. 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]}
  709. }