ao_module.js 27 KB

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