ao_module.js 31 KB

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