ao_module.js 25 KB

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