ao_module.js 32 KB

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