helpers.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. log(o) {
  16. if(typeof o === "object" && "_" in o) {
  17. const obj = {...o};
  18. delete obj._;
  19. return console.log(obj);
  20. }
  21. return console.log(o);
  22. }
  23. reduceSaveObject(path) {
  24. let obj = Object.assign({}, path);
  25. if (path.saveObject) {
  26. if (path.saveObject["queue"]) {
  27. if (path.saveObject["queue"]["time"]) {
  28. obj.saveObject = {
  29. "init": true,
  30. "queue": {
  31. "time": path.saveObject["queue"]["time"]
  32. }
  33. }
  34. }
  35. }
  36. }
  37. return obj
  38. }
  39. // IsInstanceID tests if the passed in potential Instance ID
  40. // is a valid instance id.
  41. IsInstanceID(potentialInstanceID) {
  42. if (potentialInstanceID.match(/^[0-9A-Za-z]{16}$/)) {
  43. return true;
  44. }
  45. return false;
  46. }
  47. // GenerateInstanceID function creates a randomly generated instance ID.
  48. GenerateInstanceID() {
  49. var text = "";
  50. for (var i = 0; i < 16; i++)
  51. text += this.ValidIDChars.charAt(Math.floor(Math.random() * this.ValidIDChars.length));
  52. return text;
  53. }
  54. // JoinPath
  55. // Takes multiple arguments, joins them together into one path.
  56. JoinPath( /* arguments */) {
  57. var result = "";
  58. if (arguments.length > 0) {
  59. if (arguments[0]) {
  60. result = arguments[0];
  61. }
  62. for (var index = 1; index < arguments.length; index++) {
  63. var newSegment = arguments[index];
  64. if (newSegment == undefined) {
  65. newSegment = "";
  66. }
  67. if ((newSegment[0] == "/") && (result[result.length - 1] == "/")) {
  68. result = result + newSegment.slice(1);
  69. } else if ((newSegment[0] == "/") || (result[result.length - 1] == "/")) {
  70. result = result + newSegment;
  71. } else {
  72. result = result + "/" + newSegment;
  73. }
  74. //result = libpath.join( result, newSegment );
  75. }
  76. }
  77. return result;
  78. }
  79. GetNamespace(processedURL) {
  80. if ((processedURL['instance']) && (processedURL['public_path'])) {
  81. return this.JoinPath(processedURL['public_path'], processedURL['application'], processedURL['instance']);
  82. }
  83. return undefined;
  84. }
  85. // GenerateSegments takes a string, breaks it into
  86. // '/' separated segments, and removes potential
  87. // blank first and last segments.
  88. GenerateSegments(argument) {
  89. var result = argument.split("/");
  90. if (result.length > 0) {
  91. if (result[0] == "") {
  92. result.shift();
  93. }
  94. }
  95. if (result.length > 0) {
  96. if (result[result.length - 1] == "") {
  97. result.pop();
  98. }
  99. }
  100. return result;
  101. }
  102. getInstanceID(obj) {
  103. // "/world/index.vwf/CcI3c1MnTsblg3H7"
  104. return obj.split('/')[3]
  105. }
  106. get appPath() {
  107. return JSON.parse(localStorage.getItem('lcs_app')).path.public_path.slice(1)
  108. }
  109. get worldStateName() {
  110. let appConfig = JSON.parse(localStorage.getItem('lcs_app'));
  111. var saveName = appConfig.path.public_path.slice(1);
  112. let privatePath = appConfig.path.private_path;
  113. if (privatePath) {
  114. if (privatePath.indexOf('load') !== -1) {
  115. saveName = privatePath.split('/')[1];
  116. }
  117. }
  118. return saveName
  119. }
  120. getRoot() {
  121. let data = JSON.parse(localStorage.getItem('lcs_app'));
  122. return {
  123. "root": data.path.public_path.slice(1),
  124. "inst": data.path.instance,
  125. "user": data.user
  126. }
  127. }
  128. get worldUser() {
  129. return this.getRoot(false).root.split('/')[0];
  130. }
  131. randId() {
  132. return '_' + Math.random().toString(36).substr(2, 9);
  133. }
  134. getRandomInt(min, max) {
  135. min = Math.ceil(min);
  136. max = Math.floor(max);
  137. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  138. }
  139. GUID() {
  140. var S4 = function () {
  141. return Math.floor(
  142. Math.random() * 0x10000 /* 65536 */
  143. ).toString(16);
  144. };
  145. return (
  146. S4() + S4() + "-" +
  147. S4() + "-" +
  148. S4() + "-" +
  149. S4() + "-" +
  150. S4() + S4() + S4()
  151. );
  152. }
  153. async sha256(message) {
  154. // encode as UTF-8
  155. const msgBuffer = new TextEncoder('utf-8').encode(message);
  156. // hash the message
  157. const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  158. // convert ArrayBuffer to Array
  159. const hashArray = Array.from(new Uint8Array(hashBuffer));
  160. // convert bytes to hex string
  161. const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
  162. return hashHex;
  163. }
  164. replaceSubStringALL(target, search, replacement) {
  165. return target.split(search).join(replacement);
  166. };
  167. convertFileSource(file, source) {
  168. //var source = (typeof(sourceToEdit) =="object") ? JSON.stringify(sourceToEdit): sourceToEdit;
  169. var convert;
  170. if (file.includes('_json') && (typeof source !== 'object')) {
  171. convert = (typeof JSON.parse(source) == 'object') ? JSON.stringify(JSON.parse(source), null, '\t') : source
  172. //source = source;//JSON.stringify(source, null, '\t');
  173. } else if (typeof source == 'object') {
  174. convert = JSON.stringify(source, null, '\t')
  175. } else if (typeof source == 'string') {
  176. convert = source
  177. }
  178. return convert
  179. }
  180. async getHtmlText(url) {
  181. let file = await fetch(url, { method: 'get' });
  182. let text = await file.text();
  183. return text
  184. }
  185. removePatches(obj) {
  186. let rm = L.lazy(rec =>
  187. L.ifElse(R.is(String),
  188. L.when(x => x == 'patches'), [L.keysEverywhere, rec], L.optional)
  189. ); //x == 'id' ||
  190. return L.remove(rm, obj)
  191. };
  192. replacePatchesWithIds(obj) {
  193. let rm = L.lazy(rec =>
  194. L.ifElse(R.is(String),
  195. L.when(x => x == 'patches'), [L.keysEverywhere, rec], L.optional)
  196. );
  197. return L.modify(rm, (k) => 'id', obj)
  198. };
  199. removeProps(obj) {
  200. let rm = L.lazy(rec =>
  201. L.ifElse(R.is(String),
  202. L.when(x => x == 'random' || x == 'sequence' || x === 'id' || x === 'patches' || x === 'childrenDeleted'), [L.keysEverywhere, rec], L.optional)
  203. );
  204. return L.remove(rm, obj)
  205. // Object.keys(obj).forEach(key =>
  206. // (key === 'id' || key === 'patches' || key === 'random' || key === 'sequence') && delete obj[key] ||
  207. // (obj[key] && typeof obj[key] === 'object') && this.removeProps(obj[key])
  208. // );
  209. //return obj;
  210. };
  211. removeGrammarObj(obj) {
  212. let rm = L.lazy(rec =>
  213. L.ifElse(R.is(String),
  214. L.when(x => x == 'grammar'
  215. || x == 'semantics'), [L.keysEverywhere, rec], L.optional)
  216. );
  217. return L.remove(rm, obj)
  218. // Object.keys(obj).forEach(key =>
  219. // (key === 'grammar' || key === 'semantics') && delete obj[key] ||
  220. // (obj[key] && typeof obj[key] === 'object') && this.removeGrammarObj(obj[key])
  221. // );
  222. // return obj;
  223. };
  224. collectMethods(obj) {
  225. let files = {};
  226. Object.keys(obj.children).forEach(childName => {
  227. let child = obj.children[childName];
  228. if (child.scritps && child.methods)
  229. files[childName] = "";
  230. let methods = child.methods;
  231. Object.keys(methods).forEach(el => {
  232. let method = methods[el];
  233. if (method.body) {
  234. let params = method.parameters ? method.parameters.toString() : '';
  235. let funDef = "this." + el + ' = function(' + params + ') { \n' + method.body + '\n' + '}';
  236. files[childName] = files[childName].concat('\n').concat(funDef);
  237. }
  238. })
  239. })
  240. return files
  241. }
  242. getNodeJSProps(nodeID) {
  243. let node = vwf.models.javascript.nodes[nodeID]
  244. return node
  245. }
  246. getWorldProto() {
  247. let worldID = vwf.application();
  248. let nodeDef = this.getNodeDef(worldID);
  249. const rm = L.lazy(rec =>
  250. L.ifElse(R.is(String), L.when(x => x.includes('avatar-') || x.includes('xcontroller-') || x.includes('gearvr-') || x.includes('mouse-')), [L.keys, rec], L.optional)
  251. )
  252. let fixedDef = L.remove(['children', L.props(rm)], nodeDef)
  253. return fixedDef
  254. }
  255. getNodeDef(nodeID) {
  256. let node = vwf.getNode(nodeID, true);
  257. let nodeDefPure = this.removeProps(node);
  258. let nodeDef = this.removeGrammarObj(nodeDefPure);
  259. let finalDef = this.replaceFloatArraysInNodeDef(nodeDef);
  260. return finalDef
  261. // if(param == 'withID'){
  262. // return this.replacePatchesWithIds(finalDef);
  263. // }
  264. // return this.removePatches(finalDef)
  265. }
  266. replaceFloatArraysInNodeDef(state) {
  267. var objectIsTypedArray = function (candidate) {
  268. var typedArrayTypes = [
  269. Int8Array,
  270. Uint8Array,
  271. // Uint8ClampedArray,
  272. Int16Array,
  273. Uint16Array,
  274. Int32Array,
  275. Uint32Array,
  276. Float32Array,
  277. Float64Array
  278. ];
  279. var isTypedArray = false;
  280. if (typeof candidate == "object" && candidate != null) {
  281. typedArrayTypes.forEach(function (typedArrayType) {
  282. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  283. });
  284. }
  285. return isTypedArray;
  286. };
  287. var transitTransformation = function (object) {
  288. if(object instanceof THREE.Vector2 || object instanceof THREE.Vector3 || object instanceof THREE.Vector4){
  289. return AFRAME.utils.coordinates.stringify(object)
  290. } else {
  291. return objectIsTypedArray(object) ?
  292. Array.prototype.slice.call(object) : object;
  293. }
  294. };
  295. let value = vwf.utility.transform(
  296. state, transitTransformation
  297. );
  298. return value
  299. }
  300. httpGet(url) {
  301. return new Promise(function (resolve, reject) {
  302. // do the usual Http request
  303. let request = new XMLHttpRequest();
  304. request.open('GET', url);
  305. request.onload = function () {
  306. if (request.status == 200) {
  307. resolve(request.response);
  308. } else {
  309. reject(Error(request.statusText));
  310. }
  311. };
  312. request.onerror = function () {
  313. reject(Error('Network Error'));
  314. };
  315. request.send();
  316. });
  317. }
  318. async httpGetJson(url) {
  319. // check if the URL looks like a JSON file and call httpGet.
  320. let regex = /\.(json)$/i;
  321. if (regex.test(url)) {
  322. // call the async function, wait for the result
  323. return await this.httpGet(url);
  324. } else {
  325. throw Error('Bad Url Format');
  326. }
  327. }
  328. authUser(alias, pass) {
  329. let self = this;
  330. _LCSDB.user().auth(alias, pass
  331. , function (ack) {
  332. if (ack.err) {
  333. self.notyErr(ack.err)
  334. }
  335. }
  336. );
  337. }
  338. testJSON(text) {
  339. if (typeof text !== "string") {
  340. return false;
  341. }
  342. try {
  343. JSON.parse(text);
  344. return true;
  345. }
  346. catch (error) {
  347. return false;
  348. }
  349. }
  350. async getUserPub(userName) {
  351. //TODO: Fix for using hashids instead users aliases with pubs sorted by time of registration
  352. let alias = '~@' + userName;
  353. let user = await (new Promise(res => _LCSDB.get(alias).once(res)));
  354. if (user) {
  355. if (Object.keys(user).length > 1) {
  356. let pubs = await Promise.all(Object.keys(user).filter(el => el !== '_').map(el => _LCSDB.user(el.slice(1)).then(res => {
  357. let ts = Gun.state.is(res, 'pub')
  358. return { pub: res.pub, time: ts }
  359. })))
  360. //console.log(pubs);
  361. pubs.sort(function (a, b) {
  362. return new Date(b.time) - new Date(a.time);
  363. });
  364. return pubs[0].pub
  365. } else {
  366. return Object.keys(user)[1].slice(1)
  367. }
  368. }
  369. }
  370. checkUserCollision() {
  371. //TODO: Fix for using hashids instead users aliases with pubs sorted by time of registration
  372. _app.helpers.getUserPub(_LCSDB.user().is.alias).then(res => {
  373. if (_LCSDB.user().is.pub !== res) {
  374. if (window.confirm("ERROR: User name collision. Try to delete user collision?")) {
  375. _LCSDB.user().delete();
  376. window.reload();
  377. }
  378. }
  379. })
  380. }
  381. async getUserAlias(userPub) {
  382. let user = await (new Promise(res => _LCSDB.user(userPub).get('alias').once(res)));
  383. if (user)
  384. return user
  385. }
  386. notyOK(msg) {
  387. let noty = new Noty({
  388. text: msg,
  389. timeout: 2000,
  390. theme: 'mint',
  391. layout: 'bottomRight',
  392. type: 'success'
  393. });
  394. noty.show();
  395. }
  396. notyErr(msg) {
  397. let noty = new Noty({
  398. text: msg,
  399. timeout: 2000,
  400. theme: 'mint',
  401. layout: 'bottomRight',
  402. type: 'error'
  403. });
  404. noty.show();
  405. }
  406. remap(inMin, inMax, outMin, outMax) {
  407. return function remaper(x) {
  408. return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
  409. }
  410. }
  411. get appPath (){
  412. return JSON.parse(localStorage.getItem('lcs_app')).path.public_path.slice(1)
  413. }
  414. get appName() {
  415. return JSON.parse(localStorage.getItem('lcs_app')).path.application.split(".").join("_")
  416. }
  417. // Changing this function significantly from the GLGE code
  418. // Will search hierarchy down until encountering a matching child
  419. // Will look into nodes that don't match.... this might not be desirable
  420. findChildByName(obj, childName, childType, recursive) {
  421. let self = this;
  422. var child = undefined;
  423. if (recursive) {
  424. // TODO: If the obj itself has the child name, the object will be returned by this function
  425. // I don't think this this desirable.
  426. if (self.nameTest.call(this, obj, childName)) {
  427. child = obj;
  428. } else if (obj.children && obj.children.length > 0) {
  429. for (var i = 0; i < obj.children.length && child === undefined; i++) {
  430. child = FindChildByName(obj.children[i], childName, childType, true);
  431. }
  432. }
  433. } else {
  434. if (obj.children) {
  435. for (var i = 0; i < obj.children.length && child === undefined; i++) {
  436. if (self.nameTest.call(this, obj.children[i], childName)) {
  437. child = obj.children[i];
  438. }
  439. }
  440. }
  441. }
  442. return child;
  443. }
  444. nameTest(obj, name) {
  445. if (obj.name == "") {
  446. return (obj.parent.name + "Child" == name);
  447. } else {
  448. return (obj.name == name || obj.id == name || obj.vwfID == name);
  449. }
  450. }
  451. }
  452. export { Helpers }