main.js 35 KB

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