helpers.js 15 KB

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