ao_module.js 32 KB

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