ao_module.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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){
  486. var result = "";
  487. $.ajax({
  488. type: 'GET',
  489. url: ao_root + "system/file_system/preference",
  490. data: {key: moduleName + "/" + configName},
  491. success: function(data){
  492. if (data.error !== undefined){
  493. result = "";
  494. }else{
  495. result = data;
  496. }
  497. },
  498. error: function(data){result = "";},
  499. async:false,
  500. timeout: 3000
  501. });
  502. return result;
  503. }
  504. }
  505. class ao_module_codec{
  506. //Decode umfilename into standard filename in utf-8, which umfilename usually start with "inith"
  507. //Example: ao_module_codec.decodeUmFilename(umfilename_here);
  508. static decodeUmFilename(umfilename){
  509. if (umfilename.includes("inith")){
  510. var data = umfilename.split(".");
  511. if (data.length == 1){
  512. //This is a filename without extension
  513. data = data[0].replace("inith","");
  514. var decodedname = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(data));
  515. if (decodedname != "false"){
  516. //This is a umfilename
  517. return decodedname;
  518. }else{
  519. //This is not a umfilename
  520. return umfilename;
  521. }
  522. }else{
  523. //This is a filename with extension
  524. var extension = data.pop();
  525. var filename = data[0];
  526. filename = filename.replace("inith",""); //Javascript replace only remove the first instances (i.e. the first inith in filename)
  527. var decodedname = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(filename));
  528. if (decodedname != "false"){
  529. //This is a umfilename
  530. return decodedname + "." + extension;
  531. }else{
  532. //This is not a umfilename
  533. return umfilename;
  534. }
  535. }
  536. }else{
  537. //This is not umfilename as it doesn't have the inith prefix
  538. return umfilename;
  539. }
  540. }
  541. //Encode filename to UMfilename
  542. //Example: ao_module_codec.encodeUMFilename("test.stl");
  543. static encodeUMFilename(filename){
  544. if (filename.substring(0,5) != "inith"){
  545. //Check if the filename include extension.
  546. if (filename.includes(".")){
  547. //Filename with extension. pop it out first.
  548. var info = filename.split(".");
  549. var ext = info.pop();
  550. var filenameOnly = info.join(".");
  551. var encodedFilename = "inith" + ao_module_codec.decode_utf8(ao_module_codec.bin2hex(filenameOnly)) + "." + ext;
  552. return encodedFilename;
  553. }else{
  554. //Filename with no extension. Convert the whole name into UMfilename
  555. var encodedFilename = "inith" + ao_module_codec.decode_utf8(ao_module_codec.bin2hex(filename));
  556. return encodedFilename;
  557. }
  558. }else{
  559. //This is already a UMfilename. return the raw filename.
  560. return filename;
  561. }
  562. }
  563. //Decode hexFoldername into standard foldername in utf-8, return the original name if it is not a hex foldername
  564. //Example: ao_module_codec.decodeHexFoldername(hexFolderName_here);
  565. static decodeHexFoldername(folderName, prefix=true){
  566. var decodedFoldername = ao_module_codec.decode_utf8(ao_module_codec.hex2bin(folderName));
  567. if (decodedFoldername == "false"){
  568. //This is not a hex encoded foldername
  569. decodedFoldername = folderName;
  570. }else{
  571. //This is a hex encoded foldername
  572. if (prefix){
  573. decodedFoldername = "*" + decodedFoldername;
  574. }else{
  575. decodedFoldername =decodedFoldername;
  576. }
  577. }
  578. return decodedFoldername;
  579. }
  580. //Encode foldername into hexfoldername
  581. //Example: ao_module_codec.encodeHexFoldername("test");
  582. static encodeHexFoldername(folderName){
  583. var encodedFilename = "";
  584. if (ao_module_codec.decodeHexFoldername(folderName) == folderName){
  585. //This is not hex foldername. Encode it
  586. encodedFilename = ao_module_codec.decode_utf8(ao_module_codec.bin2hex(folderName));
  587. }else{
  588. //This folder name already encoded. Return the original value
  589. encodedFilename = folderName;
  590. }
  591. return encodedFilename;
  592. }
  593. static hex2bin(s){
  594. var ret = []
  595. var i = 0
  596. var l
  597. s += ''
  598. for (l = s.length; i < l; i += 2) {
  599. var c = parseInt(s.substr(i, 1), 16)
  600. var k = parseInt(s.substr(i + 1, 1), 16)
  601. if (isNaN(c) || isNaN(k)) return false
  602. ret.push((c << 4) | k)
  603. }
  604. return String.fromCharCode.apply(String, ret)
  605. }
  606. static bin2hex(s){
  607. var i
  608. var l
  609. var o = ''
  610. var n
  611. s += ''
  612. for (i = 0, l = s.length; i < l; i++) {
  613. n = s.charCodeAt(i)
  614. .toString(16)
  615. o += n.length < 2 ? '0' + n : n
  616. }
  617. return o
  618. }
  619. static decode_utf8(s) {
  620. return decodeURIComponent(escape(s));
  621. }
  622. }
  623. /**
  624. ArOZ Online Module Utils for quick deploy of ArOZ Online WebApps
  625. ao_module_utils.objectToAttr(object); //object to DOM attr
  626. ao_module_utils.attrToObject(attr); //DOM attr to Object
  627. ao_module_utils.getRandomUID(); //Get random UUID from timestamp
  628. ao_module_utils.getIconFromExt(ext); //Get icon tag from file extension
  629. ao_module_utils.getDropFileInfo(dropEvent); //Get the filepath and filename list from file explorer drag drop
  630. ao_module_utils.formatBytes(byte, decimals); //Format file byte size to human readable size
  631. ao_module_utils.timeConverter(unix_timestamp); //Get human readable timestamp
  632. **/
  633. class ao_module_utils{
  634. //Two simple functions for converting any Javascript object into string that can be put into the attr value of an DOM object
  635. static objectToAttr(object){
  636. return encodeURIComponent(JSON.stringify(object));
  637. }
  638. static attrToObject(attr){
  639. return JSON.parse(decodeURIComponent(attr));
  640. }
  641. //Get a random id for a new floatWindow, use with var uid = ao_module_utils.getRandomUID();
  642. static getRandomUID(){
  643. return new Date().getTime();
  644. }
  645. static stringToBlob(text, mimetype="text/plain"){
  646. var blob = new Blob([text], { type: mimetype });
  647. return blob
  648. }
  649. static blobToFile(blob, filename, mimetype="text/plain"){
  650. var file = new File([blob], filename, {type: mimetype});
  651. return file
  652. }
  653. //Get the icon of a file with given extension (ext), use with ao_module_utils.getIconFromExt("ext");
  654. static getIconFromExt(ext){
  655. var ext = ext.toLowerCase().trim();
  656. var iconList={
  657. md:"file text outline",
  658. txt:"file text outline",
  659. pdf:"file pdf outline",
  660. doc:"file word outline",
  661. docx:"file word outline",
  662. odt:"file word outline",
  663. xlsx:"file excel outline",
  664. ods:"file excel outline",
  665. ppt:"file powerpoint outline",
  666. pptx:"file powerpoint outline",
  667. odp:"file powerpoint outline",
  668. jpg:"file image outline",
  669. png:"file image outline",
  670. jpeg:"file image outline",
  671. gif:"file image outline",
  672. odg:"file image outline",
  673. psd:"file image outline",
  674. zip:"file archive outline",
  675. '7z':"file archive outline",
  676. rar:"file archive outline",
  677. tar:"file archive outline",
  678. mp3:"file audio outline",
  679. m4a:"file audio outline",
  680. flac:"file audio outline",
  681. wav:"file audio outline",
  682. aac:"file audio outline",
  683. mp4:"file video outline",
  684. webm:"file video outline",
  685. php:"file code outline",
  686. html:"file code outline",
  687. htm:"file code outline",
  688. js:"file code outline",
  689. css:"file code outline",
  690. xml:"file code outline",
  691. json:"file code outline",
  692. csv:"file code outline",
  693. odf:"file code outline",
  694. bmp:"file image outline",
  695. rtf:"file text outline",
  696. wmv:"file video outline",
  697. mkv:"file video outline",
  698. ogg:"file audio outline",
  699. stl:"cube",
  700. obj:"cube",
  701. "3ds":"cube",
  702. fbx:"cube",
  703. collada:"cube",
  704. step:"cube",
  705. iges:"cube",
  706. gcode:"cube",
  707. shortcut:"external square",
  708. opus:"file audio outline",
  709. apscene:"cubes"
  710. };
  711. var icon = "";
  712. if (ext == ""){
  713. icon = "folder outline";
  714. }else{
  715. icon = iconList[ext];
  716. if (icon == undefined){
  717. icon = "file outline"
  718. }
  719. }
  720. return icon;
  721. }
  722. //Get the drop file properties {filepath: xxx, filename: xxx} from file drop events from file exploere
  723. static getDropFileInfo(dropEvent){
  724. if (dropEvent.dataTransfer.getData("filedata") !== ""){
  725. var filelist = dropEvent.dataTransfer.getData("filedata");
  726. filelist = JSON.parse(filelist);
  727. return filelist;
  728. }
  729. }
  730. static readFileFromFileObject(fileObject, successCallback, failedCallback=undefined){
  731. let reader = new FileReader();
  732. reader.readAsText(fileObject);
  733. reader.onload = function() {
  734. successCallback(reader.result);
  735. };
  736. reader.onerror = function() {
  737. if (failedCallback != undefined){
  738. failedCallback(reader.error);
  739. }else{
  740. console.log(reader.error);
  741. }
  742. };
  743. }
  744. static durationConverter(seconds){
  745. var days = Math.floor(seconds / 86400);
  746. seconds -= days * 86400;
  747. var hours = Math.floor(seconds / 3600) % 24;
  748. seconds -= hours * 3600;
  749. var minutes = Math.floor(seconds / 60) % 60;
  750. seconds -= minutes * 60;
  751. var seconds = seconds % 60;
  752. var resultDuration = "";
  753. if (days > 0){
  754. resultDuration += days + " Day";
  755. if (days > 1){
  756. resultDuration+= "s"
  757. }
  758. resultDuration += " "
  759. }
  760. if (hours > 0){
  761. resultDuration += hours + " Hour"
  762. if (hours > 1){
  763. resultDuration += "s"
  764. }
  765. resultDuration += " "
  766. }
  767. if (minutes > 0){
  768. resultDuration += minutes + " Minute"
  769. if (minutes > 1){
  770. resultDuration += "s"
  771. }
  772. resultDuration += " "
  773. }
  774. if (seconds > 0){
  775. resultDuration += seconds + " Secound"
  776. if (seconds > 1){
  777. resultDuration += "s"
  778. }
  779. resultDuration += " "
  780. }
  781. return resultDuration;
  782. }
  783. static timeConverter(UNIX_timestamp){
  784. var a = new Date(UNIX_timestamp * 1000);
  785. var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  786. var year = a.getFullYear();
  787. var month = months[a.getMonth()];
  788. var date = a.getDate();
  789. var hour = a.getHours().toString().padStart(2, "0");
  790. var min = a.getMinutes().toString().padStart(2, "0");
  791. var sec = a.getSeconds().toString().padStart(2, "0");
  792. var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  793. return time;
  794. }
  795. static getWebSocketEndpoint(){
  796. let protocol = "wss://";
  797. if (location.protocol !== 'https:') {
  798. protocol = "ws://";
  799. }
  800. var port = window.location.port;
  801. if (window.location.port == ""){
  802. if (location.protocol !== 'https:') {
  803. port = "80";
  804. }else{
  805. port = "443";
  806. }
  807. }
  808. wsept = (protocol + window.location.hostname + ":" + port);
  809. return wsept;
  810. }
  811. 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]}
  812. }