ao_module.js 31 KB

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