main.js 35 KB

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