helpers.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  80. var seperatorFixedPath = path.slice(1);//path.replace(/\//g, '/');
  81. let worldName = seperatorFixedPath.split('/')[0];
  82. let fileName = seperatorFixedPath.replace(worldName + '/', "");
  83. let doc = await userDB.get('worlds').get(worldName).get(fileName).then();
  84. if (doc) {
  85. return true
  86. }
  87. return false
  88. }
  89. async IsExist(path) {
  90. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  91. var seperatorFixedPath = path.slice(1);//path.replace(/\//g, '/');
  92. let doc = await userDB.get('worlds').get(seperatorFixedPath).then();
  93. if (doc) {
  94. return true
  95. }
  96. return false
  97. }
  98. // GenerateSegments takes a string, breaks it into
  99. // '/' separated segments, and removes potential
  100. // blank first and last segments.
  101. GenerateSegments(argument) {
  102. var result = argument.split("/");
  103. if (result.length > 0) {
  104. if (result[0] == "") {
  105. result.shift();
  106. }
  107. }
  108. if (result.length > 0) {
  109. if (result[result.length - 1] == "") {
  110. result.pop();
  111. }
  112. }
  113. return result;
  114. }
  115. async GetExtension(path) {
  116. if (path.match(/\.vwf$/)) {
  117. for (const res of this.template_extensions) {
  118. let check = await this.IsFileExist(this.JoinPath(path + res).split(".").join("_"));
  119. if (check) return res
  120. }
  121. }
  122. return undefined;
  123. }
  124. get appPath() {
  125. return JSON.parse(localStorage.getItem('lcs_app')).path.public_path.slice(1)
  126. }
  127. get worldStateName() {
  128. let appConfig = JSON.parse(localStorage.getItem('lcs_app'));
  129. var saveName = appConfig.path.public_path.slice(1);
  130. let privatePath = appConfig.path.private_path;
  131. if (privatePath) {
  132. if (privatePath.indexOf('load') !== -1) {
  133. saveName = privatePath.split('/')[1];
  134. }
  135. }
  136. return saveName
  137. }
  138. getRoot(noUser) {
  139. var app = window.location.pathname;
  140. var pathSplit = app.split('/');
  141. if (pathSplit[0] == "") {
  142. pathSplit.shift();
  143. }
  144. if (pathSplit[pathSplit.length - 1] == "") {
  145. pathSplit.pop();
  146. }
  147. var inst = undefined;
  148. var instIndex = pathSplit.length - 1;
  149. if (pathSplit.length > 2) {
  150. if (pathSplit[pathSplit.length - 2] == "load") {
  151. instIndex = pathSplit.length - 3;
  152. }
  153. }
  154. if (pathSplit.length > 3) {
  155. if (pathSplit[pathSplit.length - 3] == "load") {
  156. instIndex = pathSplit.length - 4;
  157. }
  158. }
  159. inst = pathSplit[instIndex];
  160. var root = "";
  161. for (var i = 0; i < instIndex; i++) {
  162. if (root != "") {
  163. root = root + "/";
  164. }
  165. root = root + pathSplit[i];
  166. }
  167. if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  168. if (noUser) {
  169. return {
  170. "root": root.replace(pathSplit[0] + '/', ""),
  171. "inst": inst
  172. }
  173. } else {
  174. return {
  175. "root": root,
  176. "inst": inst
  177. }
  178. }
  179. }
  180. get worldUser() {
  181. return this.getRoot(false).root.split('/')[0];
  182. }
  183. randId() {
  184. return '_' + Math.random().toString(36).substr(2, 9);
  185. }
  186. getRandomInt(min, max) {
  187. min = Math.ceil(min);
  188. max = Math.floor(max);
  189. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  190. }
  191. GUID() {
  192. var S4 = function () {
  193. return Math.floor(
  194. Math.random() * 0x10000 /* 65536 */
  195. ).toString(16);
  196. };
  197. return (
  198. S4() + S4() + "-" +
  199. S4() + "-" +
  200. S4() + "-" +
  201. S4() + "-" +
  202. S4() + S4() + S4()
  203. );
  204. }
  205. async sha256(message) {
  206. // encode as UTF-8
  207. const msgBuffer = new TextEncoder('utf-8').encode(message);
  208. // hash the message
  209. const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  210. // convert ArrayBuffer to Array
  211. const hashArray = Array.from(new Uint8Array(hashBuffer));
  212. // convert bytes to hex string
  213. const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
  214. return hashHex;
  215. }
  216. replaceSubStringALL(target, search, replacement) {
  217. return target.split(search).join(replacement);
  218. };
  219. async getHtmlText(url) {
  220. let file = await fetch(url, { method: 'get' });
  221. let text = await file.text();
  222. return text
  223. }
  224. removeProps(obj) {
  225. Object.keys(obj).forEach(key =>
  226. (key === 'id' || key === 'patches' || key === 'random' || key === 'sequence') && delete obj[key] ||
  227. (obj[key] && typeof obj[key] === 'object') && this.removeProps(obj[key])
  228. );
  229. return obj;
  230. };
  231. getNodeDef(nodeID) {
  232. let node = vwf.getNode(nodeID, true);
  233. let nodeDefPure = this.removeProps(node);
  234. let nodeDef = this.removeGrammarObj(nodeDefPure);
  235. let finalDef = this.replaceFloatArraysInNodeDef(nodeDef);
  236. return finalDef
  237. }
  238. replaceFloatArraysInNodeDef(state){
  239. var objectIsTypedArray = function (candidate) {
  240. var typedArrayTypes = [
  241. Int8Array,
  242. Uint8Array,
  243. // Uint8ClampedArray,
  244. Int16Array,
  245. Uint16Array,
  246. Int32Array,
  247. Uint32Array,
  248. Float32Array,
  249. Float64Array
  250. ];
  251. var isTypedArray = false;
  252. if (typeof candidate == "object" && candidate != null) {
  253. typedArrayTypes.forEach(function (typedArrayType) {
  254. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  255. });
  256. }
  257. return isTypedArray;
  258. };
  259. var transitTransformation = function (object) {
  260. return objectIsTypedArray(object) ?
  261. Array.prototype.slice.call(object) : object;
  262. };
  263. let value = require("vwf/utility").transform(
  264. state, transitTransformation
  265. );
  266. return value
  267. }
  268. removeGrammarObj(obj) {
  269. Object.keys(obj).forEach(key =>
  270. (key === 'grammar' || key === 'semantics') && delete obj[key] ||
  271. (obj[key] && typeof obj[key] === 'object') && this.removeGrammarObj(obj[key])
  272. );
  273. return obj;
  274. };
  275. httpGet(url) {
  276. return new Promise(function (resolve, reject) {
  277. // do the usual Http request
  278. let request = new XMLHttpRequest();
  279. request.open('GET', url);
  280. request.onload = function () {
  281. if (request.status == 200) {
  282. resolve(request.response);
  283. } else {
  284. reject(Error(request.statusText));
  285. }
  286. };
  287. request.onerror = function () {
  288. reject(Error('Network Error'));
  289. };
  290. request.send();
  291. });
  292. }
  293. async httpGetJson(url) {
  294. // check if the URL looks like a JSON file and call httpGet.
  295. let regex = /\.(json)$/i;
  296. if (regex.test(url)) {
  297. // call the async function, wait for the result
  298. return await this.httpGet(url);
  299. } else {
  300. throw Error('Bad Url Format');
  301. }
  302. }
  303. }
  304. export { Helpers }