UNPKG

@pubby.club/sdk

Version:
235 lines (234 loc) 11.2 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread) || function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WsStream = void 0; var socket_io_client_1 = __importDefault(require("socket.io-client")); var time_sync_event_1 = require("./outgoing/time-sync.event"); var all_events_1 = require("./incoming/all-events"); var polyfills_1 = require("../lib/polyfills"); var streams_1 = require("../lib/streams"); var operators_1 = require("../lib/streams/operators"); var TIME_SYNC_INTERVAL = 60 * 5000; var WsStream = /** @class */ (function (_super) { __extends(WsStream, _super); function WsStream(url, pubby) { var _this = _super.call(this) || this; _this.url = url; _this.pubby = pubby; _this._timeOffset = 0; /** Informa se o cliente foi desconectado, propositalmente, de maneira forçada */ _this.forciblyDisconnected = false; return _this; } WsStream.prototype.reconnect = function () { return __awaiter(this, void 0, void 0, function () { var wait; return __generator(this, function (_a) { switch (_a.label) { case 0: wait = function (time) { return new Promise(function (resolve) { return setTimeout(resolve, time); }); }; _a.label = 1; case 1: if (!(!this.io.connected && !this.forciblyDisconnected)) return [3 /*break*/, 4]; console.log("Reconectando..."); return [4 /*yield*/, this.connect(true).catch(function (e) { return console.error(e); })]; case 2: _a.sent(); console.log("esperar 1s"); return [4 /*yield*/, wait(1000)]; case 3: _a.sent(); return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); }; WsStream.prototype.connect = function (reconnect) { var _this = this; if (reconnect === void 0) { reconnect = false; } // eslint-disable-next-line no-async-promise-executor return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var ticket, onevent, stream; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.io) { if (this.io.connected) { return [2 /*return*/, resolve()]; } this.io.removeAllListeners(); } return [4 /*yield*/, this.pubby.auth.getTicket()]; case 1: ticket = _a.sent(); this.io = socket_io_client_1.default(this.url, { reconnection: false, query: { reconnect: String(reconnect), ticket: ticket.accessToken, }, }); // Handle connection events this.io.once("connect", function () { // Envia o pacote de sincronização _this.syncTime().then(resolve); // Inicia a sincronização de tempo clearInterval(_this.syncTimer); _this.syncTimer = setInterval(function () { return _this.syncTime(); }, TIME_SYNC_INTERVAL); }); this.io.once("error", reject); this.io.once("connect_error", function (err) { console.log("Failed to connect"); reject(err); }); this.io.once("disconnect", function () { console.log("Desconectado!"); _this.reconnect(); }); this.io.once("force_disconnect", function (reason) { console.log("Desconectado de maneira forçada!", reason); _this.forciblyDisconnected = true; }); this.io.on("exception", function (err) { return _this.error(err); }); onevent = this.io.onevent; stream = this; this.io.onevent = function (packet) { if (packet.type === 2) { var _a = __read(packet.data, 2), event = _a[0], data = _a[1]; var MessageConstructor = all_events_1.ALL_EVENTS.get(event); if (MessageConstructor) { var args = [].concat(data); var message = new (MessageConstructor.bind.apply(MessageConstructor, __spread([void 0], args)))(); streams_1.PubbyStream.prototype.add.call(stream, message); } } return onevent.call(this, packet); }; return [2 /*return*/]; } }); }); }); }; WsStream.prototype.add = function (data, cb) { if (data !== null) { this._write(data, cb); } return this; }; WsStream.prototype.asyncAdd = function (data) { var _this = this; return new Promise(function (resolve, reject) { _this.add(data, function (err, data) { return (err ? reject(err) : resolve(data)); }); }); }; WsStream.prototype.listen = function (type) { return this.pipe(operators_1.filter(function (d) { return d instanceof type; })); }; WsStream.prototype._write = function (message, cb) { var _a; (_a = this.io).emit.apply(_a, __spread([message.constructor.id], message.toMessage(), [cb])); }; Object.defineProperty(WsStream.prototype, "timeOffset", { get: function () { return this._timeOffset; }, enumerable: false, configurable: true }); Object.defineProperty(WsStream.prototype, "now", { get: function () { return Date.now() - this.timeOffset; }, enumerable: false, configurable: true }); WsStream.prototype.syncTime = function () { var _this = this; return new Promise(function (resolve) { var start = polyfills_1.performance.now(); _this.add(new time_sync_event_1.TimeSyncRequest(Date.now()), function (_, _a) { var _b = __read(_a, 1), timeOffset = _b[0]; var delay = (polyfills_1.performance.now() - start) / 2; _this._timeOffset = timeOffset - delay; resolve(); }); }); }; return WsStream; }(streams_1.PubbyStream)); exports.WsStream = WsStream;