DHWs.js 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DHWs = factory());
  5. }(this, (function () { 'use strict';
  6. /**
  7. * @description 处理客户端登陆、登出、保活。版本相关逻辑
  8. * @author 178730 <jin_cong2@dahuatech.com>
  9. * @date 2021-04-27
  10. */
  11. var account = {
  12. /**
  13. * @description 登录客户端
  14. */
  15. loginClient() {
  16. this.loginEnd = false;
  17. this.loginStartTime = Date.now();
  18. const config = this.config;
  19. let { appName, appId, browser: { name, version, platform } } = config;
  20. // 登陆确保有appName
  21. if (!appName) {
  22. this.loginEnd = true;
  23. return false;
  24. }
  25. const params = {
  26. appName,
  27. params: {
  28. browser: name,
  29. version,
  30. platform
  31. },
  32. appId
  33. };
  34. this.postMessage('register', params);
  35. },
  36. /**
  37. * @description 注销客户端
  38. */
  39. logoutClient() {
  40. console.log("注销客户端");
  41. const config = this.config;
  42. const { appName, appId } = config;
  43. this.postMessage('unregister', {
  44. appName,
  45. appId
  46. });
  47. this.config.appName = '';
  48. },
  49. };
  50. /**
  51. * @description 处理浏览器位置和DOM对象方法
  52. * @author 178730 <jin_cong2@dahuatech.com>
  53. * @date 2021-04-27
  54. */
  55. /**
  56. * @description 检测浏览器缩放比例
  57. */
  58. function detectZoom() {
  59. var ratio = 0, screen = window.screen, ua = navigator.userAgent.toLowerCase();
  60. if (window.devicePixelRatio !== undefined) {
  61. ratio = window.devicePixelRatio;
  62. }
  63. else if (~ua.indexOf('msie')) {
  64. if (screen['deviceXDPI'] && screen['logicalXDPI']) {
  65. ratio = screen['deviceXDPI'] / screen['logicalXDPI'];
  66. }
  67. }
  68. else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
  69. ratio = window.outerWidth / window.innerWidth;
  70. }
  71. if (ratio) {
  72. ratio = Math.round(ratio * 100);
  73. }
  74. return ratio;
  75. }
  76. /**
  77. * @description 检测浏览器是否有Y轴滚动条
  78. */
  79. function hasScrollbarY() {
  80. return (getDocument().body.scrollHeight >
  81. (window.innerHeight || getDocument().documentElement.clientHeight));
  82. }
  83. /**
  84. * @description 检测浏览器是否有X轴滚动条
  85. */
  86. function hasScrollbarX() {
  87. return (getDocument().body.scrollWidth >
  88. (window.innerWidth || getDocument().documentElement.clientWidth));
  89. }
  90. /**
  91. * @description 获取浏览器滚动条宽度
  92. */
  93. function getScrollbarWidth() {
  94. var scrollDiv = getDocument().createElement('div');
  95. scrollDiv.style.cssText =
  96. 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
  97. getDocument().body.appendChild(scrollDiv);
  98. var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
  99. getDocument().body.removeChild(scrollDiv);
  100. return scrollbarWidth;
  101. }
  102. /**
  103. * @description 获取当前浏览器缩放和滚动条信息
  104. */
  105. function getScrollInfo() {
  106. let ratio = detectZoom();
  107. let scrollX = window.pageXOffset;
  108. let scrollY = window.pageYOffset;
  109. var hasscrollbary = hasScrollbarY();
  110. var hasscrollbarx = hasScrollbarX();
  111. var scrollbarWidth = getScrollbarWidth();
  112. let scrollXH = hasscrollbarx ? scrollbarWidth : 0;
  113. let scrollYW = hasscrollbary ? scrollbarWidth : 0;
  114. return { ratio, scrollX, scrollY, scrollXH, scrollYW };
  115. }
  116. /**
  117. * @description 根据domId检测Dom是否有宽和高的属性
  118. * @param {Obeject} domId 元素ID
  119. */
  120. function checkDomExit(domId, log = true) {
  121. let defaultDomInfo = {
  122. x: 0,
  123. y: 0,
  124. width: 0,
  125. height: 0
  126. };
  127. const domTarget = getDocument().getElementById(domId);
  128. if (!domTarget) {
  129. log && console.log(`ws-can not find dom by id ${domId}`);
  130. return defaultDomInfo;
  131. }
  132. const domInfo = (domTarget.getClientRects() && domTarget.getClientRects()[0]);
  133. if (!domInfo) { // 若找不到DOM元素,报错
  134. log && console.warn(`ws-can not find domInfo by id ${domId}, please check dom exited`);
  135. return defaultDomInfo;
  136. }
  137. return domInfo;
  138. }
  139. /**
  140. * @description 判断当前是否在iframe之中
  141. */
  142. function isIframe() {
  143. return self.frameElement && self.frameElement.tagName == "IFRAME";
  144. }
  145. /**
  146. * @description 获取当前的document对象,兼容iframe处理
  147. * 存在iframe,实例在top,目标窗口在子层,需要级联
  148. */
  149. function getDocument() {
  150. let _document = window.document;
  151. // 判断是否在iframe里面
  152. if (isIframe()) {
  153. // 存在navigator
  154. if (top['$nav']) {
  155. // 通过navigator获取dom
  156. const iframe = top['$nav'].getIframeByPath();
  157. if (iframe) {
  158. _document = iframe.contentWindow.document;
  159. }
  160. else {
  161. throw new Error('can not find document in iframe by @psi/navigator');
  162. }
  163. }
  164. else {
  165. // iframe嵌入,且没有@psi/navigator
  166. throw new Error('not support in iframe that without @psi/navigator');
  167. }
  168. }
  169. return _document;
  170. }
  171. /**
  172. * @description 通过元素ID获取DOM对象
  173. * @param {Obeject} domId 元素ID
  174. */
  175. function getDomById(domId) {
  176. console.log('ws-getDomById', domId);
  177. const domInfo = checkDomExit(domId);
  178. const width = domInfo.width;
  179. const height = domInfo.height;
  180. let x = domInfo.x;
  181. let y = domInfo.y;
  182. if (isIframe()) {
  183. console.log('dom in iframe');
  184. if (top['$nav']) {
  185. // 通过navigator获取dom
  186. const iframe = top['$nav'].getIframeByPath();
  187. if (iframe) {
  188. let iframeRect = iframe.getClientRects();
  189. if (iframeRect && iframeRect[0]) {
  190. x += iframeRect[0].x;
  191. y += iframeRect[0].y;
  192. }
  193. throw new Error('can not find document in iframe by @psi/navigator');
  194. }
  195. throw new Error('can not find document in iframe by @psi/navigator');
  196. }
  197. else {
  198. // iframe嵌入,且没有@psi/navigator
  199. throw new Error('not support in iframe that without @psi/navigator');
  200. }
  201. }
  202. return {
  203. width,
  204. height,
  205. x,
  206. y
  207. };
  208. }
  209. var control = {
  210. /**
  211. * @description 提交浏览器信息
  212. */
  213. browserInfo() {
  214. const config = this.config;
  215. const { loginIp, userCode } = config;
  216. const { browser: { name, version, platform } } = config;
  217. this.postMessage('browserInfo', {
  218. loginIp,
  219. userCode,
  220. params: {
  221. browser: name,
  222. version,
  223. platform
  224. }
  225. });
  226. },
  227. /**
  228. * @description 浏览器切换显隐
  229. */
  230. webVisibilityChange() {
  231. const config = this.config;
  232. //const { loginIp, userCode } = config;
  233. const { appName, appId } = config;
  234. this.postMessage('webVisibilityChange', {
  235. appName,
  236. appId,
  237. params: {
  238. hidden: getDocument().hidden
  239. }
  240. });
  241. },
  242. /**
  243. * @description 受信任站点
  244. */
  245. trusteSite(http) {
  246. console.log('ws-trusteSite-http', http);
  247. const config = this.config;
  248. const { loginIp, userCode } = config;
  249. this.postMessage('trusteSite', {
  250. loginIp,
  251. userCode,
  252. params: {
  253. trusteSite: http
  254. }
  255. });
  256. },
  257. /**
  258. * @description 设置下载路径
  259. * @params {String} path 下载路径地址
  260. */
  261. setDownloadPath(path) {
  262. const config = this.config;
  263. const { loginIp, userCode } = config;
  264. return this.postMessage('setDownloadPath', {
  265. loginIp,
  266. userCode,
  267. params: {
  268. downloadPath: path
  269. }
  270. });
  271. },
  272. /**
  273. * @description 下载视频
  274. * @params {Array} downloads 下载录像参数
  275. * {
  276. channelName: '11111',
  277. channelId: '1DSNHDHF654DS',
  278. beginTime: 1602559308127,
  279. endTime: 1602559308227,
  280. format: 1,
  281. sourceType: 1,
  282. streamType: 1
  283. }
  284. * @params {Boolean} visible 是否显示下载窗口
  285. */
  286. downloadVideo(downloads, visible) {
  287. const config = this.config;
  288. const { loginIp, userCode } = config;
  289. return this.postMessage('downloadVideo', {
  290. loginIp,
  291. userCode,
  292. params: {
  293. array: downloads,
  294. visible: visible
  295. }
  296. });
  297. },
  298. /**
  299. * @description 创建控件
  300. *
  301. * @param {Array} documents
  302. * {
  303. * array: [{
  304. * ctrlCode: '11',
  305. * ctrlType: 'playerCtrl'
  306. * }]
  307. * }
  308. */
  309. createCtrl(widgets) {
  310. console.log('ws-createCtrl', widgets);
  311. const _this = this;
  312. const config = this.config;
  313. // const { loginIp, userCode } = config;
  314. const { appName, appId } = config;
  315. let widgetParams = [];
  316. if (widgets.length === 0) {
  317. console.error('param widget must has a ctrlCode.');
  318. return false;
  319. }
  320. widgets.forEach(item => {
  321. if (_this.ids.includes(item.ctrlCode)) {
  322. _this.destroyCtrl([item.ctrlCode]);
  323. }
  324. let widgetParam = {};
  325. const { ctrlType, ctrlCode, ctrlProperty, visible, cutList, domId } = item;
  326. getDocument().getElementById(domId);
  327. // if(!domTarget) {
  328. // console.warn(`can not find dom by id ${domId}`);
  329. // // throw new Error(`can not find dom by id ${domId}`);
  330. // }
  331. let domInfo = getDomById(domId);
  332. let scrollInfo = getScrollInfo();
  333. // 停止观测
  334. // observer.disconnect();
  335. widgetParam['ctrlType'] = ctrlType;
  336. widgetParam['visible'] = visible;
  337. widgetParam['ctrlCode'] = ctrlCode;
  338. widgetParam['ctrlProperty'] = ctrlProperty;
  339. //widgetParam['cutList'] = cutList;
  340. widgetParam['posX'] = domInfo.x;
  341. widgetParam['posY'] = domInfo.y;
  342. widgetParam['width'] = domInfo.width;
  343. widgetParam['height'] = domInfo.height;
  344. widgetParam['ratio'] = scrollInfo.ratio;
  345. widgetParam['scrollX'] = scrollInfo.scrollX;
  346. widgetParam['scrollY'] = scrollInfo.scrollY;
  347. widgetParam['scrollXH'] = scrollInfo.scrollXH;
  348. widgetParam['scrollYW'] = scrollInfo.scrollYW;
  349. // widgetParam['observer'] = observer;
  350. widgetParam['domId'] = domId;
  351. // widgetParam['domTarget'] = domTarget;
  352. widgetParams.push(widgetParam);
  353. _this.ctrls.push(widgetParam);
  354. _this.ids.push(ctrlCode);
  355. });
  356. return this.postMessage('createCtrl', {
  357. // todo 回退uuidmap/ctrls处理
  358. // loginIp,
  359. // userCode,
  360. appName,
  361. appId,
  362. params: {
  363. array: widgetParams
  364. }
  365. });
  366. },
  367. /**
  368. * @description 设置可见
  369. *
  370. * @param {Array} ctrls
  371. * {
  372. * array: [{
  373. * ctrlCode: "bf662065-3bda-4cb7-8fdd-b6e13997d84f"
  374. * visible: true
  375. * }]
  376. * }
  377. */
  378. setCtrlVisible(ctrls) {
  379. const _this = this;
  380. const config = this.config;
  381. //const { loginIp, userCode } = config;
  382. const { appName, appId } = config;
  383. let ctrlParams = [];
  384. if (ctrls.length === 0) {
  385. return false;
  386. }
  387. ctrls.forEach(item => {
  388. const ctrlParam = {};
  389. if (!_this.ids.includes(item.ctrlCode)) {
  390. return false;
  391. }
  392. const ctrl = _this.ctrls.find((ctrl) => {
  393. return ctrl.ctrlCode === item.ctrlCode;
  394. });
  395. ctrl['visible'] = item.visible;
  396. ctrlParam['ctrlCode'] = item.ctrlCode;
  397. ctrlParam['visible'] = item.visible;
  398. ctrlParams.push(ctrlParam);
  399. });
  400. return this.postMessage('setCtrlVisible', {
  401. appName,
  402. appId,
  403. params: {
  404. array: ctrlParams
  405. }
  406. });
  407. },
  408. /**
  409. * @description 设置控件属性--位置,剪裁
  410. *
  411. * @param {Array} positions
  412. * {
  413. * array: [{
  414. * id: 1,
  415. * posX: 100,
  416. * posY: 200
  417. * }]
  418. * }
  419. */
  420. setCtrlPos(positions) {
  421. const _this = this;
  422. const config = this.config;
  423. //const { loginIp, userCode } = config;
  424. const { appName, appId } = config;
  425. let widgetParams = [];
  426. if (positions.length === 0) {
  427. throw new Error('setCtrlPos must has a Id.');
  428. }
  429. positions.forEach(item => {
  430. if (!_this.ids.includes(item.ctrlCode)) {
  431. throw new Error(`widget by id:${item.ctrlCode} has not been created.`);
  432. }
  433. const ctrl = _this.ctrls.find((ctrl) => {
  434. return ctrl.ctrlCode === item.ctrlCode;
  435. });
  436. if (!ctrl) {
  437. throw new Error(`can not find ctrl by id:${item.ctrlCode}.`);
  438. }
  439. // 待设置属性列表
  440. let propList = ['posX', 'posY', 'width', 'height', 'ratio', 'scrollX', 'scrollY', 'scrollXH', 'scrollYW', 'cutList'];
  441. // 设置控件属性
  442. function setProp(ctrl, item, prop) {
  443. item.hasOwnProperty(prop) ? ctrl[prop] = item[prop] : '';
  444. }
  445. propList.forEach(e => {
  446. setProp(ctrl, item, e);
  447. });
  448. const widgetParam = ctrl;
  449. widgetParams.push(widgetParam);
  450. });
  451. return this.postMessage('setCtrlPos', {
  452. appName,
  453. appId,
  454. params: {
  455. array: widgetParams
  456. }
  457. });
  458. },
  459. /**
  460. * @description 重新定位控件位置
  461. * @params {Array} ['ctrlId1', 'ctrlId2']
  462. */
  463. reLocatedPosition(ctrlCode) {
  464. let _ctrlList = [];
  465. if (ctrlCode && ctrlCode.length > 0) {
  466. this.ctrls.forEach(e => {
  467. if (ctrlCode.includes(e.ctrlCode)) {
  468. _ctrlList.push(e);
  469. }
  470. });
  471. }
  472. let _needLocationList = _ctrlList.length > 0 ? _ctrlList : this.ctrls;
  473. if (_needLocationList.length === 0)
  474. return false;
  475. let exitParams = _needLocationList.filter(e => {
  476. return (e.domId && checkDomExit(e.domId, false));
  477. });
  478. let params = exitParams.map(e => {
  479. let domInfo = getDomById(e.domId);
  480. let scrollInfo = getScrollInfo();
  481. let ctrlCode = e.ctrlCode;
  482. let cutList = e.cutList;
  483. let posX = domInfo.x;
  484. let posY = domInfo.y;
  485. let width = domInfo.width;
  486. let height = domInfo.height;
  487. let ratio = scrollInfo.ratio;
  488. let scrollX = scrollInfo.scrollX;
  489. let scrollY = scrollInfo.scrollY;
  490. let scrollXH = scrollInfo.scrollXH;
  491. let scrollYW = scrollInfo.scrollYW;
  492. return { ctrlCode, cutList, posX, posY, width, height, ratio, scrollX, scrollY, scrollXH, scrollYW };
  493. });
  494. if (params.length) {
  495. return this.setCtrlPos(params);
  496. }
  497. else {
  498. return new Promise((resolve) => { resolve(true); });
  499. }
  500. },
  501. /**
  502. * @description 销毁控件
  503. *
  504. * @param {Array} ids
  505. * {
  506. * array: ['1','2']
  507. * }
  508. */
  509. destroyCtrl(ids) {
  510. if (ids.length === 0) {
  511. return false;
  512. }
  513. const _this = this;
  514. const config = this.config;
  515. //const { loginIp, userCode } = config;
  516. const { appName, appId } = config;
  517. const _ids = [...ids];
  518. // 删除缓存中的控件和ids
  519. const params = ids.map(item => {
  520. return { ctrlCode: item };
  521. });
  522. _ids.forEach(id => {
  523. // if (!_this.ids.includes(id)) {
  524. // throw new Error(`element by id:${id} has not been created.`);
  525. // }
  526. for (var i = 0; i < _this.ctrls.length; i++) {
  527. if (_this.ctrls[i].ctrlCode === id) {
  528. _this.ctrls.splice(i, 1);
  529. _this.ids.splice(i, 1);
  530. }
  531. }
  532. });
  533. return this.postMessage('destroyCtrl', {
  534. appName,
  535. appId,
  536. params: {
  537. array: params
  538. }
  539. });
  540. },
  541. /**
  542. * @description 播放实时视频
  543. *
  544. * @param {Object}
  545. * {
  546. * "ctrlCode":"ctrlCode",// 唯一标识符
  547. * "channelIds": ["AcqRGNrqA1B15042F6AMEO"]// 播放的通道编码
  548. * }
  549. */
  550. openCtrlPreview(obj) {
  551. const config = this.config;
  552. const { loginIp, userCode } = config;
  553. if (!obj.ctrlCode || !this.ids.includes(obj.ctrlCode)) {
  554. throw new Error(`widget by id:${obj.ctrlCode} has not been created.`);
  555. }
  556. if (obj.channelIds.length === 0) {
  557. return false;
  558. }
  559. const arr = obj.channelIds.map((i) => {
  560. return { channelId: i };
  561. });
  562. return this.postMessage('openCtrlPreview', {
  563. loginIp,
  564. userCode,
  565. params: {
  566. array: [
  567. {
  568. ctrlCode: obj.ctrlCode,
  569. array: arr
  570. }
  571. ]
  572. }
  573. });
  574. },
  575. /**
  576. * @description 播放录像
  577. *
  578. * @param {Object}
  579. * [
  580. * {
  581. * "ctrlCode":"code0",
  582. * "array":
  583. * [{
  584. * "beginTime": "2019-02-21 00:00:00",
  585. * "channelId": "AcqRGNrqA1B15042F6AMEO",
  586. * "endTime": "2019-02-21 23:59:59"
  587. * }]
  588. * }
  589. * ]
  590. */
  591. openCtrlRecord(arr) {
  592. const config = this.config;
  593. var obj = arr[0];
  594. if (!obj.ctrlCode || !this.ids.includes(obj.ctrlCode)) {
  595. throw new Error(`widget by id:${obj.ctrlCode} has not been created.`);
  596. }
  597. const { loginIp, userCode } = config;
  598. return this.postMessage('openCtrlRecord', {
  599. loginIp,
  600. userCode,
  601. params: {
  602. array: arr
  603. }
  604. });
  605. },
  606. /**
  607. * @description 关闭单个控件所有视频
  608. *
  609. * @param {Object}
  610. * {
  611. * "ctrlCode":["uuidcode"] //唯一标识符
  612. * }
  613. */
  614. closeCtrlVideo(arr) {
  615. const config = this.config;
  616. const { loginIp, userCode } = config;
  617. const arrParams = arr.map(item => {
  618. return { ctrlCode: item };
  619. });
  620. return this.postMessage('closeCtrlVideo', {
  621. loginIp,
  622. userCode,
  623. params: {
  624. array: arrParams
  625. }
  626. });
  627. },
  628. /**
  629. * @description 弹窗打开实时视频
  630. *
  631. * @param {Array} arr
  632. * // 标准参数 ["channelId1", "channelId2" ]
  633. * // 兼容qt参数,传入对象{array: [{channelId: "channelId1"}, {channelId: "channelId2"}]}
  634. */
  635. openVideo(arr) {
  636. const config = this.config;
  637. const { userCode, loginIp } = config;
  638. let params = {};
  639. if (Array.isArray(arr)) {
  640. let _arr = arr.map(i => {
  641. return { channelId: i };
  642. });
  643. params = { array: _arr };
  644. }
  645. else { // 兼容之前的代码,之前根据客户端协议传递,为未处理格式的对象
  646. params = arr;
  647. }
  648. return this.postMessage('openVideo', {
  649. loginIp,
  650. userCode,
  651. params: params
  652. });
  653. },
  654. /**
  655. * @description 弹窗打开录像
  656. *
  657. * @param {any} arr
  658. */
  659. openRecord(arr) {
  660. const config = this.config;
  661. const { userCode, loginIp } = config;
  662. let params = {};
  663. if (Array.isArray(arr)) {
  664. params = { array: arr };
  665. }
  666. else { // 兼容之前的代码,之前根据客户端协议传递,为未处理格式的对象
  667. params = arr;
  668. }
  669. return this.postMessage('openRecord', {
  670. loginIp,
  671. userCode,
  672. params: params
  673. });
  674. },
  675. /**
  676. * @description 打开混合弹窗
  677. * @params {String} menuCode 菜单code
  678. * @params {Array} 根据输入参数展示对应按钮。0:以图搜图,1:上传工作台,2:上传视图作战
  679. * @params {Array} array 客户端通道和播放时间
  680. * [{
  681. "channelId": "AcqRGNrqA1B15042F6AMEO", // 通道Id
  682. "beginTime": "2021-01-05 13:57:00", // 回放开始时间
  683. "endTime": "2021-01-05 14:26:59" // 回放结束时间
  684. }]
  685. */
  686. openMixedModeDialog(menuCode, array, toolBarFucList = [0, 1, 2]) {
  687. const config = this.config;
  688. const { userCode, loginIp } = config;
  689. let params = {
  690. destinationCode: menuCode,
  691. toolBarFucList: toolBarFucList,
  692. array: array
  693. };
  694. return this.postMessage('openMixedModeDialog', {
  695. loginIp,
  696. userCode,
  697. params: params
  698. });
  699. },
  700. /**
  701. * @description 图片增强
  702. *
  703. * @param {any} url
  704. * @param {any} value
  705. * @param {number} [type=1] [[1, 去偏色], [2, 去雾], [3, 夜增强], [4, 降噪]]
  706. */
  707. PictureEnhance(url, value, type = 1) {
  708. const config = this.config;
  709. const { userCode, loginIp } = config;
  710. const params = {
  711. loginIp,
  712. userCode,
  713. params: {
  714. array: [{ type: `${type}`, degree: `${value}`, url }]
  715. }
  716. };
  717. return this.postMessage('PictureEnhance', params);
  718. }
  719. };
  720. var transparent = {
  721. // 透传方法,参数不做任何处理
  722. // transparent(method, params) {
  723. // const config = this.config;
  724. // //const { loginIp, userCode } = config;
  725. // const { appName, appId } = config;
  726. // return this.postMessage(method, {
  727. // // loginIp,
  728. // // userCode,
  729. // appName,
  730. // appId,
  731. // params: params
  732. // });
  733. // },
  734. // 透传方法,参数不做任何处理
  735. transparent(method, params) {
  736. return this.postMessage(method, params);
  737. }
  738. };
  739. // import basic from './basic';
  740. var wsActions = {
  741. account,
  742. control,
  743. transparent
  744. // basic
  745. };
  746. var defaultMessageEvents = {
  747. /**
  748. * @description 获取版本信息结果
  749. */
  750. getVersionResult(data) {
  751. this.getVersionEnd = true;
  752. this.currentDssVersion = data;
  753. if (this.onlineDssVersion !== '') {
  754. this.compareVersion();
  755. }
  756. },
  757. /**
  758. * @description 客户端截图,以图搜图
  759. */
  760. goToSearchPic(data) {
  761. console.log('ws-goToSearchPic', data);
  762. if (data && data.params && data.params.array && Array.isArray(data.params.array)) {
  763. let menuCode = data.params.destinationCode;
  764. let param = {};
  765. param[menuCode] = data.params.array[0];
  766. if (frames[`nav-frame-${menuCode}`]) {
  767. frames[`nav-frame-${menuCode}`].$nav.push({
  768. code: menuCode,
  769. params: param
  770. });
  771. }
  772. else {
  773. window && window['$nav'] && window['$nav'].push({
  774. code: menuCode,
  775. params: param
  776. });
  777. }
  778. }
  779. else {
  780. this.Vue.prototype.$Message.info('未查询到数据');
  781. }
  782. },
  783. /**
  784. * @description 登陆结果
  785. */
  786. loginState(data) {
  787. console.log("登录成功");
  788. if (data) { // 登录成功
  789. this.isLoginSuccess = data;
  790. // 登录结束
  791. this.loginEnd = true;
  792. if (typeof this.callback.loginResult === 'function') {
  793. this.callback.loginResult.call(this, this.isLoginSuccess);
  794. }
  795. }
  796. else { // 登录失败
  797. this.loginFailCount++;
  798. if (this.loginFailCount < this.reLoginCount + 1) { // 登录未到最大次数
  799. this.loginClient();
  800. }
  801. else { // 登录达到最大次数
  802. // 登录结束
  803. this.loginEnd = true;
  804. // 重置登录失败次数
  805. this.loginFailCount = 0;
  806. this.isLoginSuccess = data;
  807. if (typeof this.callback.loginResult === 'function') {
  808. this.callback.loginResult.call(this, this.isLoginSuccess);
  809. }
  810. }
  811. }
  812. },
  813. registerState(data) {
  814. console.log("注册成功");
  815. if (data) { // 注册成功
  816. this.isLoginSuccess = data;
  817. // 注册结束
  818. this.loginEnd = true;
  819. if (typeof this.callback.registerResult === 'function') {
  820. this.callback.registerResult.call(this, this.isLoginSuccess);
  821. }
  822. }
  823. else { // 注册失败
  824. this.loginFailCount++;
  825. if (this.loginFailCount < this.reLoginCount + 1) { // 注册未到最大次数
  826. this.loginClient();
  827. }
  828. else { // 注册达到最大次数
  829. // 注册结束
  830. this.loginEnd = true;
  831. // 重置注册失败次数
  832. this.loginFailCount = 0;
  833. this.isLoginSuccess = data;
  834. if (typeof this.callback.registerResult === 'function') {
  835. this.callback.registerResult.call(this, this.isLoginSuccess);
  836. }
  837. }
  838. }
  839. },
  840. /**
  841. * @description 创建控件结果
  842. */
  843. createCtrlResult(data) {
  844. // todo 修改ctrls 和 ids
  845. let _data = data;
  846. let failIds = [];
  847. _data.forEach(e => {
  848. if (e.result !== 0) {
  849. failIds.push(e.ctrlCode);
  850. }
  851. });
  852. this.ids.forEach((e, i) => {
  853. if (failIds.indexOf(e) !== -1) {
  854. this.ids.splice(i, 1);
  855. this.ctrls.splice(i, 1);
  856. }
  857. });
  858. },
  859. /**
  860. * @description 销毁控件结果
  861. */
  862. destroyCtrlResult(data) {
  863. // 未发现这种情况,不好模拟,暂未调试
  864. // todo 修改ctrls 和 ids
  865. console.log(data);
  866. }
  867. };
  868. /**
  869. * @description 处理客户端返回数据的数据格式
  870. * @author 178730 <jin_cong2@dahuatech.com>
  871. * @date 2021-04-27
  872. */
  873. var dealEventData = {
  874. registerState: registerState,
  875. loginState: loginState,
  876. getVersionResult: getVersionResult,
  877. // goToSearchPic,
  878. createCtrlResult: createCtrlResult
  879. };
  880. function registerState(data) {
  881. return data.params.registerResult === 0;
  882. }
  883. function loginState(data) {
  884. return data.params.loginResult === 0;
  885. }
  886. function getVersionResult(data) {
  887. return data.params.version + '';
  888. } // function goToSearchPic(data) {
  889. // return data;
  890. // }
  891. function createCtrlResult(data) {
  892. return data.params.array;
  893. }
  894. /*! *****************************************************************************
  895. Copyright (c) Microsoft Corporation. All rights reserved.
  896. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  897. this file except in compliance with the License. You may obtain a copy of the
  898. License at http://www.apache.org/licenses/LICENSE-2.0
  899. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  900. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  901. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  902. MERCHANTABLITY OR NON-INFRINGEMENT.
  903. See the Apache Version 2.0 License for specific language governing permissions
  904. and limitations under the License.
  905. ***************************************************************************** */
  906. /* global Reflect, Promise */
  907. var extendStatics = function(d, b) {
  908. extendStatics = Object.setPrototypeOf ||
  909. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  910. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  911. return extendStatics(d, b);
  912. };
  913. function __extends(d, b) {
  914. extendStatics(d, b);
  915. function __() { this.constructor = d; }
  916. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  917. }
  918. function __values(o) {
  919. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  920. if (m) return m.call(o);
  921. return {
  922. next: function () {
  923. if (o && i >= o.length) o = void 0;
  924. return { value: o && o[i++], done: !o };
  925. }
  926. };
  927. }
  928. function __read(o, n) {
  929. var m = typeof Symbol === "function" && o[Symbol.iterator];
  930. if (!m) return o;
  931. var i = m.call(o), r, ar = [], e;
  932. try {
  933. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  934. }
  935. catch (error) { e = { error: error }; }
  936. finally {
  937. try {
  938. if (r && !r.done && (m = i["return"])) m.call(i);
  939. }
  940. finally { if (e) throw e.error; }
  941. }
  942. return ar;
  943. }
  944. function __spread() {
  945. for (var ar = [], i = 0; i < arguments.length; i++)
  946. ar = ar.concat(__read(arguments[i]));
  947. return ar;
  948. }
  949. var Event = /** @class */ (function () {
  950. function Event(type, target) {
  951. this.target = target;
  952. this.type = type;
  953. }
  954. return Event;
  955. }());
  956. var ErrorEvent = /** @class */ (function (_super) {
  957. __extends(ErrorEvent, _super);
  958. function ErrorEvent(error, target) {
  959. var _this = _super.call(this, 'error', target) || this;
  960. _this.message = error.message;
  961. _this.error = error;
  962. return _this;
  963. }
  964. return ErrorEvent;
  965. }(Event));
  966. var CloseEvent = /** @class */ (function (_super) {
  967. __extends(CloseEvent, _super);
  968. function CloseEvent(code, reason, target) {
  969. if (code === void 0) { code = 1000; }
  970. if (reason === void 0) { reason = ''; }
  971. var _this = _super.call(this, 'close', target) || this;
  972. _this.wasClean = true;
  973. _this.code = code;
  974. _this.reason = reason;
  975. return _this;
  976. }
  977. return CloseEvent;
  978. }(Event));
  979. /*!
  980. * Reconnecting WebSocket
  981. * by Pedro Ladaria <pedro.ladaria@gmail.com>
  982. * https://github.com/pladaria/reconnecting-websocket
  983. * License MIT
  984. */
  985. var getGlobalWebSocket = function () {
  986. if (typeof WebSocket !== 'undefined') {
  987. // @ts-ignore
  988. return WebSocket;
  989. }
  990. };
  991. /**
  992. * Returns true if given argument looks like a WebSocket class
  993. */
  994. var isWebSocket = function (w) { return typeof w !== 'undefined' && !!w && w.CLOSING === 2; };
  995. var DEFAULT = {
  996. maxReconnectionDelay: 10000,
  997. minReconnectionDelay: 1000 + Math.random() * 4000,
  998. minUptime: 5000,
  999. reconnectionDelayGrowFactor: 1.3,
  1000. connectionTimeout: 4000,
  1001. maxRetries: Infinity,
  1002. maxEnqueuedMessages: Infinity,
  1003. startClosed: false,
  1004. debug: false,
  1005. };
  1006. var ReconnectingWebSocket = /** @class */ (function () {
  1007. function ReconnectingWebSocket(url, protocols, options) {
  1008. var _this = this;
  1009. if (options === void 0) { options = {}; }
  1010. this._listeners = {
  1011. error: [],
  1012. message: [],
  1013. open: [],
  1014. close: [],
  1015. };
  1016. this._retryCount = -1;
  1017. this._shouldReconnect = true;
  1018. this._connectLock = false;
  1019. this._binaryType = 'blob';
  1020. this._closeCalled = false;
  1021. this._messageQueue = [];
  1022. /**
  1023. * An event listener to be called when the WebSocket connection's readyState changes to CLOSED
  1024. */
  1025. this.onclose = null;
  1026. /**
  1027. * An event listener to be called when an error occurs
  1028. */
  1029. this.onerror = null;
  1030. /**
  1031. * An event listener to be called when a message is received from the server
  1032. */
  1033. this.onmessage = null;
  1034. /**
  1035. * An event listener to be called when the WebSocket connection's readyState changes to OPEN;
  1036. * this indicates that the connection is ready to send and receive data
  1037. */
  1038. this.onopen = null;
  1039. this._handleOpen = function (event) {
  1040. _this._debug('open event');
  1041. var _a = _this._options.minUptime, minUptime = _a === void 0 ? DEFAULT.minUptime : _a;
  1042. clearTimeout(_this._connectTimeout);
  1043. _this._uptimeTimeout = setTimeout(function () { return _this._acceptOpen(); }, minUptime);
  1044. _this._ws.binaryType = _this._binaryType;
  1045. // send enqueued messages (messages sent before websocket open event)
  1046. _this._messageQueue.forEach(function (message) { return _this._ws.send(message); });
  1047. _this._messageQueue = [];
  1048. if (_this.onopen) {
  1049. _this.onopen(event);
  1050. }
  1051. _this._listeners.open.forEach(function (listener) { return _this._callEventListener(event, listener); });
  1052. };
  1053. this._handleMessage = function (event) {
  1054. _this._debug('message event');
  1055. if (_this.onmessage) {
  1056. _this.onmessage(event);
  1057. }
  1058. _this._listeners.message.forEach(function (listener) { return _this._callEventListener(event, listener); });
  1059. };
  1060. this._handleError = function (event) {
  1061. _this._debug('error event', event.message);
  1062. _this._disconnect(undefined, event.message === 'TIMEOUT' ? 'timeout' : undefined);
  1063. if (_this.onerror) {
  1064. _this.onerror(event);
  1065. }
  1066. _this._debug('exec error listeners');
  1067. _this._listeners.error.forEach(function (listener) { return _this._callEventListener(event, listener); });
  1068. _this._connect();
  1069. };
  1070. this._handleClose = function (event) {
  1071. _this._debug('close event');
  1072. _this._clearTimeouts();
  1073. if (_this._shouldReconnect) {
  1074. _this._connect();
  1075. }
  1076. if (_this.onclose) {
  1077. _this.onclose(event);
  1078. }
  1079. _this._listeners.close.forEach(function (listener) { return _this._callEventListener(event, listener); });
  1080. };
  1081. this._url = url;
  1082. this._protocols = protocols;
  1083. this._options = options;
  1084. if (this._options.startClosed) {
  1085. this._shouldReconnect = false;
  1086. }
  1087. this._connect();
  1088. }
  1089. Object.defineProperty(ReconnectingWebSocket, "CONNECTING", {
  1090. get: function () {
  1091. return 0;
  1092. },
  1093. enumerable: true,
  1094. configurable: true
  1095. });
  1096. Object.defineProperty(ReconnectingWebSocket, "OPEN", {
  1097. get: function () {
  1098. return 1;
  1099. },
  1100. enumerable: true,
  1101. configurable: true
  1102. });
  1103. Object.defineProperty(ReconnectingWebSocket, "CLOSING", {
  1104. get: function () {
  1105. return 2;
  1106. },
  1107. enumerable: true,
  1108. configurable: true
  1109. });
  1110. Object.defineProperty(ReconnectingWebSocket, "CLOSED", {
  1111. get: function () {
  1112. return 3;
  1113. },
  1114. enumerable: true,
  1115. configurable: true
  1116. });
  1117. Object.defineProperty(ReconnectingWebSocket.prototype, "CONNECTING", {
  1118. get: function () {
  1119. return ReconnectingWebSocket.CONNECTING;
  1120. },
  1121. enumerable: true,
  1122. configurable: true
  1123. });
  1124. Object.defineProperty(ReconnectingWebSocket.prototype, "OPEN", {
  1125. get: function () {
  1126. return ReconnectingWebSocket.OPEN;
  1127. },
  1128. enumerable: true,
  1129. configurable: true
  1130. });
  1131. Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSING", {
  1132. get: function () {
  1133. return ReconnectingWebSocket.CLOSING;
  1134. },
  1135. enumerable: true,
  1136. configurable: true
  1137. });
  1138. Object.defineProperty(ReconnectingWebSocket.prototype, "CLOSED", {
  1139. get: function () {
  1140. return ReconnectingWebSocket.CLOSED;
  1141. },
  1142. enumerable: true,
  1143. configurable: true
  1144. });
  1145. Object.defineProperty(ReconnectingWebSocket.prototype, "binaryType", {
  1146. get: function () {
  1147. return this._ws ? this._ws.binaryType : this._binaryType;
  1148. },
  1149. set: function (value) {
  1150. this._binaryType = value;
  1151. if (this._ws) {
  1152. this._ws.binaryType = value;
  1153. }
  1154. },
  1155. enumerable: true,
  1156. configurable: true
  1157. });
  1158. Object.defineProperty(ReconnectingWebSocket.prototype, "retryCount", {
  1159. /**
  1160. * Returns the number or connection retries
  1161. */
  1162. get: function () {
  1163. return Math.max(this._retryCount, 0);
  1164. },
  1165. enumerable: true,
  1166. configurable: true
  1167. });
  1168. Object.defineProperty(ReconnectingWebSocket.prototype, "bufferedAmount", {
  1169. /**
  1170. * The number of bytes of data that have been queued using calls to send() but not yet
  1171. * transmitted to the network. This value resets to zero once all queued data has been sent.
  1172. * This value does not reset to zero when the connection is closed; if you keep calling send(),
  1173. * this will continue to climb. Read only
  1174. */
  1175. get: function () {
  1176. var bytes = this._messageQueue.reduce(function (acc, message) {
  1177. if (typeof message === 'string') {
  1178. acc += message.length; // not byte size
  1179. }
  1180. else if (message instanceof Blob) {
  1181. acc += message.size;
  1182. }
  1183. else {
  1184. acc += message.byteLength;
  1185. }
  1186. return acc;
  1187. }, 0);
  1188. return bytes + (this._ws ? this._ws.bufferedAmount : 0);
  1189. },
  1190. enumerable: true,
  1191. configurable: true
  1192. });
  1193. Object.defineProperty(ReconnectingWebSocket.prototype, "extensions", {
  1194. /**
  1195. * The extensions selected by the server. This is currently only the empty string or a list of
  1196. * extensions as negotiated by the connection
  1197. */
  1198. get: function () {
  1199. return this._ws ? this._ws.extensions : '';
  1200. },
  1201. enumerable: true,
  1202. configurable: true
  1203. });
  1204. Object.defineProperty(ReconnectingWebSocket.prototype, "protocol", {
  1205. /**
  1206. * A string indicating the name of the sub-protocol the server selected;
  1207. * this will be one of the strings specified in the protocols parameter when creating the
  1208. * WebSocket object
  1209. */
  1210. get: function () {
  1211. return this._ws ? this._ws.protocol : '';
  1212. },
  1213. enumerable: true,
  1214. configurable: true
  1215. });
  1216. Object.defineProperty(ReconnectingWebSocket.prototype, "readyState", {
  1217. /**
  1218. * The current state of the connection; this is one of the Ready state constants
  1219. */
  1220. get: function () {
  1221. if (this._ws) {
  1222. return this._ws.readyState;
  1223. }
  1224. return this._options.startClosed
  1225. ? ReconnectingWebSocket.CLOSED
  1226. : ReconnectingWebSocket.CONNECTING;
  1227. },
  1228. enumerable: true,
  1229. configurable: true
  1230. });
  1231. Object.defineProperty(ReconnectingWebSocket.prototype, "url", {
  1232. /**
  1233. * The URL as resolved by the constructor
  1234. */
  1235. get: function () {
  1236. return this._ws ? this._ws.url : '';
  1237. },
  1238. enumerable: true,
  1239. configurable: true
  1240. });
  1241. /**
  1242. * Closes the WebSocket connection or connection attempt, if any. If the connection is already
  1243. * CLOSED, this method does nothing
  1244. */
  1245. ReconnectingWebSocket.prototype.close = function (code, reason) {
  1246. if (code === void 0) { code = 1000; }
  1247. this._closeCalled = true;
  1248. this._shouldReconnect = false;
  1249. this._clearTimeouts();
  1250. if (!this._ws) {
  1251. this._debug('close enqueued: no ws instance');
  1252. return;
  1253. }
  1254. if (this._ws.readyState === this.CLOSED) {
  1255. this._debug('close: already closed');
  1256. return;
  1257. }
  1258. this._ws.close(code, reason);
  1259. };
  1260. /**
  1261. * Closes the WebSocket connection or connection attempt and connects again.
  1262. * Resets retry counter;
  1263. */
  1264. ReconnectingWebSocket.prototype.reconnect = function (code, reason) {
  1265. this._shouldReconnect = true;
  1266. this._closeCalled = false;
  1267. this._retryCount = -1;
  1268. if (!this._ws || this._ws.readyState === this.CLOSED) {
  1269. this._connect();
  1270. }
  1271. else {
  1272. this._disconnect(code, reason);
  1273. this._connect();
  1274. }
  1275. };
  1276. /**
  1277. * Enqueue specified data to be transmitted to the server over the WebSocket connection
  1278. */
  1279. ReconnectingWebSocket.prototype.send = function (data) {
  1280. if (this._ws && this._ws.readyState === this.OPEN) {
  1281. this._debug('send', data);
  1282. this._ws.send(data);
  1283. }
  1284. else {
  1285. var _a = this._options.maxEnqueuedMessages, maxEnqueuedMessages = _a === void 0 ? DEFAULT.maxEnqueuedMessages : _a;
  1286. if (this._messageQueue.length < maxEnqueuedMessages) {
  1287. this._debug('enqueue', data);
  1288. this._messageQueue.push(data);
  1289. }
  1290. }
  1291. };
  1292. /**
  1293. * Register an event handler of a specific event type
  1294. */
  1295. ReconnectingWebSocket.prototype.addEventListener = function (type, listener) {
  1296. if (this._listeners[type]) {
  1297. // @ts-ignore
  1298. this._listeners[type].push(listener);
  1299. }
  1300. };
  1301. ReconnectingWebSocket.prototype.dispatchEvent = function (event) {
  1302. var e_1, _a;
  1303. var listeners = this._listeners[event.type];
  1304. if (listeners) {
  1305. try {
  1306. for (var listeners_1 = __values(listeners), listeners_1_1 = listeners_1.next(); !listeners_1_1.done; listeners_1_1 = listeners_1.next()) {
  1307. var listener = listeners_1_1.value;
  1308. this._callEventListener(event, listener);
  1309. }
  1310. }
  1311. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1312. finally {
  1313. try {
  1314. if (listeners_1_1 && !listeners_1_1.done && (_a = listeners_1.return)) _a.call(listeners_1);
  1315. }
  1316. finally { if (e_1) throw e_1.error; }
  1317. }
  1318. }
  1319. return true;
  1320. };
  1321. /**
  1322. * Removes an event listener
  1323. */
  1324. ReconnectingWebSocket.prototype.removeEventListener = function (type, listener) {
  1325. if (this._listeners[type]) {
  1326. // @ts-ignore
  1327. this._listeners[type] = this._listeners[type].filter(function (l) { return l !== listener; });
  1328. }
  1329. };
  1330. ReconnectingWebSocket.prototype._debug = function () {
  1331. var args = [];
  1332. for (var _i = 0; _i < arguments.length; _i++) {
  1333. args[_i] = arguments[_i];
  1334. }
  1335. if (this._options.debug) {
  1336. // not using spread because compiled version uses Symbols
  1337. // tslint:disable-next-line
  1338. console.log.apply(console, __spread(['RWS>'], args));
  1339. }
  1340. };
  1341. ReconnectingWebSocket.prototype._getNextDelay = function () {
  1342. var _a = this._options, _b = _a.reconnectionDelayGrowFactor, reconnectionDelayGrowFactor = _b === void 0 ? DEFAULT.reconnectionDelayGrowFactor : _b, _c = _a.minReconnectionDelay, minReconnectionDelay = _c === void 0 ? DEFAULT.minReconnectionDelay : _c, _d = _a.maxReconnectionDelay, maxReconnectionDelay = _d === void 0 ? DEFAULT.maxReconnectionDelay : _d;
  1343. var delay = 0;
  1344. if (this._retryCount > 0) {
  1345. delay =
  1346. minReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, this._retryCount - 1);
  1347. if (delay > maxReconnectionDelay) {
  1348. delay = maxReconnectionDelay;
  1349. }
  1350. }
  1351. this._debug('next delay', delay);
  1352. return delay;
  1353. };
  1354. ReconnectingWebSocket.prototype._wait = function () {
  1355. var _this = this;
  1356. return new Promise(function (resolve) {
  1357. setTimeout(resolve, _this._getNextDelay());
  1358. });
  1359. };
  1360. ReconnectingWebSocket.prototype._getNextUrl = function (urlProvider) {
  1361. if (typeof urlProvider === 'string') {
  1362. return Promise.resolve(urlProvider);
  1363. }
  1364. if (typeof urlProvider === 'function') {
  1365. var url = urlProvider();
  1366. if (typeof url === 'string') {
  1367. return Promise.resolve(url);
  1368. }
  1369. if (!!url.then) {
  1370. return url;
  1371. }
  1372. }
  1373. throw Error('Invalid URL');
  1374. };
  1375. ReconnectingWebSocket.prototype._connect = function () {
  1376. var _this = this;
  1377. if (this._connectLock || !this._shouldReconnect) {
  1378. return;
  1379. }
  1380. this._connectLock = true;
  1381. var _a = this._options, _b = _a.maxRetries, maxRetries = _b === void 0 ? DEFAULT.maxRetries : _b, _c = _a.connectionTimeout, connectionTimeout = _c === void 0 ? DEFAULT.connectionTimeout : _c, _d = _a.WebSocket, WebSocket = _d === void 0 ? getGlobalWebSocket() : _d;
  1382. if (this._retryCount >= maxRetries) {
  1383. this._debug('max retries reached', this._retryCount, '>=', maxRetries);
  1384. return;
  1385. }
  1386. this._retryCount++;
  1387. this._debug('connect', this._retryCount);
  1388. this._removeListeners();
  1389. if (!isWebSocket(WebSocket)) {
  1390. throw Error('No valid WebSocket class provided');
  1391. }
  1392. this._wait()
  1393. .then(function () { return _this._getNextUrl(_this._url); })
  1394. .then(function (url) {
  1395. // close could be called before creating the ws
  1396. if (_this._closeCalled) {
  1397. return;
  1398. }
  1399. _this._debug('connect', { url: url, protocols: _this._protocols });
  1400. _this._ws = _this._protocols
  1401. ? new WebSocket(url, _this._protocols)
  1402. : new WebSocket(url);
  1403. _this._ws.onerror = function (e) {
  1404. window.postMessage({method: "connectResult", success: false}, "*")
  1405. }
  1406. _this._ws.binaryType = _this._binaryType;
  1407. _this._connectLock = false;
  1408. _this._addListeners();
  1409. _this._connectTimeout = setTimeout(function () { return _this._handleTimeout(); }, connectionTimeout);
  1410. });
  1411. };
  1412. ReconnectingWebSocket.prototype._handleTimeout = function () {
  1413. this._debug('timeout event');
  1414. this._handleError(new ErrorEvent(Error('TIMEOUT'), this));
  1415. };
  1416. ReconnectingWebSocket.prototype._disconnect = function (code, reason) {
  1417. if (code === void 0) { code = 1000; }
  1418. this._clearTimeouts();
  1419. if (!this._ws) {
  1420. return;
  1421. }
  1422. this._removeListeners();
  1423. try {
  1424. this._ws.close(code, reason);
  1425. this._handleClose(new CloseEvent(code, reason, this));
  1426. }
  1427. catch (error) {
  1428. // ignore
  1429. }
  1430. };
  1431. ReconnectingWebSocket.prototype._acceptOpen = function () {
  1432. this._debug('accept open');
  1433. this._retryCount = 0;
  1434. };
  1435. ReconnectingWebSocket.prototype._callEventListener = function (event, listener) {
  1436. if ('handleEvent' in listener) {
  1437. // @ts-ignore
  1438. listener.handleEvent(event);
  1439. }
  1440. else {
  1441. // @ts-ignore
  1442. listener(event);
  1443. }
  1444. };
  1445. ReconnectingWebSocket.prototype._removeListeners = function () {
  1446. if (!this._ws) {
  1447. return;
  1448. }
  1449. this._debug('removeListeners');
  1450. this._ws.removeEventListener('open', this._handleOpen);
  1451. this._ws.removeEventListener('close', this._handleClose);
  1452. this._ws.removeEventListener('message', this._handleMessage);
  1453. // @ts-ignore
  1454. this._ws.removeEventListener('error', this._handleError);
  1455. };
  1456. ReconnectingWebSocket.prototype._addListeners = function () {
  1457. if (!this._ws) {
  1458. return;
  1459. }
  1460. this._debug('addListeners');
  1461. this._ws.addEventListener('open', this._handleOpen);
  1462. this._ws.addEventListener('close', this._handleClose);
  1463. this._ws.addEventListener('message', this._handleMessage);
  1464. // @ts-ignore
  1465. this._ws.addEventListener('error', this._handleError);
  1466. };
  1467. ReconnectingWebSocket.prototype._clearTimeouts = function () {
  1468. clearTimeout(this._connectTimeout);
  1469. clearTimeout(this._uptimeTimeout);
  1470. };
  1471. return ReconnectingWebSocket;
  1472. }());
  1473. var reconnectingWebsocketCjs = ReconnectingWebSocket;
  1474. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  1475. function unwrapExports (x) {
  1476. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  1477. }
  1478. function createCommonjsModule(fn, module) {
  1479. return module = { exports: {} }, fn(module, module.exports), module.exports;
  1480. }
  1481. var es5 = createCommonjsModule(function (module, exports) {
  1482. !function(e,t){module.exports=t();}(commonjsGlobal,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n});},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return "NT";case"XP":return "XP";case"NT 5.0":return "2000";case"NT 5.1":return "XP";case"NT 5.2":return "2003";case"NT 6.0":return "Vista";case"NT 6.1":return "7";case"NT 6.2":return "8";case"NT 6.3":return "8.1";case"NT 10.0":return "10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return "Leopard";case 6:return "Snow Leopard";case 7:return "Lion";case 8:return "Mountain Lion";case 9:return "Mavericks";case 10:return "Yosemite";case 11:return "El Capitan";case 12:return "Sierra";case 13:return "High Sierra";case 14:return "Mojave";case 15:return "Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),o=Math.max(i,s),a=0,u=e.map([t,r],(function(t){var r=o-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(u[0][o]>u[1][o])return 1;if(u[0][o]===u[1][o]){if(o===a)return 0;o-=1;}else if(u[0][o]<u[1][o])return -1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),o=1;o<i;o++)s[o-1]=arguments[o];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var a=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach((function(t){n[t]=e[t];}));};for(t=0,r=s.length;t<r;t+=1)a();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default;},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0;t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"};t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"};t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"};t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"};t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n);}}var a=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&o(t.prototype,r),n&&o(t,n),e}();t.default=a,e.exports=t.default;},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=u(r(92)),i=u(r(93)),s=u(r(94)),o=u(r(95)),a=u(r(17));function u(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse();}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=a.default.find(n.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=a.default.find(i.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=a.default.find(s.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=a.default.find(o.default,(function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some((function(t){return e.test(t)}));throw new Error("Browser's test function is not valid")}));return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return a.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach((function(t){var o=e[t];"string"==typeof o?(i[t]=o,s+=1):"object"==typeof o&&(r[t]=o,n+=1);})),n>0){var o=Object.keys(r),u=a.default.find(o,(function(e){return t.isOS(e)}));if(u){var d=this.satisfies(r[u]);if(void 0!==d)return d}var c=a.default.find(o,(function(e){return t.isPlatform(e)}));if(c){var f=this.satisfies(r[c]);if(void 0!==f)return f}}if(s>0){var l=Object.keys(i),h=a.default.find(l,(function(e){return t.isBrowser(e,!0)}));if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return ">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e){return this.isBrowser(e)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=d,e.exports=t.default;},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n};var s=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(s,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return {name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default;},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var o=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return {name:s.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return {name:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?) Version\//],describe:function(e){var t=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return {name:s.OS_MAP.iOS,version:t}}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:s.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return {name:s.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:s.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:s.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return {name:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return {name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return {name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return {name:s.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default;},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var o=[{test:[/googlebot/i],describe:function(){return {type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?) Version\//],describe:function(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return {type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return {type:s.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return {type:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return {type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return {type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return "blackberry"===e.getBrowserName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return "bada"===e.getBrowserName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return "windows phone"===e.getBrowserName()},describe:function(){return {type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return "android"===e.getOSName(!0)&&t>=3},describe:function(){return {type:s.PLATFORMS_MAP.tablet}}},{test:function(e){return "android"===e.getOSName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return "macos"===e.getOSName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return "windows"===e.getOSName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return "linux"===e.getOSName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return "playstation 4"===e.getOSName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.tv}}},{test:function(e){return "roku"===e.getOSName(!0)},describe:function(){return {type:s.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default;},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var o=[{test:function(e){return "microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return {name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return {name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:s.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:s.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return {name:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default;}})}));
  1483. });
  1484. var Bowser = unwrapExports(es5);
  1485. es5.bowser;
  1486. // 与客户端交互方法列表
  1487. const browser = Bowser.getParser(window.navigator.userAgent);
  1488. class Ws {
  1489. constructor({ url = 'ws://localhost', port = '1234', publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbEpPpxpLJft4W9YZj8bRh2bYYZshBEsKOlxgyn11rlEyTasjBSZRV9aj33tvQ2T55izH0fWl+dL/dLZChawFrlGDcH8JuWge2xYMgII9mggcYa0UiQ7pLXJ9ivXZ/cOY3HzrRQdR7dGTSNn3Z0Ctbns6mLgvlA2r3qMNs/8wHBwIDAQAB', reConnectCount = 3, reLoginCount = 0, loginIp = location.hostname, appName = "", loginPort = location.port, userName = '', userPwd = '', token = '', callback = {
  1490. connectResult: null,
  1491. loginResult: null
  1492. }, isKeepConnect = true, detectDssVersion = true, messageEvents = {} }) {
  1493. // 是否连接客户端
  1494. this.isConnectSuccessQt = false;
  1495. // 是否登录客户端
  1496. this.isLoginSuccess = false;
  1497. // 外部注册客户端消息处理
  1498. this.messageEvents = {};
  1499. // 最大重连数
  1500. this.reConnectCount = 3;
  1501. // 连接失败次数
  1502. this.connectFailCount = 0;
  1503. // 连接完成标识
  1504. this.connectEnd = true;
  1505. // 连接客户端开始时间
  1506. this.connectStartTime = 0;
  1507. // 连接超时时间
  1508. this.connectTimeOut = 30 * 1000;
  1509. // 登录完成标识
  1510. this.loginEnd = true;
  1511. // 登录客户端开始时间
  1512. this.loginStartTime = 0;
  1513. // 登录超时时间
  1514. this.loginTimeOut = 60 * 1000;
  1515. // 最大重登数
  1516. this.reLoginCount = 0;
  1517. // 连接失败次数
  1518. this.loginFailCount = 0;
  1519. // 当前websocket登录配置
  1520. this.config = {
  1521. browser: {}
  1522. };
  1523. // 用户标识符
  1524. this.userCode = 0;
  1525. //对应注册的唯一编码
  1526. this.appId = 0;
  1527. // 是否检测客户端版本
  1528. this.detectDssVersion = true;
  1529. // 当前客户端版本
  1530. this.currentDssVersion = '';
  1531. // 获取当前版本结束标志
  1532. //getVersionEnd: Boolean = true;
  1533. // 获取版本开始时间
  1534. //getVersionStartTime: number = 0;
  1535. // 获取版本超时时间
  1536. //getVersionTimeOut: number = 30 * 1000;
  1537. // 线上客户端版本
  1538. this.onlineDssVersion = '';
  1539. // 线上客户顿版本获取地址后缀,32系统文件名添加32
  1540. this.onlineDssVersionAfterfix = '/data/VSL/DSSEnterpriseClient/LightWeightVersion.txt';
  1541. // 线上客户顿获取地址后缀,32系统文件名添加32
  1542. this.onlineDssAfterfix = '/data/VSL/DSSEnterpriseClient/DSS_LightWeight_Client.zip';
  1543. // 是否一直保持重新连接
  1544. this.isKeepConnect = true;
  1545. // 创建的控件ID列表
  1546. this.ids = [];
  1547. // 创建的控件列表
  1548. this.ctrls = [];
  1549. // 心跳
  1550. this.heartBeatTimer = null;
  1551. // 监听的添加式方法表
  1552. this.handlers = {};
  1553. this.url = url;
  1554. this.port = port;
  1555. this.userCode = new Date().valueOf();
  1556. this.appId = new Date().valueOf(); //对应注册的唯一编码,可以取一个随机字符串。
  1557. this.webSocket = null;
  1558. this.reConnectCount = reConnectCount;
  1559. this.reLoginCount = reLoginCount;
  1560. this.publicKey = publicKey;
  1561. this.loginIp = loginIp;
  1562. this.appName = appName; //应用名称,相同的应用名称会共用一个客户端进程。
  1563. this.loginPort = loginPort;
  1564. this.userName = userName;
  1565. this.userPwd = userPwd;
  1566. this.token = token;
  1567. this.callback = callback;
  1568. this.isKeepConnect = isKeepConnect;
  1569. this.detectDssVersion = detectDssVersion;
  1570. this.messageEvents = messageEvents || {};
  1571. this.connectFailCount = this.connectFailCount;
  1572. // 基础操作所需功能或属性
  1573. this.ids = [];
  1574. this.ctrls = [];
  1575. // 是否连接客户端
  1576. this.isConnectSuccessQt = false;
  1577. // 是否登陆客户端
  1578. this.isLoginSuccess = false;
  1579. this.heartBeatTimer = null;
  1580. // 用户注册监听事件表
  1581. this.handlers = {};
  1582. // 用户注册监听事件表
  1583. this.listerns = new Map();
  1584. // 获取与客户端交互方法列表
  1585. const defaultActions = [];
  1586. Object.keys(wsActions).forEach(item => {
  1587. if (hasKey(wsActions, item)) {
  1588. defaultActions.push(wsActions[item]);
  1589. }
  1590. });
  1591. // 与客户端通讯功能注册
  1592. usePlugin(defaultActions);
  1593. // 处理客户端消息 合并以内置方法为主,客户自定义事件与内置方法重复,则抛弃
  1594. this.messageEvents = Object.assign(this.messageEvents, defaultMessageEvents);
  1595. Object.keys(this.messageEvents).forEach(item => {
  1596. this.addEventListener(item, this.messageEvents[item].bind(this));
  1597. });
  1598. // 初始化配置参数
  1599. this.initConfig();
  1600. // 连接客户端
  1601. //this. connectSocket();
  1602. // 登录
  1603. // this.detectConnectQt().then((res: Boolean) => {
  1604. // if(res) {
  1605. // // 登陆客户端
  1606. // console.log(212);
  1607. // this.loginClient();
  1608. // }
  1609. // });
  1610. }
  1611. /**
  1612. * @description 获得实例对象
  1613. */
  1614. static getInstance(options) {
  1615. if (!top['$ws']) {
  1616. if (!this._instance) {
  1617. this._instance = new Ws(options || {});
  1618. top['$ws'] = this._instance;
  1619. }
  1620. }
  1621. else {
  1622. this._instance = top['$ws'];
  1623. // TODO 合并参数
  1624. // 合并messageEvents
  1625. // if(options.messageEvents) {
  1626. // Object.assign(this._instance.messageEvents, options.messageEvents);
  1627. // 移除所有监听
  1628. // ------
  1629. // Object.keys(this._instance.messageEvents).forEach(item => {
  1630. // this._instance.addEventListener(item, this._instance.messageEvents[item].bind(this._instance));
  1631. // });
  1632. // }
  1633. }
  1634. return this._instance;
  1635. }
  1636. /**
  1637. * @description 用户注册监听事件,覆盖式监听
  1638. * @params {String} eventType 事件名称
  1639. * @params {any} callback 回调函数
  1640. */
  1641. on(eventType, callback) {
  1642. this.listerns.set(eventType, callback);
  1643. }
  1644. /**
  1645. * @description 用户取消监听事件,覆盖式监听
  1646. * @params {String} eventType 事件名称
  1647. */
  1648. off(eventType) {
  1649. delete this.listerns[eventType];
  1650. }
  1651. /**
  1652. * @description 用户注册监听事件,添加式监听
  1653. * @params {String} eventType 事件名称
  1654. * @params {any} handler 回调函数
  1655. */
  1656. addEventListener(eventType, handler) {
  1657. // 首先判断handlers内有没有type事件容器,没有则创建一个新数组容器
  1658. if (!(eventType in this.handlers)) {
  1659. this.handlers[eventType] = [];
  1660. }
  1661. // 将事件存入
  1662. this.handlers[eventType].push(handler);
  1663. }
  1664. /**
  1665. * @description 添加式监听,触发事件
  1666. * @params {String} eventType 事件名称
  1667. * @params {any} params 函数参数
  1668. */
  1669. dispatchEvent(eventType, ...params) {
  1670. // 若没有注册该事件则抛出错误
  1671. if (!(eventType in this.handlers)) {
  1672. return new Error('未注册该事件');
  1673. }
  1674. // 便利触发
  1675. this.handlers[eventType].forEach(handler => {
  1676. handler(...params);
  1677. });
  1678. }
  1679. /**
  1680. * @description 用户取消监听事件
  1681. * @params {String} eventType 事件名称
  1682. */
  1683. removeEventListener(eventType, handler) {
  1684. // 无效事件抛出
  1685. if (!(eventType in this.handlers)) {
  1686. return new Error('无效事件');
  1687. }
  1688. if (!handler) {
  1689. // 直接移除事件
  1690. delete this.handlers[eventType];
  1691. }
  1692. else {
  1693. const idx = this.handlers[eventType].findIndex(ele => ele === handler);
  1694. // 抛出异常事件
  1695. if (idx === -1) {
  1696. return new Error('无该绑定事件');
  1697. }
  1698. // 移除事件
  1699. this.handlers[eventType].splice(idx, 1);
  1700. if (this.handlers[eventType].length === 0) {
  1701. delete this.handlers[eventType];
  1702. }
  1703. }
  1704. }
  1705. /**
  1706. * @description 发送消息给客户端
  1707. * @params {String} method 事件名称
  1708. * @params {Object} data 传输消息的数据内容
  1709. */
  1710. postMessage(method, data) {
  1711. console.log('sendMessageToClient', method, data);
  1712. const { webSocket } = this;
  1713. data.method = method;
  1714. // 不需要判断登录和连接的方法过滤
  1715. //let filterList = ['register', 'unregister', 'browserInfo', 'getVersion', 'trusteSite'];
  1716. let filterList = ['register', 'unregister', 'browserInfo', 'trusteSite'];
  1717. if (filterList.includes(method)) {
  1718. webSocket.send(JSON.stringify(data));
  1719. // if(method == 'unregister'){
  1720. // const { appName } = _this.config;
  1721. // if('appName' in _this.config){
  1722. // _this.config[appName] = '';
  1723. // }
  1724. // }
  1725. return Promise.resolve(true);
  1726. }
  1727. return new Promise((resolve, reject) => {
  1728. this.keeper().then(res => {
  1729. if (res) {
  1730. // if(method == "register"){
  1731. // _this.loginEnd = true;
  1732. // }
  1733. webSocket.send(JSON.stringify(data));
  1734. resolve(true);
  1735. }
  1736. else {
  1737. reject(false);
  1738. }
  1739. }).catch(e => {
  1740. console.error('ws-error in keeper');
  1741. });
  1742. });
  1743. }
  1744. /*
  1745. * 初始化配置
  1746. */
  1747. initConfig() {
  1748. // token登陆的username通过token截取
  1749. if (this.token && this.token.split('_')[0]) {
  1750. this.userName = this.token.split('_')[0];
  1751. }
  1752. this.config = {
  1753. userName: this.userName,
  1754. userCode: this.userCode,
  1755. appId: this.appId,
  1756. loginPort: this.loginPort,
  1757. loginIp: this.loginIp,
  1758. userPwd: this.userPwd,
  1759. token: this.token,
  1760. appName: this.appName,
  1761. port: this.port
  1762. };
  1763. // 浏览器信息
  1764. const browserInfo = {
  1765. name: '',
  1766. version: '',
  1767. platform: ''
  1768. };
  1769. browserInfo.name = browser.getBrowserName().toLowerCase();
  1770. browserInfo.version = browser.getBrowser().version.toLowerCase();
  1771. browserInfo.platform =
  1772. browser._ua.indexOf('Win64') >= 0 || browser._ua.indexOf('Wow64') >= 0
  1773. ? 'win64'
  1774. : 'win32';
  1775. this.config['browser'] = browserInfo;
  1776. }
  1777. /**
  1778. * @description 连接客户端
  1779. */
  1780. connectSocket(config) {
  1781. this.connectFailCount = 0;
  1782. this.connectEnd = false;
  1783. this.connectStartTime = Date.now();
  1784. let { port } = config;
  1785. let url = this.url + ":" + port;
  1786. // 连接客户端
  1787. this.webSocket = new reconnectingWebsocketCjs(url, '', {
  1788. maxRetries: this.reConnectCount
  1789. });
  1790. // 取消订阅的事件
  1791. this.removeEvents();
  1792. // 订阅事件
  1793. this.addEvents();
  1794. return this.detectConnectQt();
  1795. }
  1796. /**
  1797. * @description 获取线上和线下客户端版本
  1798. */
  1799. // getDSSVersion() {
  1800. // this.getOnlineDssVersion();
  1801. // this.getLocalDssVersion();
  1802. // }
  1803. /**
  1804. * @description 获取线上客户端版本
  1805. */
  1806. // getOnlineDssVersion() {
  1807. // // 待解决跨域问题
  1808. // let _this = this;
  1809. // let platform = this.config['browser'].platform;
  1810. // let versionUrl = this.onlineDssVersionAfterfix;
  1811. // if(platform === 'win32') {
  1812. // versionUrl = versionUrl.replace('.txt', '32.txt');
  1813. // }
  1814. // var request = new XMLHttpRequest();
  1815. // request.open("get", versionUrl);/*设置请求方法与路径*/
  1816. // request.send(null);/*不发送数据到服务器*/
  1817. // request.onload = function () {/*XHR对象获取到返回信息后执行*/
  1818. // if (request.status == 200) {/*返回状态为200,即为数据获取成功*/
  1819. // _this.onlineDssVersion = request.response.replace('ClientVersion = ', '')
  1820. // if(_this.currentDssVersion !== '') {
  1821. // _this.compareVersion();
  1822. // }
  1823. // }
  1824. // }
  1825. // }
  1826. /**
  1827. * @description 检测连接客户端状态
  1828. */
  1829. detectConnectQt() {
  1830. let _this = this;
  1831. return new Promise((resolve, reject) => {
  1832. if (!_this.connectEnd) { // 连接中
  1833. // let now = Date.now();
  1834. // if((now - _this.connectStartTime) > _this.connectTimeOut) {
  1835. // console.log(`ws-this.connectEndTime-${now}`);
  1836. // reject('connect timeout');
  1837. // }
  1838. let _interval = setInterval(() => {
  1839. if (_this.connectEnd) {
  1840. clearInterval(_interval);
  1841. resolve(_this.isConnectSuccessQt);
  1842. }
  1843. }, 50);
  1844. }
  1845. else {
  1846. resolve(_this.isConnectSuccessQt);
  1847. }
  1848. });
  1849. }
  1850. /**
  1851. * @description 检测登录客户端状态
  1852. */
  1853. detectLoginClient() {
  1854. let _this = this;
  1855. return new Promise((resolve, reject) => {
  1856. console.log(this.loginEnd, "this.loginEnd");
  1857. if (!this.loginEnd) { // 登录中
  1858. let _interval = setInterval(() => {
  1859. if (_this.loginEnd) {
  1860. clearInterval(_interval);
  1861. resolve(_this.isLoginSuccess);
  1862. }
  1863. }, 50);
  1864. }
  1865. else {
  1866. resolve(_this.isLoginSuccess);
  1867. }
  1868. });
  1869. }
  1870. /**
  1871. * @description 连接状态守护
  1872. */
  1873. keepConnect() {
  1874. return new Promise((resolve, reject) => {
  1875. // 监测连接状态
  1876. this.detectConnectQt().then((connectStatus) => {
  1877. // 连接正常
  1878. if (connectStatus) {
  1879. resolve(true);
  1880. }
  1881. else {
  1882. // 连接状态失效,重新连接
  1883. // this. connectSocket({}).then((ReconnectStatus: Boolean) => {
  1884. // // 重连成功
  1885. // if(ReconnectStatus) {
  1886. // resolve(true);
  1887. // } else {
  1888. // console.log(`ws-in-keepConnect-reConnect-fail`);
  1889. // reject(false);
  1890. // }
  1891. // })
  1892. this.Vue.prototype.$Message.info("请先连接客户端");
  1893. }
  1894. });
  1895. });
  1896. }
  1897. /**
  1898. * @description 连接和登录状态守护
  1899. */
  1900. keeper() {
  1901. return new Promise((resolve, reject) => {
  1902. // 监测连接状态
  1903. this.detectConnectQt().then((connectStatus) => {
  1904. // 连接正常
  1905. if (connectStatus) {
  1906. this.detectLoginClient().then((loginStatus) => {
  1907. // 登录正常
  1908. if (loginStatus) {
  1909. resolve(true);
  1910. }
  1911. else {
  1912. // 登录异常
  1913. // 登录
  1914. console.log(507);
  1915. this.loginClient();
  1916. // 登录后的状态监测
  1917. this.detectLoginClient().then((reLoginStatus) => {
  1918. if (reLoginStatus) {
  1919. resolve(true);
  1920. }
  1921. else {
  1922. console.log(`ws-in-keeper-reLogin-fail`);
  1923. reject(false);
  1924. }
  1925. });
  1926. }
  1927. });
  1928. }
  1929. else {
  1930. // 连接状态失效,重新连接
  1931. // this. connectSocket({}).then((ReconnectStatus: Boolean) => {
  1932. // // 连接成功
  1933. // if(ReconnectStatus) {
  1934. // // 登录
  1935. // console.log(`ws-in-keeper-reConnect-reLogin`);
  1936. // console.log(528);
  1937. // this.loginClient()
  1938. // // 登录状态监测
  1939. // this.detectLoginClient().then((loginStatus: Boolean) => {
  1940. // if(loginStatus) {
  1941. // resolve(true);
  1942. // } else {
  1943. // console.log(`ws-in-keeper-reLogin-fail`);
  1944. // reject(false);
  1945. // }
  1946. // })
  1947. // } else {
  1948. // console.log(`ws-in-keeper-reConnect-fail`);
  1949. // reject(false);
  1950. // }
  1951. // })
  1952. this.Vue.prototype.$Message.info("请先连接客户端");
  1953. }
  1954. });
  1955. });
  1956. }
  1957. /**
  1958. * @description 获取当前客户端版本
  1959. */
  1960. // getLocalDssVersion() {
  1961. // let _this = this;
  1962. // this.getVersion();
  1963. // console.log(`ws-getLocalDssVersion-getVersionEnd-${this.getVersionEnd}`)
  1964. // return new Promise((resolve, reject) => {
  1965. // if(!this.getVersionEnd) { // 连接中或者获取中
  1966. // // let now = Date.now();
  1967. // // if((now - _this.getVersionStartTime) > _this.getVersionTimeOut) {
  1968. // // console.log(`ws-this.getVersionEndTime-${now}`);
  1969. // // reject('get version timeout');
  1970. // // }
  1971. // let _interval = setInterval(() => {
  1972. // if(_this.getVersionEnd) {
  1973. // clearInterval(_interval);
  1974. // resolve(_this.currentDssVersion);
  1975. // }
  1976. // }, 50)
  1977. // } else {
  1978. // resolve(_this.currentDssVersion);
  1979. // }
  1980. // })
  1981. // }
  1982. /**
  1983. * @description 比较客户端版本
  1984. */
  1985. compareVersion() {
  1986. if (this.currentDssVersion && this.onlineDssVersion && Number(this.onlineDssVersion) > Number(this.currentDssVersion)) {
  1987. this.dispatchEvent('updateDss');
  1988. // this.Vue && this.Vue.prototype.$Modal.confirm({
  1989. // title: '客户端更新',
  1990. // content: '系统检测到新客户端版本,请更新后使用?',
  1991. // onOk: () => {
  1992. // this.downloadClient();
  1993. // },
  1994. // onCancel: () => {
  1995. // this.detectDssVersion = false;
  1996. // }
  1997. // });
  1998. }
  1999. }
  2000. /**
  2001. * @description 下载客户端
  2002. */
  2003. downloadClient() {
  2004. var agent = navigator.userAgent.toLowerCase();
  2005. let type = '64';
  2006. if (agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0) {
  2007. type = '32';
  2008. }
  2009. else if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) {
  2010. type = '64';
  2011. }
  2012. let downUrl = location.origin + '/data/VSL/DSSEnterpriseClient/DSS_LightWeight_Client';
  2013. type === '32' ? downUrl = downUrl + '32.zip' : downUrl = downUrl + '.zip';
  2014. window.open(downUrl);
  2015. }
  2016. /**
  2017. * @description 登录客户端
  2018. * @params {Object} config 登录相关配置
  2019. */
  2020. register(config) {
  2021. console.log('ws-login-start');
  2022. this.loginFailCount = 0;
  2023. // 如果登陆时用户名变更,更新userCode
  2024. let { userName, token } = config;
  2025. // token登陆的username通过token截取
  2026. if (token && token.split('_')[0]) {
  2027. userName = token.split('_')[0];
  2028. }
  2029. if (this.config['userName'] && (userName !== this.config['userName'])) {
  2030. this.userCode = new Date().valueOf();
  2031. this.appId = new Date().valueOf();
  2032. }
  2033. this.userName = userName;
  2034. this.initConfig();
  2035. Object.assign(this.config, config);
  2036. this.detectConnectQt().then((res) => {
  2037. if (res) {
  2038. // 若已登录,先注销
  2039. console.log('ws-login-start-this.isLoginSuccess', this.isLoginSuccess);
  2040. // if (this.isLoginSuccess) {
  2041. // this.unregister();
  2042. // }
  2043. // 登陆客户端
  2044. console.log(637);
  2045. this.loginClient();
  2046. // 获取线上客户端版本
  2047. //this.detectDssVersion && this.getDSSVersion();
  2048. }
  2049. else {
  2050. // 未连接客户端
  2051. // this. connectSocket({}).then((res1: Boolean) => {
  2052. // if(res1) {
  2053. // // 登陆客户端
  2054. // console.log(646);
  2055. // this.loginClient();
  2056. // // 获取线上客户端版本
  2057. // this.detectDssVersion && this.getDSSVersion();
  2058. // } else {
  2059. // throw new Error('连接客户端失败');
  2060. // }
  2061. // })
  2062. this.Vue.prototype.$Message.info("请先连接客户端");
  2063. }
  2064. });
  2065. }
  2066. /**
  2067. * @description 登出客户端
  2068. */
  2069. unregister() {
  2070. // 退出客户端
  2071. this.logoutClient();
  2072. // this.detectLoginClient().then(res => {
  2073. // res && this.logoutClient();
  2074. // })
  2075. this.ids = [];
  2076. this.ctrls = [];
  2077. this.isLoginSuccess = false;
  2078. if (typeof this.callback.loginResult === 'function') {
  2079. this.callback.loginResult.call(this, this.isLoginSuccess);
  2080. }
  2081. }
  2082. /**
  2083. * @description 添加websocket/window监听事件
  2084. */
  2085. addEvents() {
  2086. const webSocket = this.webSocket;
  2087. webSocket.addEventListener('open', this.onOpen.bind(this));
  2088. webSocket.addEventListener('message', this.onMessage.bind(this));
  2089. webSocket.addEventListener('error', this.onError.bind(this));
  2090. window.addEventListener('resize', this.reLocatedPosition.bind(this));
  2091. window.addEventListener('scroll', this.reLocatedPosition.bind(this));
  2092. window.addEventListener('visibilitychange', this.webVisibilityChange.bind(this));
  2093. window.addEventListener('onunload', this.closeBrowser.bind(this));
  2094. }
  2095. /**
  2096. * @description 移除websocket/window监听事件
  2097. */
  2098. removeEvents() {
  2099. const webSocket = this.webSocket;
  2100. webSocket.removeEventListener('open', this.onOpen);
  2101. webSocket.removeEventListener('message', this.onMessage);
  2102. webSocket.removeEventListener('error', this.onError);
  2103. window.removeEventListener('resize', this.reLocatedPosition);
  2104. window.removeEventListener('scroll', this.reLocatedPosition);
  2105. window.removeEventListener('visibilitychange', this.webVisibilityChange);
  2106. window.removeEventListener('onunload', this.closeBrowser);
  2107. }
  2108. /**
  2109. * @description 连接客户端成功事件
  2110. */
  2111. onOpen() {
  2112. console.log('ws-onOpen');
  2113. // chrome浏览器版本大于80,需要添加信任站点,加载http/https跨站点资源
  2114. // if(this.config['browser'].name === 'chrome' && this.config['browser'].version && Number(this.config['browser'].version.split('.')[0]) >= 80) {
  2115. // this.trusteSite(location.hostname);
  2116. // }
  2117. this.isConnectSuccessQt = true;
  2118. this.dispatchEvent('connectStateChange', true);
  2119. this.connectEnd = true;
  2120. if (typeof this.callback.connectResult === 'function') {
  2121. this.callback.connectResult.call(this, this.isConnectSuccessQt);
  2122. }
  2123. // 获取客户端版本
  2124. //this.getVersionEnd = false;
  2125. //this.getDSSVersion();
  2126. }
  2127. /**
  2128. * @description 接收客户端消息
  2129. * @params {Object} event 接收客户端的消息数据
  2130. */
  2131. onMessage(event) {
  2132. try {
  2133. const data = JSON.parse(event.data);
  2134. const { method } = data;
  2135. console.log('receiveMessageFromClient', method, event);
  2136. const callback = this.listerns.get(method);
  2137. // 数据格式处理
  2138. let dealDataRes = dealEventData[method] ? dealEventData[method](data) : data;
  2139. this.dispatchEvent(method, dealDataRes);
  2140. // if (method === 'registerState') {
  2141. // callback;
  2142. // }
  2143. // else {
  2144. // callback && callback(data);
  2145. // }
  2146. // if (method === 'loginState') {
  2147. // console.log(this.isLoginSuccess, "this.isLoginSuccess");
  2148. // callback;
  2149. // }
  2150. // else {
  2151. // callback && callback(data);
  2152. // }
  2153. callback && callback(data);
  2154. }
  2155. catch (e) {
  2156. // 客户端协议中含有返回的不是Json数据
  2157. console.log('ws-error-客户端返回的消息不是Json数据', e);
  2158. }
  2159. }
  2160. /**
  2161. * @description 客户端发生错误事件
  2162. */
  2163. onError() {
  2164. this.ctrls = [];
  2165. this.ids = [];
  2166. this.isConnectSuccessQt = false;
  2167. // clearTimeout(this.heartbeatTimer);
  2168. this.connectFailCount++;
  2169. this.dispatchEvent('connectStateChange', false);
  2170. if (this.connectFailCount === this.reConnectCount + 1) {
  2171. this.connectEnd = true;
  2172. this.isKeepConnect && this.keepConnect();
  2173. if (typeof this.callback.connectResult === 'function') {
  2174. this.callback.connectResult.call(this, this.isConnectSuccessQt);
  2175. }
  2176. }
  2177. }
  2178. /**
  2179. * @description 判断是否成功连接客户端
  2180. */
  2181. isOpen() {
  2182. if (!this.webSocket)
  2183. return false;
  2184. return this.webSocket.readyState === 1;
  2185. }
  2186. /**
  2187. * @description 心跳事件
  2188. */
  2189. // _heartbeat() {
  2190. // this.heartbeat();
  2191. // clearTimeout(this.heartbeatTimer);
  2192. // this.heartbeatTimer = setTimeout(() => {
  2193. // this._heartbeat();
  2194. // }, 10000);
  2195. // }
  2196. /**
  2197. * @description 关闭浏览器事件
  2198. */
  2199. closeBrowser() {
  2200. this.unregister();
  2201. // 延迟100ms登出,关闭所有控件
  2202. var timestamp = new Date().getTime();
  2203. while ((new Date().getTime() - timestamp) < 100) { }
  2204. }
  2205. }
  2206. // 唯一实例
  2207. Ws._instance = null;
  2208. /**
  2209. * @description 判断对象是否含有某属性
  2210. * @params {Object} obj 对象
  2211. * @params {String} key 属性key
  2212. */
  2213. function hasKey(obj, key) {
  2214. return key in obj;
  2215. }
  2216. /**
  2217. * @description 与客户端通讯功能注册
  2218. * @params {Array} actions 功能列表
  2219. */
  2220. function usePlugin(actions) {
  2221. actions.forEach((plugin) => {
  2222. Object.getOwnPropertyNames(plugin).forEach(prop => {
  2223. Ws.prototype[prop] = plugin[prop];
  2224. });
  2225. });
  2226. }
  2227. return Ws;
  2228. })));
  2229. //# sourceMappingURL=DHWs.js.map