main.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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. * =============================================================================
  425. * ***************************** websocket assist ****************************
  426. * =============================================================================
  427. */
  428. $.extend({
  429. /**
  430. * @param config {username, url, token, channel, logCallback}
  431. */
  432. WTWS: function (config) {
  433. this.__instance = null;
  434. this.__connected = false;
  435. this.__callbackid = {};
  436. this.__openNum = 0;
  437. this.__autoNum = 0;
  438. this.__autoLine = function (timeout) {
  439. var tempNum = this.__autoNum;
  440. var thas = this;
  441. setTimeout(function () {
  442. if (tempNum === thas.__autoNum) {
  443. thas.__autoNum++
  444. if (!thas.__config.token) {
  445. thas.__log("[WS] No token");
  446. thas.__autoLine(timeout + 5);
  447. } else {
  448. thas.sendTo('refresh', function (res) {
  449. thas.__log("[WS] Connection " + (res.status ? 'success' : 'error'));
  450. thas.__autoLine(timeout + 5);
  451. });
  452. }
  453. }
  454. }, Math.min(timeout, 30) * 1000);
  455. }
  456. this.__log = function (text, event) {
  457. typeof this.__config.logCallback === "function" && this.__config.logCallback(text, event);
  458. }
  459. this.__lExists = function (string, find, lower) {
  460. string += "";
  461. find += "";
  462. if (lower !== true) {
  463. string = string.toLowerCase();
  464. find = find.toLowerCase();
  465. }
  466. return (string.substring(0, find.length) === find);
  467. }
  468. this.__rNum = function (str, fixed) {
  469. var _s = Number(str);
  470. if (_s + "" === "NaN") {
  471. _s = 0;
  472. }
  473. if (/^[0-9]*[1-9][0-9]*$/.test(fixed)) {
  474. _s = _s.toFixed(fixed);
  475. var rs = _s.indexOf('.');
  476. if (rs < 0) {
  477. _s += ".";
  478. for (var i = 0; i < fixed; i++) {
  479. _s += "0";
  480. }
  481. }
  482. }
  483. return _s;
  484. }
  485. this.__jParse = function (str, defaultVal) {
  486. if (str === null) {
  487. return defaultVal ? defaultVal : {};
  488. }
  489. if (typeof str === "object") {
  490. return str;
  491. }
  492. try {
  493. return JSON.parse(str);
  494. } catch (e) {
  495. return defaultVal ? defaultVal : {};
  496. }
  497. }
  498. this.__randString = function (len) {
  499. len = len || 32;
  500. var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678oOLl9gqVvUuI1';
  501. var maxPos = $chars.length;
  502. var pwd = '';
  503. for (var i = 0; i < len; i++) {
  504. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  505. }
  506. return pwd;
  507. }
  508. this.__urlParams = function(url, params) {
  509. if (typeof params === "object" && params !== null) {
  510. url+= "";
  511. url+= url.indexOf("?") === -1 ? '?' : '';
  512. for (var key in params) {
  513. if (!params.hasOwnProperty(key)) {
  514. continue;
  515. }
  516. url+= '&' + key + '=' + params[key];
  517. }
  518. }
  519. return url.replace("?&", "?");
  520. }
  521. this.__isArr = function (obj){
  522. return Object.prototype.toString.call(obj)=='[object Array]';
  523. }
  524. /**
  525. * 设置参数
  526. * @param config
  527. */
  528. this.config = function (config) {
  529. if (typeof config !== "object" || config === null) {
  530. config = {};
  531. }
  532. config.username = config.username || '';
  533. config.url = config.url || '';
  534. config.token = config.token || '';
  535. config.channel = config.channel || '';
  536. config.logCallback = config.logCallback || null;
  537. this.__config = config;
  538. return this;
  539. }
  540. /**
  541. * 连接
  542. * @param force
  543. */
  544. this.connection = function (force) {
  545. if (!this.__lExists(this.__config.url, "ws://") && !this.__lExists(this.__config.url, "wss://")) {
  546. this.__log("[WS] No connection address");
  547. return this;
  548. }
  549. if (!this.__config.token) {
  550. this.__log("[WS] No connected token");
  551. return this;
  552. }
  553. if (this.__instance !== null && force !== true) {
  554. this.__log("[WS] Connection exists");
  555. return this;
  556. }
  557. var thas = this;
  558. // 初始化客户端套接字并建立连接
  559. this.__instance = new WebSocket(this.__urlParams(this.__config.url, {
  560. token: this.__config.token,
  561. channel: this.__config.channel
  562. }));
  563. // 连接建立时触发
  564. this.__instance.onopen = function (event) {
  565. thas.__log("[WS] Connection opened", event);
  566. }
  567. // 接收到服务端推送时执行
  568. this.__instance.onmessage = function (event) {
  569. var msgDetail = thas.__jParse(event.data);
  570. if (msgDetail.messageType === 'open') {
  571. thas.__log("[WS] Connection connected");
  572. msgDetail.openNum = thas.__openNum;
  573. msgDetail.config = thas.__config;
  574. thas.__openNum++;
  575. thas.__connected = true;
  576. thas.__autoLine(30);
  577. } else if (msgDetail.messageType === 'back') {
  578. typeof thas.__callbackid[msgDetail.messageId] === "function" && thas.__callbackid[msgDetail.messageId](msgDetail.body);
  579. delete thas.__callbackid[msgDetail.messageId];
  580. return;
  581. }
  582. if (thas.__rNum(msgDetail.contentId) > 0) {
  583. thas.sendTo('roger', msgDetail.contentId);
  584. }
  585. thas.triggerMsgListener(msgDetail);
  586. };
  587. // 连接关闭时触发
  588. this.__instance.onclose = function (event) {
  589. thas.__log("[WS] Connection closed", event);
  590. thas.__connected = false;
  591. thas.__instance = null;
  592. thas.__autoLine(5);
  593. }
  594. // 连接出错
  595. this.__instance.onerror = function (event) {
  596. thas.__log("[WS] Connection error", event);
  597. thas.__connected = false;
  598. thas.__instance = null;
  599. thas.__autoLine(5);
  600. }
  601. return this;
  602. }
  603. /**
  604. * 添加消息监听
  605. * @param listenerName
  606. * @param listenerType
  607. * @param callback
  608. */
  609. this.setOnMsgListener = function (listenerName, listenerType, callback) {
  610. if (typeof listenerName != "string") {
  611. return this;
  612. }
  613. if (typeof listenerType === "function") {
  614. callback = listenerType;
  615. listenerType = [];
  616. }
  617. if (!this.__isArr(listenerType)) {
  618. listenerType = [listenerType];
  619. }
  620. if (typeof callback === "function") {
  621. this.__msgListenerObject[listenerName] = {
  622. callback: callback,
  623. listenerType: listenerType,
  624. }
  625. }
  626. return this;
  627. }
  628. this.triggerMsgListener = function (msgDetail) {
  629. var key, item;
  630. for (key in this.__msgListenerObject) {
  631. if (!this.__msgListenerObject.hasOwnProperty(key)) {
  632. continue;
  633. }
  634. item = this.__msgListenerObject[key];
  635. if (item.listenerType.length > 0 && item.listenerType.indexOf(msgDetail.messageType) === -1) {
  636. continue;
  637. }
  638. if (typeof item.callback === "function") {
  639. item.callback(msgDetail);
  640. }
  641. }
  642. }
  643. this.__msgListenerObject = {}
  644. /**
  645. * 添加特殊监听
  646. * @param listenerName
  647. * @param callback
  648. */
  649. this.setOnSpecialListener = function (listenerName, callback) {
  650. if (typeof listenerName != "string") {
  651. return this;
  652. }
  653. if (typeof callback === "function") {
  654. this.__specialListenerObject[listenerName] = {
  655. callback: callback,
  656. }
  657. }
  658. return this;
  659. }
  660. this.triggerSpecialListener = function (simpleMsg) {
  661. var key, item;
  662. for (key in this.__specialListenerObject) {
  663. if (!this.__specialListenerObject.hasOwnProperty(key)) {
  664. continue;
  665. }
  666. item = this.__specialListenerObject[key];
  667. if (typeof item.callback === "function") {
  668. item.callback(simpleMsg);
  669. }
  670. }
  671. }
  672. this.__specialListenerObject = {}
  673. /**
  674. * 发送消息
  675. * @param messageType 会话类型
  676. * - refresh: 刷新
  677. * - unread: 未读信息总数量
  678. * - read: 已读会员信息
  679. * - roger: 收到信息回执
  680. * - user: 发送消息,指定target
  681. * - info: 发送消息(不保存),指定target
  682. * - team: 团队会员
  683. * - docs: 知识库
  684. * @param target 发送目标
  685. * @param body 发送内容(对象或数组)
  686. * @param callback 发送回调
  687. * @param againNum
  688. */
  689. this.sendTo = function (messageType, target, body, callback, againNum = 0) {
  690. if (typeof target === "object" && typeof body === "undefined") {
  691. body = target;
  692. target = null;
  693. }
  694. if (typeof target === "function") {
  695. body = target;
  696. target = null;
  697. }
  698. if (typeof body === "function") {
  699. callback = body;
  700. body = null;
  701. }
  702. if (body === null || typeof body !== "object") {
  703. body = {};
  704. }
  705. //
  706. var thas = this;
  707. if (this.__instance === null || this.__connected === false) {
  708. if (againNum < 10 && messageType != 'team') {
  709. setTimeout(function () {
  710. thas.sendTo(messageType, target, body, callback, thas.__rNum(againNum) + 1)
  711. }, 600);
  712. if (againNum === 0) {
  713. this.connection();
  714. }
  715. } else {
  716. if (this.__instance === null) {
  717. this.__log("[WS] Service not connected");
  718. typeof callback === "function" && callback({status: 0, message: '服务未连接'});
  719. } else {
  720. this.__log("[WS] Failed connection");
  721. typeof callback === "function" && callback({status: 0, message: '未连接成功'});
  722. }
  723. }
  724. return this;
  725. }
  726. if (['refresh', 'unread', 'read', 'roger', 'user', 'info', 'team', 'docs'].indexOf(messageType) === -1) {
  727. this.__log("[WS] Wrong message messageType: " + messageType);
  728. typeof callback === "function" && callback({status: 0, message: '错误的消息类型: ' + messageType});
  729. return this;
  730. }
  731. //
  732. var contentId = 0;
  733. if (messageType === 'roger') {
  734. contentId = target;
  735. target = null;
  736. }
  737. var messageId = '';
  738. if (typeof callback === "string" && callback === 'special') {
  739. callback = function (res) {
  740. res.status === 1 && thas.triggerSpecialListener({
  741. target: target,
  742. body: body,
  743. });
  744. }
  745. }
  746. if (typeof callback === "function") {
  747. messageId = this.__randString(16);
  748. this.__callbackid[messageId] = callback;
  749. }
  750. this.__instance.send(JSON.stringify({
  751. messageType: messageType,
  752. messageId: messageId,
  753. contentId: contentId,
  754. channel: this.__config.channel,
  755. username: this.__config.username,
  756. target: target,
  757. body: body,
  758. time: Math.round(new Date().getTime() / 1000),
  759. }));
  760. return this;
  761. }
  762. /**
  763. * 关闭连接
  764. */
  765. this.close = function () {
  766. if (this.__instance === null) {
  767. this.__log("[WS] Service not connected");
  768. return this;
  769. }
  770. if (this.__connected === false) {
  771. this.__log("[WS] Failed connection");
  772. return this;
  773. }
  774. this.__instance.close();
  775. return this;
  776. }
  777. return this.config(config);
  778. },
  779. WSOB: {
  780. instance: null,
  781. isClose: false,
  782. /**
  783. * 初始化
  784. */
  785. initialize() {
  786. let url = $A.getObject(window.webSocketConfig, 'URL');
  787. if (!url) {
  788. url = window.location.origin;
  789. url = url.replace("https://", "wss://");
  790. url = url.replace("http://", "ws://");
  791. url+= "/ws";
  792. }
  793. let config = {
  794. username: $A.getUserName(),
  795. url: url,
  796. token: $A.getToken(),
  797. channel: 'web'
  798. };
  799. if (this.instance === null) {
  800. this.instance = new $A.WTWS(config);
  801. this.instance.connection()
  802. } else if (this.isClose) {
  803. this.isClose = false
  804. this.instance.config(config);
  805. this.instance.connection();
  806. }
  807. },
  808. /**
  809. * 主动连接
  810. */
  811. connection() {
  812. this.initialize();
  813. this.instance.connection();
  814. },
  815. /**
  816. * 监听消息
  817. * @param listenerName
  818. * @param listenerType
  819. * @param callback
  820. */
  821. setOnMsgListener(listenerName, listenerType, callback) {
  822. this.initialize();
  823. this.instance.setOnMsgListener(listenerName, listenerType, callback);
  824. },
  825. /**
  826. * 添加特殊监听
  827. * @param listenerName
  828. * @param callback
  829. */
  830. setOnSpecialListener(listenerName, callback) {
  831. this.initialize();
  832. this.instance.setOnSpecialListener(listenerName, callback);
  833. },
  834. /**
  835. * 发送消息
  836. * @param messageType
  837. * @param target
  838. * @param body
  839. * @param callback
  840. */
  841. sendTo(messageType, target, body, callback) {
  842. this.initialize();
  843. this.instance.sendTo(messageType, target, body, callback);
  844. },
  845. /**
  846. * 关闭连接
  847. */
  848. close() {
  849. if (this.instance === null) {
  850. return;
  851. }
  852. this.isClose = true
  853. this.instance.config(null).close();
  854. },
  855. /**
  856. * 获取消息描述
  857. * @param content
  858. * @returns {string}
  859. */
  860. getMsgDesc(content) {
  861. let desc;
  862. switch (content.type) {
  863. case 'text':
  864. desc = content.text;
  865. break;
  866. case 'image':
  867. desc = $A.app.$L('[图片]');
  868. break;
  869. case 'file':
  870. desc = $A.app.$L('[文件]');
  871. break;
  872. case 'taskB':
  873. desc = content.text + " " + $A.app.$L("[来自关注任务]");
  874. break;
  875. case 'report':
  876. desc = content.text + " " + $A.app.$L("[来自工作报告]");
  877. break;
  878. case 'video':
  879. desc = $A.app.$L('[视频通话]');
  880. break;
  881. case 'voice':
  882. desc = $A.app.$L('[语音通话]');
  883. break;
  884. default:
  885. desc = $A.app.$L('[未知类型]');
  886. break;
  887. }
  888. return desc;
  889. }
  890. }
  891. });
  892. window.$A = $;
  893. })(window);