helpers.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. get appPath() {
  114. return JSON.parse(localStorage.getItem('lcs_app')).path.public_path.slice(1)
  115. }
  116. get worldStateName() {
  117. let appConfig = JSON.parse(localStorage.getItem('lcs_app'));
  118. var saveName = appConfig.path.public_path.slice(1);
  119. let privatePath = appConfig.path.private_path;
  120. if (privatePath) {
  121. if (privatePath.indexOf('load') !== -1) {
  122. saveName = privatePath.split('/')[1];
  123. }
  124. }
  125. return saveName
  126. }
  127. getRoot(noUser) {
  128. var app = window.location.pathname;
  129. var pathSplit = app.split('/');
  130. if (pathSplit[0] == "") {
  131. pathSplit.shift();
  132. }
  133. if (pathSplit[pathSplit.length - 1] == "") {
  134. pathSplit.pop();
  135. }
  136. var inst = undefined;
  137. var instIndex = pathSplit.length - 1;
  138. if (pathSplit.length > 2) {
  139. if (pathSplit[pathSplit.length - 2] == "load") {
  140. instIndex = pathSplit.length - 3;
  141. }
  142. }
  143. if (pathSplit.length > 3) {
  144. if (pathSplit[pathSplit.length - 3] == "load") {
  145. instIndex = pathSplit.length - 4;
  146. }
  147. }
  148. inst = pathSplit[instIndex];
  149. var root = "";
  150. for (var i = 0; i < instIndex; i++) {
  151. if (root != "") {
  152. root = root + "/";
  153. }
  154. root = root + pathSplit[i];
  155. }
  156. if (root.indexOf('.vwf') != -1) root = root.substring(0, root.lastIndexOf('/'));
  157. if (noUser) {
  158. return {
  159. "root": root.replace(pathSplit[0] + '/', ""),
  160. "inst": inst
  161. }
  162. } else {
  163. return {
  164. "root": root,
  165. "inst": inst
  166. }
  167. }
  168. }
  169. get worldUser() {
  170. return this.getRoot(false).root.split('/')[0];
  171. }
  172. randId() {
  173. return '_' + Math.random().toString(36).substr(2, 9);
  174. }
  175. getRandomInt(min, max) {
  176. min = Math.ceil(min);
  177. max = Math.floor(max);
  178. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  179. }
  180. GUID() {
  181. var S4 = function () {
  182. return Math.floor(
  183. Math.random() * 0x10000 /* 65536 */
  184. ).toString(16);
  185. };
  186. return (
  187. S4() + S4() + "-" +
  188. S4() + "-" +
  189. S4() + "-" +
  190. S4() + "-" +
  191. S4() + S4() + S4()
  192. );
  193. }
  194. async sha256(message) {
  195. // encode as UTF-8
  196. const msgBuffer = new TextEncoder('utf-8').encode(message);
  197. // hash the message
  198. const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  199. // convert ArrayBuffer to Array
  200. const hashArray = Array.from(new Uint8Array(hashBuffer));
  201. // convert bytes to hex string
  202. const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
  203. return hashHex;
  204. }
  205. replaceSubStringALL(target, search, replacement) {
  206. return target.split(search).join(replacement);
  207. };
  208. async getHtmlText(url) {
  209. let file = await fetch(url, { method: 'get' });
  210. let text = await file.text();
  211. return text
  212. }
  213. removeProps(obj) {
  214. Object.keys(obj).forEach(key =>
  215. (key === 'id' || key === 'patches' || key === 'random' || key === 'sequence') && delete obj[key] ||
  216. (obj[key] && typeof obj[key] === 'object') && this.removeProps(obj[key])
  217. );
  218. return obj;
  219. };
  220. getNodeDef(nodeID) {
  221. let node = vwf.getNode(nodeID, true);
  222. let nodeDefPure = this.removeProps(node);
  223. let nodeDef = this.removeGrammarObj(nodeDefPure);
  224. let finalDef = this.replaceFloatArraysInNodeDef(nodeDef);
  225. return finalDef
  226. }
  227. replaceFloatArraysInNodeDef(state){
  228. var objectIsTypedArray = function (candidate) {
  229. var typedArrayTypes = [
  230. Int8Array,
  231. Uint8Array,
  232. // Uint8ClampedArray,
  233. Int16Array,
  234. Uint16Array,
  235. Int32Array,
  236. Uint32Array,
  237. Float32Array,
  238. Float64Array
  239. ];
  240. var isTypedArray = false;
  241. if (typeof candidate == "object" && candidate != null) {
  242. typedArrayTypes.forEach(function (typedArrayType) {
  243. isTypedArray = isTypedArray || candidate instanceof typedArrayType;
  244. });
  245. }
  246. return isTypedArray;
  247. };
  248. var transitTransformation = function (object) {
  249. return objectIsTypedArray(object) ?
  250. Array.prototype.slice.call(object) : object;
  251. };
  252. let value = require("vwf/utility").transform(
  253. state, transitTransformation
  254. );
  255. return value
  256. }
  257. removeGrammarObj(obj) {
  258. Object.keys(obj).forEach(key =>
  259. (key === 'grammar' || key === 'semantics') && delete obj[key] ||
  260. (obj[key] && typeof obj[key] === 'object') && this.removeGrammarObj(obj[key])
  261. );
  262. return obj;
  263. };
  264. httpGet(url) {
  265. return new Promise(function (resolve, reject) {
  266. // do the usual Http request
  267. let request = new XMLHttpRequest();
  268. request.open('GET', url);
  269. request.onload = function () {
  270. if (request.status == 200) {
  271. resolve(request.response);
  272. } else {
  273. reject(Error(request.statusText));
  274. }
  275. };
  276. request.onerror = function () {
  277. reject(Error('Network Error'));
  278. };
  279. request.send();
  280. });
  281. }
  282. async httpGetJson(url) {
  283. // check if the URL looks like a JSON file and call httpGet.
  284. let regex = /\.(json)$/i;
  285. if (regex.test(url)) {
  286. // call the async function, wait for the result
  287. return await this.httpGet(url);
  288. } else {
  289. throw Error('Bad Url Format');
  290. }
  291. }
  292. authUser(alias, pass){
  293. _LCSDB.user().auth(alias, pass
  294. , function(ack) {
  295. if (ack.err) {
  296. new Noty({
  297. text: ack.err,
  298. timeout: 2000,
  299. theme: 'mint',
  300. layout: 'bottomRight',
  301. type: 'error'
  302. }).show();
  303. }
  304. }
  305. );
  306. }
  307. testJSON (text) {
  308. if (typeof text!=="string"){
  309. return false;
  310. }
  311. try{
  312. JSON.parse(text);
  313. return true;
  314. }
  315. catch (error){
  316. return false;
  317. }
  318. }
  319. async getUserPub(userName) {
  320. //TODO: Fix for using hashids instead users aliases with pubs sorted by time of registration
  321. let alias = '~@' + userName;
  322. let user = await (new Promise(res=>_LCSDB.get(alias).once(res)));
  323. if(user) {
  324. if(Object.keys(user).length > 1){
  325. let pubs = await Promise.all(Object.keys(user).filter(el=>el !== '_').map(el => _LCSDB.user(el.slice(1)).then(res=>{
  326. let ts = Gun.state.is(res, 'pub')
  327. return {pub: res.pub, time: ts}
  328. })))
  329. //console.log(pubs);
  330. pubs.sort(function(a,b){
  331. return new Date(b.time) - new Date(a.time);
  332. });
  333. return pubs[0].pub
  334. } else {
  335. return Object.keys(user)[1].slice(1)
  336. }
  337. }
  338. }
  339. checkUserCollision(){
  340. //TODO: Fix for using hashids instead users aliases with pubs sorted by time of registration
  341. _app.helpers.getUserPub(_LCSDB.user().is.alias).then(res=>{
  342. if(_LCSDB.user().is.pub !== res){
  343. if(window.confirm("ERROR: User name collision. Try to delete user collision?")) {
  344. _LCSDB.user().delete();
  345. window.reload();
  346. }
  347. }
  348. })
  349. }
  350. async getUserAlias(userPub) {
  351. let user = await (new Promise(res=>_LCSDB.user(userPub).get('alias').once(res)));
  352. if(user)
  353. return user
  354. }
  355. }
  356. export { Helpers }