main.js 35 KB

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