ao_module.js 39 KB

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