helpers.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. class Helpers {
  2. constructor() {
  3. console.log("helpers constructor");
  4. // List of valid ID characters for use in an instance.
  5. this.ValidIDChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  6. // List of valid extensions for VWF components.
  7. this.template_extensions = ["", ".yaml", ".json"];
  8. this.applicationRoot = "/"; //app
  9. }
  10. async Process(updatedURL) {
  11. var result =
  12. { 'public_path': "/", 'application': undefined, 'instance': undefined, 'private_path': undefined };
  13. var segments = this.GenerateSegments(updatedURL);
  14. var extension = undefined;
  15. while ((segments.length > 0) && (await this.IsExist(this.JoinPath(result['public_path'], segments[0])))) {
  16. result['public_path'] = this.JoinPath(result['public_path'], segments.shift());
  17. }
  18. if ((segments.length > 0) && (extension = await this.GetExtension(this.JoinPath(result['public_path'], segments[0])))) {
  19. result['application'] = segments.shift();
  20. } else if (extension = await this.GetExtension(this.JoinPath(result['public_path'], "index.vwf"))) {
  21. result['application'] = "index.vwf";
  22. }
  23. if (extension) {
  24. if ((segments.length > 0) && (this.IsInstanceID(segments[0]))) {
  25. result['instance'] = segments.shift();
  26. }
  27. if (segments.length > 0) {
  28. result['private_path'] = segments.join("/");
  29. }
  30. }
  31. return result;
  32. }
  33. // IsInstanceID tests if the passed in potential Instance ID
  34. // is a valid instance id.
  35. IsInstanceID(potentialInstanceID) {
  36. if (potentialInstanceID.match(/^[0-9A-Za-z]{16}$/)) {
  37. return true;
  38. }
  39. return false;
  40. }
  41. // GenerateInstanceID function creates a randomly generated instance ID.
  42. GenerateInstanceID() {
  43. var text = "";
  44. for (var i = 0; i < 16; i++)
  45. text += this.ValidIDChars.charAt(Math.floor(Math.random() * this.ValidIDChars.length));
  46. return text;
  47. }
  48. // JoinPath
  49. // Takes multiple arguments, joins them together into one path.
  50. JoinPath( /* arguments */) {
  51. var result = "";
  52. if (arguments.length > 0) {
  53. if (arguments[0]) {
  54. result = arguments[0];
  55. }
  56. for (var index = 1; index < arguments.length; index++) {
  57. var newSegment = arguments[index];
  58. if (newSegment == undefined) {
  59. newSegment = "";
  60. }
  61. if ((newSegment[0] == "/") && (result[result.length - 1] == "/")) {
  62. result = result + newSegment.slice(1);
  63. } else if ((newSegment[0] == "/") || (result[result.length - 1] == "/")) {
  64. result = result + newSegment;
  65. } else {
  66. result = result + "/" + newSegment;
  67. }
  68. //result = libpath.join( result, newSegment );
  69. }
  70. }
  71. return result;
  72. }
  73. async IsFileExist(path) {
  74. var seperatorFixedPath = path.slice(1);//path.replace(/\//g, '/');
  75. let worldName = seperatorFixedPath.split('/')[0];
  76. let fileName = seperatorFixedPath.replace(worldName + '/', "");
  77. let doc = await _LCS_WORLD_USER.get('worlds').get(worldName).get(fileName).once().then();
  78. if (doc) {
  79. return true
  80. }
  81. return false
  82. }
  83. async IsExist(path) {
  84. var seperatorFixedPath = path.slice(1);//path.replace(/\//g, '/');
  85. let doc = await _LCS_WORLD_USER.get('worlds').get(seperatorFixedPath).once().then();
  86. if (doc) {
  87. return true
  88. }
  89. return false
  90. }
  91. // GenerateSegments takes a string, breaks it into
  92. // '/' separated segments, and removes potential
  93. // blank first and last segments.
  94. GenerateSegments(argument) {
  95. var result = argument.split("/");
  96. if (result.length > 0) {
  97. if (result[0] == "") {
  98. result.shift();
  99. }
  100. }
  101. if (result.length > 0) {
  102. if (result[result.length - 1] == "") {
  103. result.pop();
  104. }
  105. }
  106. return result;
  107. }
  108. async GetExtension(path) {
  109. if (path.match(/\.vwf$/)) {
  110. for (const res of this.template_extensions) {
  111. let check = await this.IsFileExist(this.JoinPath(path + res).split(".").join("_"));
  112. if (check) return res
  113. }
  114. }
  115. return undefined;
  116. }
  117. get appPath() {
  118. return JSON.parse(localStorage.getItem('lcs_app')).path.public_path.slice(1)
  119. }
  120. get worldStateName() {
  121. let appConfig = JSON.parse(localStorage.getItem('lcs_app'));
  122. var saveName = appConfig.path.public_path.slice(1);
  123. let privatePath = appConfig.path.private_path;
  124. if (privatePath) {
  125. if (privatePath.indexOf('load') !== -1) {
  126. saveName = privatePath.split('/')[1];
  127. }
  128. }
  129. return saveName
  130. }
  131. getRoot(noUser) {
  132. var app = window.location.pathname;
  133. var pathSplit = app.split('/');
  134. if (pathSplit[0] == "") {
  135. pathSplit.shift();
  136. }
  137. if (pathSplit[pathSplit.length - 1] == "") {
  138. pathSplit.pop();
  139. }
  140. var inst = undefined;
  141. var instIndex = pathSplit.length - 1;
  142. if (pathSplit.length > 2) {
  143. if (pathSplit[pathSplit.length - 2] == "load") {
  144. instIndex = pathSplit.length - 3;
  145. }
  146. }
  147. if (pathSplit.length > 3) {
  148. if (pathSplit[pathSplit.length - 3] == "load") {
  149. instIndex = pathSplit.length - 4;
  150. }
  151. }
  152. inst = pathSplit[instIndex];
  153. var root = "";
  154. for (var i = 0; i < instIndex; i++) {
  155. if (root != "") {
  156. root = root + "/";
  157. }
  158. root = root + pathSplit[i];
  159. }
  160. if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  161. if (noUser) {
  162. return {
  163. "root": root.replace(pathSplit[0] + '/', ""),
  164. "inst": inst
  165. }
  166. } else {
  167. return {
  168. "root": root,
  169. "inst": inst
  170. }
  171. }
  172. }
  173. get worldUser() {
  174. return this.getRoot(false).root.split('/')[0];
  175. }
  176. randId() {
  177. return '_' + Math.random().toString(36).substr(2, 9);
  178. }
  179. getRandomInt(min, max) {
  180. min = Math.ceil(min);
  181. max = Math.floor(max);
  182. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  183. }
  184. GUID() {
  185. var S4 = function () {
  186. return Math.floor(
  187. Math.random() * 0x10000 /* 65536 */
  188. ).toString(16);
  189. };
  190. return (
  191. S4() + S4() + "-" +
  192. S4() + "-" +
  193. S4() + "-" +
  194. S4() + "-" +
  195. S4() + S4() + S4()
  196. );
  197. }
  198. async sha256(message) {
  199. // encode as UTF-8
  200. const msgBuffer = new TextEncoder('utf-8').encode(message);
  201. // hash the message
  202. const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  203. // convert ArrayBuffer to Array
  204. const hashArray = Array.from(new Uint8Array(hashBuffer));
  205. // convert bytes to hex string
  206. const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
  207. return hashHex;
  208. }
  209. replaceSubStringALL(target, search, replacement) {
  210. return target.split(search).join(replacement);
  211. };
  212. async getHtmlText(url) {
  213. let file = await fetch(url, { method: 'get' });
  214. let text = await file.text();
  215. return text
  216. }
  217. removeProps(obj) {
  218. Object.keys(obj).forEach(key =>
  219. (key === 'id' || key === 'patches' || key === 'random' || key === 'sequence') && delete obj[key] ||
  220. (obj[key] && typeof obj[key] === 'object') && this.removeProps(obj[key])
  221. );
  222. return obj;
  223. };
  224. getNodeDef(nodeID) {
  225. let node = vwf.getNode(nodeID, true);
  226. let nodeDefPure = this.removeProps(node);
  227. let nodeDef = this.removeGrammarObj(nodeDefPure);
  228. return nodeDef
  229. }
  230. removeGrammarObj(obj) {
  231. Object.keys(obj).forEach(key =>
  232. (key === 'grammar' || key === 'semantics') && delete obj[key] ||
  233. (obj[key] && typeof obj[key] === 'object') && this.removeGrammarObj(obj[key])
  234. );
  235. return obj;
  236. };
  237. httpGet(url) {
  238. return new Promise(function (resolve, reject) {
  239. // do the usual Http request
  240. let request = new XMLHttpRequest();
  241. request.open('GET', url);
  242. request.onload = function () {
  243. if (request.status == 200) {
  244. resolve(request.response);
  245. } else {
  246. reject(Error(request.statusText));
  247. }
  248. };
  249. request.onerror = function () {
  250. reject(Error('Network Error'));
  251. };
  252. request.send();
  253. });
  254. }
  255. async httpGetJson(url) {
  256. // check if the URL looks like a JSON file and call httpGet.
  257. let regex = /\.(json)$/i;
  258. if (regex.test(url)) {
  259. // call the async function, wait for the result
  260. return await this.httpGet(url);
  261. } else {
  262. throw Error('Bad Url Format');
  263. }
  264. }
  265. }
  266. export { Helpers }