import { Provider, ProviderConstructor } from '../providers/provider'; import { CloudStorageService } from '../storage/cloudstorageService'; import { Options } from './types'; import { detect } from 'detect-browser' import { version } from '../package.json' import * as axios from 'axios'; import * as events from 'events'; const device = detect(); export class RayconnectCore { public user: any; protected socket: any protected encode = true; protected authed: boolean = false; protected realTime: boolean = false; public localEvents = new events.EventEmitter(); protected CloudStorageservice: CloudStorageService; protected message_id = 0; public authToken = '' protected device = device; protected privateAuthToken: string = ""; public httpService: axios.AxiosStatic = axios.default public static readonly DefaultOps = { scopes: "", appID: "rayconnect", space: "", type: "client", url: "https://s1.iranserver1.rayconnect.ir" }; constructor(protected ops: Options = RayconnectCore.DefaultOps, private token: any, private config: any, private provider: ProviderConstructor ) { if (!this.ops.url) { this.ops.url = "https://s1.iranserver1.rayconnect.ir" } this.CloudStorageservice = new CloudStorageService(this.httpService); } protected openDB(): Promise { return new Promise((resolve, reject) => { let db: IDBDatabase; if (device?.type == "browser") { let request = indexedDB.open("rayconnectDB"); request.onerror = function (event) { reject("rayconnect need to use indexedDB"); }; request.onsuccess = function (event: any) { db = event.target.result; resolve(db); }; } else { reject("db is not supported in microservice version"); } }) } protected Connect(): any { let connectionString = this.ops.url as string; if (this.config) { connectionString = `${this.ops.url}?scopes=${this.ops.scopes}&appID=${this.ops.appID}&space=${this.ops.space}&type=${this.ops.type}&encode=${this.encode}&sdk_version=${version}`; if (this.ops.apps) { connectionString += `&apps=${this.ops.apps}` } if (this.token) { connectionString += `&token=${this.token}`; } } else { connectionString += `?token=${this.token}`; } this.authed = false; if (!Provider.CurrentConnection) new this.provider(connectionString); else if (Provider.connectionString.split('&appID=')[1].split('&')[0] != this.ops.appID) new this.provider(connectionString); Provider.CurrentConnection.on('disconnect', function () { Provider.CurrentConnection = undefined; }) return (this.socket = Provider.CurrentConnection); } protected Ack(data: any) { this.socket.emit('ackn', data); } protected ObjectIdvalue = function (id: { id: { toString: () => void } }) { return id.id.toString(); }; public OnConnect(callback: { (): void; (): void }) { this.socket.on("connect", () => { callback(); }); } public async Auth(token?: any) { this.privateAuthToken = token; const self = this; if (!token) { return; } if (!this.realTime) { const api = `https://s1.iranserver1.rayconnect.ir/api/v2/load?aid=${this.ops.appID}&token=${token}` const data = await this.httpService.get(api); this.socket.emit("auth", { token, }); this.authToken = token await this.CloudStorageservice.LoadCloudStorage(this.realTime, data.data.cloudstorage) this.user = data.data.user return Promise.resolve(data.data.user) } this.socket.emit("auth", { token, }); // this.loadGlobalCookie(token); return new Promise((resolve, reject) => { this.socket.once("retry_auth", (err: any) => { reject(err); }); const timeout = setTimeout(() => { reject("request timeout."); }, 5000); const retryAuth = function (data: any) { clearTimeout(timeout); reject({ type: "blocked", data: data, }); }; this.socket.once("retry_auth", retryAuth); this.socket.once("authed", (msg: any) => { this.authToken = token // load cloud storage when authed this.CloudStorageservice.LoadCloudStorage(this.realTime) .then((data) => { resolve(msg.data); }) .catch((ER) => { resolve(msg.data); }); clearTimeout(timeout); }); }); } async loadGlobalCookie(token: string) { setTimeout(() => { if (device?.type == "browser") { let Sessionframe = document.createElement('iframe'); Sessionframe.style.display = 'none'; Sessionframe.onload = function () { Sessionframe.parentNode?.removeChild(Sessionframe); }; Sessionframe.src = `https://http-gateway.ir/api/v1/store/save-session?token=${token}&aid=${this.ops.appID}`; document.body.appendChild(Sessionframe); } }, 100); } protected async getAccess(inputToken?: string) { try { // token key const token_key = `rayconnect-client-${this.ops.appID}-token`; // check platform is browser // check if token exist await Provider.Platform("browser"); let token = localStorage.getItem(token_key); if (!token && inputToken) { localStorage.setItem(token_key, inputToken); token = inputToken; } return this.Auth(token); } catch (error) { return this.Auth(inputToken); } } }