ao_module.js 27 KB

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