ao_module.js 25 KB

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