main.js 34 KB

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