helpers.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. reduceSaveObject(path) {
  16. let obj = Object.assign({}, path);
  17. if(path.saveObject){
  18. if ( path.saveObject[ "queue" ] ) {
  19. if ( path.saveObject[ "queue" ][ "time" ] ) {
  20. obj.saveObject = {
  21. "init": true,
  22. "queue":{
  23. "time": path.saveObject[ "queue" ][ "time" ]
  24. }
  25. }
  26. }
  27. }
  28. }
  29. return obj
  30. }
  31. async Process(updatedURL) {
  32. var result =
  33. { 'public_path': "/", 'application': undefined, 'instance': undefined, 'private_path': undefined };
  34. var segments = this.GenerateSegments(updatedURL);
  35. var extension = undefined;
  36. while ((segments.length > 0) && (await this.IsExist(this.JoinPath(result['public_path'], segments[0])))) {
  37. result['public_path'] = this.JoinPath(result['public_path'], segments.shift());
  38. }
  39. if ((segments.length > 0) && (extension = await this.GetExtension(this.JoinPath(result['public_path'], segments[0])))) {
  40. result['application'] = segments.shift();
  41. } else if (extension = await this.GetExtension(this.JoinPath(result['public_path'], "index.vwf"))) {
  42. result['application'] = "index.vwf";
  43. }
  44. if (extension) {
  45. if ((segments.length > 0) && (this.IsInstanceID(segments[0]))) {
  46. result['instance'] = segments.shift();
  47. }
  48. if (segments.length > 0) {
  49. result['private_path'] = segments.join("/");
  50. }
  51. }
  52. return result;
  53. }
  54. // IsInstanceID tests if the passed in potential Instance ID
  55. // is a valid instance id.
  56. IsInstanceID(potentialInstanceID) {
  57. if (potentialInstanceID.match(/^[0-9A-Za-z]{16}$/)) {
  58. return true;
  59. }
  60. return false;
  61. }
  62. // GenerateInstanceID function creates a randomly generated instance ID.
  63. GenerateInstanceID() {
  64. var text = "";
  65. for (var i = 0; i < 16; i++)
  66. text += this.ValidIDChars.charAt(Math.floor(Math.random() * this.ValidIDChars.length));
  67. return text;
  68. }
  69. // JoinPath
  70. // Takes multiple arguments, joins them together into one path.
  71. JoinPath( /* arguments */) {
  72. var result = "";
  73. if (arguments.length > 0) {
  74. if (arguments[0]) {
  75. result = arguments[0];
  76. }
  77. for (var index = 1; index < arguments.length; index++) {
  78. var newSegment = arguments[index];
  79. if (newSegment == undefined) {
  80. newSegment = "";
  81. }
  82. if ((newSegment[0] == "/") && (result[result.length - 1] == "/")) {
  83. result = result + newSegment.slice(1);
  84. } else if ((newSegment[0] == "/") || (result[result.length - 1] == "/")) {
  85. result = result + newSegment;
  86. } else {
  87. result = result + "/" + newSegment;
  88. }
  89. //result = libpath.join( result, newSegment );
  90. }
  91. }
  92. return result;
  93. }
  94. GetNamespace( processedURL ) {
  95. if ( ( processedURL[ 'instance' ] ) && ( processedURL[ 'public_path' ] ) ) {
  96. return this.JoinPath( processedURL[ 'public_path' ], processedURL[ 'application' ], processedURL[ 'instance' ] );
  97. }
  98. return undefined;
  99. }
  100. async IsFileExist(path) {
  101. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  102. var seperatorFixedPath = path.slice(1);//path.replace(/\//g, '/');
  103. let worldName = seperatorFixedPath.split('/')[0];
  104. let fileName = seperatorFixedPath.replace(worldName + '/', "");
  105. let world = await userDB.get('worlds').get(worldName).promOnce();
  106. if (world) {
  107. let doc = Object.keys(world.data).includes(fileName);//(await userDB.get('worlds').get(worldName).get(fileName).promOnce()).data;
  108. if (doc) {
  109. return true
  110. }
  111. }
  112. return false
  113. }
  114. async IsExist(path) {
  115. let userDB = _LCSDB.user(_LCS_WORLD_USER.pub);
  116. var seperatorFixedPath = (path.slice(1)).split('/');//path.replace(/\//g, '/');
  117. if(seperatorFixedPath.length == 1){
  118. let doc = (await userDB.get('worlds').get(seperatorFixedPath[0]).promOnce()).data; //(await userDB.get('worlds').promOnce()).data;
  119. // let doc = Object.keys(worlds).includes('index_vwf_yaml');//(await userDB.get('worlds').get(seperatorFixedPath).promOnce()).data;
  120. if (doc) {
  121. return true
  122. }
  123. }
  124. return false
  125. }
  126. // GenerateSegments takes a string, breaks it into
  127. // '/' separated segments, and removes potential
  128. // blank first and last segments.
  129. GenerateSegments(argument) {
  130. var result = argument.split("/");
  131. if (result.length > 0) {
  132. if (result[0] == "") {
  133. result.shift();
  134. }
  135. }
  136. if (result.length > 0) {
  137. if (result[result.length - 1] == "") {
  138. result.pop();
  139. }
  140. }
  141. return result;
  142. }
  143. async GetExtension(path) {
  144. if (path.match(/\.vwf$/)) {
  145. // ["", ".yaml", ".json"]
  146. let check1 = await this.IsFileExist(this.JoinPath(path + "").split(".").join("_"));
  147. if(check1)
  148. return ""
  149. let check2 = await this.IsFileExist(this.JoinPath(path + ".yaml").split(".").join("_"));
  150. if(check2)
  151. return ".yaml"
  152. let check3 = await this.IsFileExist(this.JoinPath(path + ".json").split(".").join("_"));
  153. if(check3)
  154. return ".json"
  155. // for (const res of this.template_extensions) {
  156. // let check = await this.IsFileExist(this.JoinPath(path + res).split(".").join("_"));
  157. // if (check) return res
  158. // }
  159. }
  160. return undefined;
  161. }
  162. get appPath() {
  163. return JSON.parse(localStorage.getItem('lcs_app')).path.public_path.slice(1)
  164. }
  165. get worldStateName() {
  166. let appConfig = JSON.parse(localStorage.getItem('lcs_app'));
  167. var saveName = appConfig.path.public_path.slice(1);
  168. let privatePath = appConfig.path.private_path;
  169. if (privatePath) {
  170. if (privatePath.indexOf('load') !== -1) {
  171. saveName = privatePath.split('/')[1];
  172. }
  173. }
  174. return saveName
  175. }
  176. getRoot(noUser) {
  177. var app = window.location.pathname;
  178. var pathSplit = app.split('/');
  179. if (pathSplit[0] == "") {
  180. pathSplit.shift();
  181. }
  182. if (pathSplit[pathSplit.length - 1] == "") {
  183. pathSplit.pop();
  184. }
  185. var inst = undefined;
  186. var instIndex = pathSplit.length - 1;
  187. if (pathSplit.length > 2) {
  188. if (pathSplit[pathSplit.length - 2] == "load") {
  189. instIndex = pathSplit.length - 3;
  190. }
  191. }
  192. if (pathSplit.length > 3) {
  193. if (pathSplit[pathSplit.length - 3] == "load") {
  194. instIndex = pathSplit.length - 4;
  195. }
  196. }
  197. inst = pathSplit[instIndex];
  198. var root = "";
  199. for (var i = 0; i < instIndex; i++) {
  200. if (root != "") {
  201. root = root + "/";
  202. }
  203. root = root + pathSplit[i];
  204. }
  205. if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  206. if (noUser) {
  207. return {
  208. "root": root.replace(pathSplit[0] + '/', ""),
  209. "inst": inst
  210. }
  211. } else {
  212. return {
  213. "root": root,
  214. "inst": inst
  215. }
  216. }
  217. }
  218. get worldUser() {
  219. return this.getRoot(false).root.split('/')[0];
  220. }
  221. randId() {
  222. return '_' + Math.random().toString(36).substr(2, 9);
  223. }
  224. getRandomInt(min, max) {
  225. min = Math.ceil(min);
  226. max = Math.floor(max);
  227. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  228. }
  229. GUID() {
  230. var S4 = function () {
  231. return Math.floor(
  232. Math.random() * 0x10000 /* 65536 */
  233. ).toString(16);
  234. };
  235. return (
  236. S4() + S4() + "-" +
  237. S4() + "-" +
  238. S4() + "-" +
  239. S4() + "-" +
  240. S4() + S4() + S4()
  241. );
  242. }
  243. async sha256(message) {
  244. // encode as UTF-8
  245. const msgBuffer = new TextEncoder('utf-8').encode(message);
  246. // hash the message
  247. const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  248. // convert ArrayBuffer to Array
  249. const hashArray = Array.from(new Uint8Array(hashBuffer));
  250. // convert bytes to hex string
  251. const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
  252. return hashHex;
  253. }
  254. replaceSubStringALL(target, search, replacement) {
  255. return target.split(search).join(replacement);
  256. };
  257. async getHtmlText(url) {
  258. let file = await fetch(url, { method: 'get' });
  259. let text = await file.text();
  260. return text
  261. }
  262. removeProps(obj) {
  263. Object.keys(obj).forEach(key =>
  264. (key === 'id' || key === 'patches' || key === 'random' || key === 'sequence') && delete obj[key] ||
  265. (obj[key] && typeof obj[key] === 'object') && this.removeProps(obj[key])
  266. );
  267. return obj;
  268. };
  269. getNodeDef(nodeID) {
  270. let node = vwf.getNode(nodeID, true);
  271. let nodeDefPure = this.removeProps(node);
  272. let nodeDef = this.removeGrammarObj(nodeDefPure);
  273. let finalDef = this.replaceFloatArraysInNodeDef(nodeDef);
  274. return finalDef
  275. }
  276. replaceFloatArraysInNodeDef(state){
  277. var objectIsTypedArray = function (candidate) {
  278. var typedArrayTypes = [
  279. Int8Array,
  280. Uint8Array,
  281. // Uint8ClampedArray,
  282. Int16Array,
  283. Uint16Array,
  284. Int32Array,
  285. Uint32Array,
  286. Float32Array,
  287. Float64Array
  288. ];
  289. var isTypedArray = false;
  290. if (typeof candidate == "object" && candidate != null) {
  291. typedArrayTypes.forEach(function (typedArrayType) {
  292. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  293. });
  294. }
  295. return isTypedArray;
  296. };
  297. var transitTransformation = function (object) {
  298. return objectIsTypedArray(object) ?
  299. Array.prototype.slice.call(object) : object;
  300. };
  301. let value = require("vwf/utility").transform(
  302. state, transitTransformation
  303. );
  304. return value
  305. }
  306. removeGrammarObj(obj) {
  307. Object.keys(obj).forEach(key =>
  308. (key === 'grammar' || key === 'semantics') && delete obj[key] ||
  309. (obj[key] && typeof obj[key] === 'object') && this.removeGrammarObj(obj[key])
  310. );
  311. return obj;
  312. };
  313. httpGet(url) {
  314. return new Promise(function (resolve, reject) {
  315. // do the usual Http request
  316. let request = new XMLHttpRequest();
  317. request.open('GET', url);
  318. request.onload = function () {
  319. if (request.status == 200) {
  320. resolve(request.response);
  321. } else {
  322. reject(Error(request.statusText));
  323. }
  324. };
  325. request.onerror = function () {
  326. reject(Error('Network Error'));
  327. };
  328. request.send();
  329. });
  330. }
  331. async httpGetJson(url) {
  332. // check if the URL looks like a JSON file and call httpGet.
  333. let regex = /\.(json)$/i;
  334. if (regex.test(url)) {
  335. // call the async function, wait for the result
  336. return await this.httpGet(url);
  337. } else {
  338. throw Error('Bad Url Format');
  339. }
  340. }
  341. }
  342. export { Helpers }