main.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. /**
  2. * 页面专用
  3. */
  4. import '../../sass/main.scss';
  5. (function (window) {
  6. let apiUrl = window.location.origin + '/api/';
  7. let $ = window.$A;
  8. $.extend({
  9. fillUrl(str) {
  10. if (str.substring(0, 2) === "//" ||
  11. str.substring(0, 7) === "http://" ||
  12. str.substring(0, 8) === "https://" ||
  13. str.substring(0, 6) === "ftp://" ||
  14. str.substring(0, 1) === "/") {
  15. return str;
  16. }
  17. return window.location.origin + '/' + str;
  18. },
  19. webUrl(str) {
  20. return $A.fillUrl(str || '');
  21. },
  22. apiUrl(str) {
  23. if (str.substring(0, 2) === "//" ||
  24. str.substring(0, 7) === "http://" ||
  25. str.substring(0, 8) === "https://" ||
  26. str.substring(0, 6) === "ftp://" ||
  27. str.substring(0, 1) === "/") {
  28. return str;
  29. }
  30. return apiUrl + str;
  31. },
  32. apiAjax(params) {
  33. if (typeof params !== 'object') return false;
  34. if (typeof params.success === 'undefined') params.success = () => { };
  35. params.url = this.apiUrl(params.url);
  36. //
  37. let beforeCall = params.beforeSend;
  38. params.beforeSend = () => {
  39. $A.aAjaxLoad++;
  40. $A(".w-spinner").show();
  41. //
  42. if (typeof beforeCall == "function") {
  43. beforeCall();
  44. }
  45. };
  46. //
  47. let completeCall = params.complete;
  48. params.complete = () => {
  49. $A.aAjaxLoad--;
  50. if ($A.aAjaxLoad <= 0) {
  51. $A(".w-spinner").hide();
  52. }
  53. //
  54. if (typeof completeCall == "function") {
  55. completeCall();
  56. }
  57. };
  58. //
  59. let callback = params.success;
  60. params.success = (data, status, xhr) => {
  61. if (typeof data === 'object') {
  62. if (data.ret === -1 && params.checkRole !== false) {
  63. //身份丢失
  64. $A.app.$Modal.error({
  65. title: '温馨提示',
  66. content: data.msg,
  67. onOk: () => {
  68. $A.userLogout();
  69. }
  70. });
  71. return;
  72. }
  73. if (data.ret === -2 && params.role !== false) {
  74. //没有权限
  75. $A.app.$Modal.error({
  76. title: '权限不足',
  77. content: data.msg ? data.msg : "你没有相关的权限查看或编辑!"
  78. });
  79. }
  80. }
  81. if (typeof callback === "function") {
  82. callback(data, status, xhr);
  83. }
  84. };
  85. //
  86. $A.ajax(params);
  87. },
  88. aAjaxLoad: 0,
  89. /**
  90. * 编辑器参数配置
  91. * @returns {{modules: {toolbar: *[]}}}
  92. */
  93. editorOption() {
  94. return {
  95. modules: {
  96. toolbar: [
  97. ['bold', 'italic'],
  98. [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  99. [{ 'size': ['small', false, 'large', 'huge'] }],
  100. [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
  101. [{ 'color': [] }, { 'background': [] }],
  102. [{ 'align': [] }]
  103. ]
  104. }
  105. };
  106. },
  107. /**
  108. * 获取token
  109. * @returns {boolean}
  110. */
  111. getToken() {
  112. let token = $A.token();
  113. return $A.count(token) < 10 ? false : token;
  114. },
  115. /**
  116. * 设置token
  117. * @param token
  118. */
  119. setToken(token) {
  120. $A.token(token);
  121. },
  122. /**
  123. * 获取会员昵称
  124. * @returns string
  125. */
  126. getUserName() {
  127. if ($A.getToken() === false) {
  128. return "";
  129. }
  130. let userInfo = $A.getUserInfo();
  131. return $A.ishave(userInfo.username) ? userInfo.username : '';
  132. },
  133. /**
  134. * 获取用户信息(并保存)
  135. * @param callback 网络请求获取到用户信息回调(监听用户信息发生变化)
  136. * @param continueListenerName 持续监听标识(字符串或boolean,true:自动生成监听标识,false:自动生成监听标识但首次不请求网络)
  137. * @returns Object
  138. */
  139. getUserInfo(callback, continueListenerName) {
  140. if (typeof callback === 'function' || (typeof callback === "boolean" && callback === true)) {
  141. if (typeof continueListenerName === "boolean") {
  142. if (continueListenerName === true) {
  143. continueListenerName = "auto-" + $A.randomString(6);
  144. } else {
  145. $A.setOnUserInfoListener("auto-" + $A.randomString(6), callback);
  146. return $A.jsonParse($A.storage("userInfo"));
  147. }
  148. }
  149. //
  150. $A.apiAjax({
  151. url: 'users/info',
  152. error: () => {
  153. $A.userLogout();
  154. },
  155. success: (res) => {
  156. if (res.ret === 1) {
  157. $A.storage("userInfo", res.data);
  158. $A.setToken(res.data.token);
  159. $A.triggerUserInfoListener(res.data);
  160. typeof callback === "function" && callback(res.data, $A.getToken() !== false);
  161. }
  162. },
  163. afterComplete: () => {
  164. if (typeof continueListenerName == "string" && continueListenerName) {
  165. $A.setOnUserInfoListener(continueListenerName, callback);
  166. }
  167. },
  168. });
  169. }
  170. return $A.jsonParse($A.storage("userInfo"));
  171. },
  172. /**
  173. * 根据用户名获取用户基本信息
  174. * @param username
  175. * @param callback
  176. * @param cacheTime
  177. */
  178. getUserBasic(username, callback, cacheTime = 300) {
  179. if (typeof callback !== "function") {
  180. return;
  181. }
  182. if (!username) {
  183. callback({}, false);
  184. return;
  185. }
  186. //
  187. let keyName = '__userBasic:' + username.substring(0, 1) + '__';
  188. let localData = $A.jsonParse(window.localStorage[keyName]);
  189. if ($A.getObject(localData, username + '.success') === true) {
  190. callback(localData[username].data, true);
  191. if (localData[username].update + cacheTime > Math.round(new Date().getTime() / 1000)) {
  192. return;
  193. }
  194. }
  195. //
  196. $A.__userBasicObject.push({
  197. username: username,
  198. callback: callback
  199. });
  200. //
  201. $A.__userBasicTimeout++;
  202. let timeout = $A.__userBasicTimeout;
  203. setTimeout(() => {
  204. timeout === $A.__userBasicTimeout && $A.__userBasicEvent();
  205. }, 100);
  206. },
  207. __userBasicEvent() {
  208. if ($A.__userBasicLoading === true) {
  209. return;
  210. }
  211. $A.__userBasicLoading = true;
  212. //
  213. let userArray = [];
  214. $A.__userBasicObject.some((item) => {
  215. userArray.push(item.username);
  216. if (userArray.length >= 30) {
  217. return true;
  218. }
  219. });
  220. //
  221. $A.apiAjax({
  222. url: 'users/basic',
  223. data: {
  224. username: $A.jsonStringify(userArray),
  225. },
  226. error: () => {
  227. userArray.forEach((username) => {
  228. let tmpLists = $A.__userBasicObject.filter((item) => { return item.username == username });
  229. tmpLists.forEach((item) => {
  230. if (typeof item.callback === "function") {
  231. item.callback({}, false);
  232. item.callback = null;
  233. }
  234. });
  235. });
  236. //
  237. $A.__userBasicLoading = false;
  238. $A.__userBasicObject = $A.__userBasicObject.filter((item) => { return typeof item.callback === "function"});
  239. if ($A.__userBasicObject.length > 0) {
  240. $A.__userBasicEvent();
  241. }
  242. },
  243. success: (res) => {
  244. if (res.ret === 1) {
  245. res.data.forEach((data) => {
  246. let keyName = '__userBasic:' + data.username.substring(0, 1) + '__';
  247. let localData = $A.jsonParse(window.localStorage[keyName]);
  248. localData[data.username] = {
  249. success: true,
  250. update: Math.round(new Date().getTime() / 1000),
  251. data: data
  252. };
  253. window.localStorage[keyName] = $A.jsonStringify(localData);
  254. });
  255. }
  256. userArray.forEach((username) => {
  257. let tmpLists = $A.__userBasicObject.filter((item) => { return item.username == username });
  258. tmpLists.forEach((item) => {
  259. if (typeof item.callback === "function") {
  260. let info = res.data.filter((data) => { return data.username == username });
  261. if (info.length === 0) {
  262. item.callback({}, false);
  263. } else {
  264. item.callback(info[0], true);
  265. }
  266. item.callback = null;
  267. }
  268. });
  269. });
  270. //
  271. $A.__userBasicLoading = false;
  272. $A.__userBasicObject = $A.__userBasicObject.filter((item) => { return typeof item.callback === "function"});
  273. if ($A.__userBasicObject.length > 0) {
  274. $A.__userBasicEvent();
  275. }
  276. }
  277. });
  278. },
  279. __userBasicTimeout: 0,
  280. __userBasicLoading: false,
  281. __userBasicObject: [],
  282. /**
  283. * 打开登录页面
  284. */
  285. userLogout() {
  286. $A.token("");
  287. $A.storage("userInfo", {});
  288. $A.triggerUserInfoListener({});
  289. if (typeof $A.app === "object") {
  290. $A.app.goForward({path: '/', query:{from:encodeURIComponent(window.location.href)}}, true);
  291. } else {
  292. window.location.replace($A.webUrl() + '?from=' + encodeURIComponent(window.location.href));
  293. }
  294. },
  295. /**
  296. * 权限是否通过
  297. * @param role
  298. * @returns {boolean}
  299. */
  300. identity(role) {
  301. let userInfo = $A.getUserInfo();
  302. return $A.identityRaw(role, userInfo.identity);
  303. },
  304. /**
  305. * 权限是否通过
  306. * @param role
  307. * @returns {boolean}
  308. */
  309. identityRaw(role, identity) {
  310. let isRole = false;
  311. $A.each(identity, (index, res) => {
  312. if (res === role) {
  313. isRole = true;
  314. }
  315. });
  316. return isRole;
  317. },
  318. /**
  319. * 监听用户信息发生变化
  320. * @param listenerName 监听标识
  321. * @param callback 监听回调
  322. */
  323. setOnUserInfoListener(listenerName, callback) {
  324. if (typeof listenerName != "string") {
  325. return;
  326. }
  327. if (typeof callback === "function") {
  328. $A.__userInfoListenerObject[listenerName] = {
  329. callback: callback,
  330. }
  331. }
  332. },
  333. triggerUserInfoListener(userInfo) {
  334. let key, item;
  335. for (key in $A.__userInfoListenerObject) {
  336. if (!$A.__userInfoListenerObject.hasOwnProperty(key)) continue;
  337. item = $A.__userInfoListenerObject[key];
  338. if (typeof item.callback === "function") {
  339. item.callback(userInfo, $A.getToken() !== false);
  340. }
  341. }
  342. },
  343. __userInfoListenerObject: {},
  344. /**
  345. * 监听任务发生变化
  346. * @param listenerName 监听标识
  347. * @param callback 监听回调
  348. * @param callSpecial 是否监听几种特殊情况
  349. */
  350. setOnTaskInfoListener(listenerName, callback, callSpecial) {
  351. if (typeof listenerName != "string") {
  352. return;
  353. }
  354. if (typeof callback === "function") {
  355. $A.__taskInfoListenerObject[listenerName] = {
  356. special: callSpecial === true,
  357. callback: callback,
  358. }
  359. }
  360. },
  361. triggerTaskInfoListener(act, taskDetail, sendToWS = true) {
  362. let key, item;
  363. for (key in $A.__taskInfoListenerObject) {
  364. if (!$A.__taskInfoListenerObject.hasOwnProperty(key)) continue;
  365. item = $A.__taskInfoListenerObject[key];
  366. if (typeof item.callback === "function") {
  367. if (['deleteproject', 'deletelabel', 'leveltask'].indexOf(act) === -1 || item.special === true) {
  368. if (typeof taskDetail.__modifyUsername === "undefined") {
  369. taskDetail.__modifyUsername = $A.getUserName();
  370. }
  371. item.callback(act, taskDetail);
  372. }
  373. }
  374. }
  375. if (sendToWS === true) {
  376. $A.WSOB.sendTo('team', {
  377. type: "taskA",
  378. act: act,
  379. taskDetail: taskDetail
  380. });
  381. }
  382. },
  383. __taskInfoListenerObject: {},
  384. /**
  385. * 获取待推送的日志并推送
  386. * @param taskid
  387. */
  388. triggerTaskInfoChange(taskid) {
  389. $A.apiAjax({
  390. url: 'project/task/pushlog',
  391. data: {
  392. taskid: taskid,
  393. pagesize: 20
  394. },
  395. success: (res) => {
  396. if (res.ret === 1) {
  397. res.data.lists.forEach((item) => {
  398. let msgData = {
  399. type: 'taskB',
  400. username: item.username,
  401. userimg: item.userimg,
  402. indate: item.indate,
  403. text: item.detail,
  404. other: item.other
  405. };
  406. res.data.follower.forEach((username) => {
  407. if (username != msgData.username && username != $A.getUserName()) {
  408. $A.WSOB.sendTo('user', username, msgData, 'special');
  409. }
  410. });
  411. });
  412. }
  413. }
  414. });
  415. }
  416. });
  417. /**
  418. * =============================================================================
  419. * ***************************** websocket assist ****************************
  420. * =============================================================================
  421. */
  422. $.extend({
  423. /**
  424. * @param config {username, url, token, channel, logCallback}
  425. */
  426. WTWS: function (config) {
  427. this.__instance = null;
  428. this.__connected = false;
  429. this.__callbackid = {};
  430. this.__openNum = 0;
  431. this.__autoNum = 0;
  432. this.__autoLine = function (timeout) {
  433. var tempNum = this.__autoNum;
  434. var thas = this;
  435. setTimeout(function () {
  436. if (tempNum === thas.__autoNum) {
  437. thas.__autoNum++
  438. if (!thas.__config.token) {
  439. thas.__log("[WS] No token");
  440. thas.__autoLine(timeout + 5);
  441. } else {
  442. thas.sendTo('refresh', function (res) {
  443. thas.__log("[WS] Connection " + (res.status ? 'success' : 'error'));
  444. thas.__autoLine(timeout + 5);
  445. });
  446. }
  447. }
  448. }, Math.min(timeout, 30) * 1000);
  449. }
  450. this.__log = function (text, event) {
  451. typeof this.__config.logCallback === "function" && this.__config.logCallback(text, event);
  452. }
  453. this.__lExists = function (string, find, lower) {
  454. string += "";
  455. find += "";
  456. if (lower !== true) {
  457. string = string.toLowerCase();
  458. find = find.toLowerCase();
  459. }
  460. return (string.substring(0, find.length) === find);
  461. }
  462. this.__rNum = function (str, fixed) {
  463. var _s = Number(str);
  464. if (_s + "" === "NaN") {
  465. _s = 0;
  466. }
  467. if (/^[0-9]*[1-9][0-9]*$/.test(fixed)) {
  468. _s = _s.toFixed(fixed);
  469. var rs = _s.indexOf('.');
  470. if (rs < 0) {
  471. _s += ".";
  472. for (var i = 0; i < fixed; i++) {
  473. _s += "0";
  474. }
  475. }
  476. }
  477. return _s;
  478. }
  479. this.__jParse = function (str, defaultVal) {
  480. if (str === null) {
  481. return defaultVal ? defaultVal : {};
  482. }
  483. if (typeof str === "object") {
  484. return str;
  485. }
  486. try {
  487. return JSON.parse(str);
  488. } catch (e) {
  489. return defaultVal ? defaultVal : {};
  490. }
  491. }
  492. this.__randString = function (len) {
  493. len = len || 32;
  494. var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678oOLl9gqVvUuI1';
  495. var maxPos = $chars.length;
  496. var pwd = '';
  497. for (var i = 0; i < len; i++) {
  498. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  499. }
  500. return pwd;
  501. }
  502. this.__urlParams = function(url, params) {
  503. if (typeof params === "object" && params !== null) {
  504. url+= "";
  505. url+= url.indexOf("?") === -1 ? '?' : '';
  506. for (var key in params) {
  507. if (!params.hasOwnProperty(key)) {
  508. continue;
  509. }
  510. url+= '&' + key + '=' + params[key];
  511. }
  512. }
  513. return url.replace("?&", "?");
  514. }
  515. this.__isArr = function (obj){
  516. return Object.prototype.toString.call(obj)=='[object Array]';
  517. }
  518. /**
  519. * 设置参数
  520. * @param config
  521. */
  522. this.config = function (config) {
  523. if (typeof config !== "object" || config === null) {
  524. config = {};
  525. }
  526. config.username = config.username || '';
  527. config.url = config.url || '';
  528. config.token = config.token || '';
  529. config.channel = config.channel || '';
  530. config.logCallback = config.logCallback || null;
  531. this.__config = config;
  532. return this;
  533. }
  534. /**
  535. * 连接
  536. * @param force
  537. */
  538. this.connection = function (force) {
  539. if (!this.__lExists(this.__config.url, "ws://") && !this.__lExists(this.__config.url, "wss://")) {
  540. this.__log("[WS] No connection address");
  541. return this;
  542. }
  543. if (!this.__config.token) {
  544. this.__log("[WS] No connected token");
  545. return this;
  546. }
  547. if (this.__instance !== null && force !== true) {
  548. this.__log("[WS] Connection exists");
  549. return this;
  550. }
  551. var thas = this;
  552. // 初始化客户端套接字并建立连接
  553. this.__instance = new WebSocket(this.__urlParams(this.__config.url, {
  554. token: this.__config.token,
  555. channel: this.__config.channel
  556. }));
  557. // 连接建立时触发
  558. this.__instance.onopen = function (event) {
  559. thas.__log("[WS] Connection opened", event);
  560. }
  561. // 接收到服务端推送时执行
  562. this.__instance.onmessage = function (event) {
  563. var msgDetail = thas.__jParse(event.data);
  564. if (msgDetail.messageType === 'open') {
  565. thas.__log("[WS] Connection connected");
  566. msgDetail.openNum = thas.__openNum;
  567. msgDetail.config = thas.__config;
  568. thas.__openNum++;
  569. thas.__connected = true;
  570. thas.__autoLine(30);
  571. } else if (msgDetail.messageType === 'back') {
  572. typeof thas.__callbackid[msgDetail.messageId] === "function" && thas.__callbackid[msgDetail.messageId](msgDetail.body);
  573. delete thas.__callbackid[msgDetail.messageId];
  574. return;
  575. }
  576. if (thas.__rNum(msgDetail.contentId) > 0) {
  577. thas.sendTo('roger', msgDetail.contentId);
  578. }
  579. thas.triggerMsgListener(msgDetail);
  580. };
  581. // 连接关闭时触发
  582. this.__instance.onclose = function (event) {
  583. thas.__log("[WS] Connection closed", event);
  584. thas.__connected = false;
  585. thas.__instance = null;
  586. thas.__autoLine(5);
  587. }
  588. // 连接出错
  589. this.__instance.onerror = function (event) {
  590. thas.__log("[WS] Connection error", event);
  591. thas.__connected = false;
  592. thas.__instance = null;
  593. thas.__autoLine(5);
  594. }
  595. return this;
  596. }
  597. /**
  598. * 添加消息监听
  599. * @param listenerName
  600. * @param listenerType
  601. * @param callback
  602. */
  603. this.setOnMsgListener = function (listenerName, listenerType, callback) {
  604. if (typeof listenerName != "string") {
  605. return this;
  606. }
  607. if (typeof listenerType === "function") {
  608. callback = listenerType;
  609. listenerType = [];
  610. }
  611. if (!this.__isArr(listenerType)) {
  612. listenerType = [listenerType];
  613. }
  614. if (typeof callback === "function") {
  615. this.__msgListenerObject[listenerName] = {
  616. callback: callback,
  617. listenerType: listenerType,
  618. }
  619. }
  620. return this;
  621. }
  622. this.triggerMsgListener = function (msgDetail) {
  623. var key, item;
  624. for (key in this.__msgListenerObject) {
  625. if (!this.__msgListenerObject.hasOwnProperty(key)) {
  626. continue;
  627. }
  628. item = this.__msgListenerObject[key];
  629. if (item.listenerType.length > 0 && item.listenerType.indexOf(msgDetail.messageType) === -1) {
  630. continue;
  631. }
  632. if (typeof item.callback === "function") {
  633. item.callback(msgDetail);
  634. }
  635. }
  636. }
  637. this.__msgListenerObject = {}
  638. /**
  639. * 添加特殊监听
  640. * @param listenerName
  641. * @param callback
  642. */
  643. this.setOnSpecialListener = function (listenerName, callback) {
  644. if (typeof listenerName != "string") {
  645. return this;
  646. }
  647. if (typeof callback === "function") {
  648. this.__specialListenerObject[listenerName] = {
  649. callback: callback,
  650. }
  651. }
  652. return this;
  653. }
  654. this.triggerSpecialListener = function (simpleMsg) {
  655. var key, item;
  656. for (key in this.__specialListenerObject) {
  657. if (!this.__specialListenerObject.hasOwnProperty(key)) {
  658. continue;
  659. }
  660. item = this.__specialListenerObject[key];
  661. if (typeof item.callback === "function") {
  662. item.callback(simpleMsg);
  663. }
  664. }
  665. }
  666. this.__specialListenerObject = {}
  667. /**
  668. * 发送消息
  669. * @param messageType 会话类型
  670. * - refresh: 刷新
  671. * - unread: 未读信息总数量
  672. * - read: 已读会员信息
  673. * - roger: 收到信息回执
  674. * - user: 发送消息,指定target
  675. * - info: 发送消息(不保存),指定target
  676. * - team: 团队会员
  677. * - docs: 知识库
  678. * @param target 发送目标
  679. * @param body 发送内容(对象或数组)
  680. * @param callback 发送回调
  681. * @param againNum
  682. */
  683. this.sendTo = function (messageType, target, body, callback, againNum = 0) {
  684. if (typeof target === "object" && typeof body === "undefined") {
  685. body = target;
  686. target = null;
  687. }
  688. if (typeof target === "function") {
  689. body = target;
  690. target = null;
  691. }
  692. if (typeof body === "function") {
  693. callback = body;
  694. body = null;
  695. }
  696. if (body === null || typeof body !== "object") {
  697. body = {};
  698. }
  699. //
  700. var thas = this;
  701. if (this.__instance === null || this.__connected === false) {
  702. if (againNum < 10 && messageType != 'team') {
  703. setTimeout(function () {
  704. thas.sendTo(messageType, target, body, callback, thas.__rNum(againNum) + 1)
  705. }, 600);
  706. if (againNum === 0) {
  707. this.connection();
  708. }
  709. } else {
  710. if (this.__instance === null) {
  711. this.__log("[WS] Service not connected");
  712. typeof callback === "function" && callback({status: 0, message: '服务未连接'});
  713. } else {
  714. this.__log("[WS] Failed connection");
  715. typeof callback === "function" && callback({status: 0, message: '未连接成功'});
  716. }
  717. }
  718. return this;
  719. }
  720. if (['refresh', 'unread', 'read', 'roger', 'user', 'info', 'team', 'docs'].indexOf(messageType) === -1) {
  721. this.__log("[WS] Wrong message messageType: " + messageType);
  722. typeof callback === "function" && callback({status: 0, message: '错误的消息类型: ' + messageType});
  723. return this;
  724. }
  725. //
  726. var contentId = 0;
  727. if (messageType === 'roger') {
  728. contentId = target;
  729. target = null;
  730. }
  731. var messageId = '';
  732. if (typeof callback === "string" && callback === 'special') {
  733. callback = function (res) {
  734. res.status === 1 && thas.triggerSpecialListener({
  735. target: target,
  736. body: body,
  737. });
  738. }
  739. }
  740. if (typeof callback === "function") {
  741. messageId = this.__randString(16);
  742. this.__callbackid[messageId] = callback;
  743. }
  744. this.__instance.send(JSON.stringify({
  745. messageType: messageType,
  746. messageId: messageId,
  747. contentId: contentId,
  748. channel: this.__config.channel,
  749. username: this.__config.username,
  750. target: target,
  751. body: body,
  752. time: Math.round(new Date().getTime() / 1000),
  753. }));
  754. return this;
  755. }
  756. /**
  757. * 关闭连接
  758. */
  759. this.close = function () {
  760. if (this.__instance === null) {
  761. this.__log("[WS] Service not connected");
  762. return this;
  763. }
  764. if (this.__connected === false) {
  765. this.__log("[WS] Failed connection");
  766. return this;
  767. }
  768. this.__instance.close();
  769. return this;
  770. }
  771. return this.config(config);
  772. },
  773. WSOB: {
  774. instance: null,
  775. isClose: false,
  776. /**
  777. * 初始化
  778. */
  779. initialize() {
  780. let url = $A.getObject(window.webSocketConfig, 'URL');
  781. if (!url) {
  782. url = window.location.origin;
  783. url = url.replace("https://", "wss://");
  784. url = url.replace("http://", "ws://");
  785. url+= "/ws";
  786. }
  787. let config = {
  788. username: $A.getUserName(),
  789. url: url,
  790. token: $A.getToken(),
  791. channel: 'web'
  792. };
  793. if (this.instance === null) {
  794. this.instance = new $A.WTWS(config);
  795. this.instance.connection()
  796. } else if (this.isClose) {
  797. this.isClose = false
  798. this.instance.config(config);
  799. this.instance.connection();
  800. }
  801. },
  802. /**
  803. * 主动连接
  804. */
  805. connection() {
  806. this.initialize();
  807. this.instance.connection();
  808. },
  809. /**
  810. * 监听消息
  811. * @param listenerName
  812. * @param listenerType
  813. * @param callback
  814. */
  815. setOnMsgListener(listenerName, listenerType, callback) {
  816. this.initialize();
  817. this.instance.setOnMsgListener(listenerName, listenerType, callback);
  818. },
  819. /**
  820. * 添加特殊监听
  821. * @param listenerName
  822. * @param callback
  823. */
  824. setOnSpecialListener(listenerName, callback) {
  825. this.initialize();
  826. this.instance.setOnSpecialListener(listenerName, callback);
  827. },
  828. /**
  829. * 发送消息
  830. * @param messageType
  831. * @param target
  832. * @param body
  833. * @param callback
  834. */
  835. sendTo(messageType, target, body, callback) {
  836. this.initialize();
  837. this.instance.sendTo(messageType, target, body, callback);
  838. },
  839. /**
  840. * 关闭连接
  841. */
  842. close() {
  843. if (this.instance === null) {
  844. return;
  845. }
  846. this.isClose = true
  847. this.instance.config(null).close();
  848. },
  849. /**
  850. * 获取消息描述
  851. * @param content
  852. * @returns {string}
  853. */
  854. getMsgDesc(content) {
  855. let desc;
  856. switch (content.type) {
  857. case 'text':
  858. desc = content.text;
  859. break;
  860. case 'image':
  861. desc = $A.app.$L('[图片]');
  862. break;
  863. case 'taskB':
  864. desc = content.text + " " + $A.app.$L("[来自关注任务]");
  865. break;
  866. case 'report':
  867. desc = content.text + " " + $A.app.$L("[来自工作报告]");
  868. break;
  869. case 'video':
  870. desc = $A.app.$L('[视频通话]');
  871. break;
  872. case 'voice':
  873. desc = $A.app.$L('[语音通话]');
  874. break;
  875. default:
  876. desc = $A.app.$L('[未知类型]');
  877. break;
  878. }
  879. return desc;
  880. }
  881. }
  882. });
  883. window.$A = $;
  884. })(window);