main.js 34 KB

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