ao_module.js 31 KB

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