main.js 33 KB

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