helpers.js 9.8 KB

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