basic-service.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /**
  2. *
  3. * Basic
  4. * 所有页面的共用基础功能
  5. * // TODO: 文件名可能需要修改
  6. * // TODO: failing ES-Lint
  7. * // TODO: Automated Test
  8. *
  9. * dependency:
  10. * jQuery (ajax, selector)
  11. *
  12. * @ jason.lu
  13. * */
  14. import 'whatwg-fetch';
  15. var BasicFunction = new (function () {
  16. this.Queue = {
  17. THRESHOLD: 1000,
  18. IS_LOADED: false,
  19. nowuse: 0, SVR_URL: "/server/",
  20. TEST_URL: "smartAds/list",
  21. groupsCount: 0, groups: [],
  22. shouldStop: false,
  23. backup: ["/server/",
  24. "http://127.0.0.1:8866/server/",
  25. "http://south.niimei.com:8866/server/",
  26. "https://4.niimei.com/server/"],
  27. list: [], temporary: 0, errorCount: 0
  28. };
  29. this.Users = {list: []};
  30. this.Sectors = {list: []};
  31. this.AlertClosingTimeout = 0;
  32. this.loglog = function (a) {
  33. console.log(a);
  34. };
  35. this.logwarn = function (obj) {
  36. console.warn(obj);
  37. };
  38. this.logerror = function (obj) {
  39. console.warn(obj);
  40. };
  41. this.logtrace = function () {
  42. console.trace();
  43. };
  44. this.logverbose = function () {
  45. // Not Echoing
  46. };
  47. this.asserThat = function(cond, why) {
  48. console.assert(cond, why);
  49. };
  50. this.goajax = function (jqObject) {
  51. if(typeof jqObject.data !== "string"){
  52. if (typeof jqObject.data === "object" && jqObject.data.toString().indexOf("FormData") !== -1) {
  53. return fetch(jqObject.url, {
  54. method: 'POST',
  55. body: jqObject.data
  56. });
  57. }
  58. }
  59. return fetch(jqObject.url, {
  60. method: 'POST',
  61. headers: {
  62. 'Content-Type': 'application/json'
  63. },
  64. body: jqObject.data
  65. });
  66. };
  67. this.utils_get_param = function (name) {
  68. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  69. var r = window.location.search.substr(1).match(reg);
  70. if (r != null) return unescape(r[2]);
  71. return null;
  72. };
  73. this.reloadPage = function () {
  74. location.reload()
  75. };
  76. this.get_server_url = function () {
  77. // AJAX
  78. this.output = this.goajax({url: this.Queue.SVR_URL + this.Queue.TEST_URL, timeout: 1000})
  79. .then(this.checkStatus)
  80. .then(this.parseJson)
  81. .then(this.onReachServer)
  82. .catch(this.onCheckFail);
  83. // .then(BasicFunction.onCheckFail);
  84. };
  85. this.onReachServer = function () {
  86. BasicFunction.Queue.IS_LOADED = true;
  87. BasicFunction.logwarn("Using SERVER : ");
  88. BasicFunction.logwarn(BasicFunction.Queue.SVR_URL);
  89. setTimeout(BasicFunction.parse_queue, 50, BasicFunction);
  90. };
  91. this.onCheckFail = function (errmsg) {
  92. if (BasicFunction.Queue.nowuse === BasicFunction.Queue.backup.length - 1) {
  93. BasicFunction.logwarn("Backup Failed : " + BasicFunction.Queue.backup[BasicFunction.Queue.nowuse]);
  94. BasicFunction.logwarn(this);
  95. var out = "";
  96. BasicFunction.Queue.backup.forEach(function (val, index) {
  97. out += index + ":[" +val +"] \n";
  98. });
  99. BasicFunction.logerror("抱歉, 服务器连接失败! \n 请确认 "+ out +" 其中之一可用");
  100. } else {
  101. BasicFunction.loglog(errmsg);
  102. BasicFunction.Queue.nowuse++;
  103. BasicFunction.Queue.SVR_URL = BasicFunction.Queue.backup[BasicFunction.Queue.nowuse];
  104. // AJAX
  105. BasicFunction.goajax({url: BasicFunction.Queue.SVR_URL + BasicFunction.Queue.TEST_URL, timeout: 1000})
  106. .then(BasicFunction.checkStatus)
  107. .then(function (response) {return response.json();} )
  108. .then(BasicFunction.onReachServer)
  109. .catch(BasicFunction.onCheckFail);
  110. }
  111. };
  112. this.get_data = function (url, callback, data, onescope) {
  113. // console.log('calling get_data()');
  114. let jsonData = data;
  115. if(typeof data !== "string"){
  116. if(data.toString().indexOf("FormData") !== -1){
  117. jsonData = data;
  118. }else {
  119. jsonData = JSON.stringify(jsonData);
  120. }
  121. }
  122. BasicFunction.Queue.list.push({url: url, callback: callback, gid: -1, data: jsonData, scope: onescope});
  123. };
  124. this.new_data_group = function (groupName, callback) {
  125. let gid = -1;
  126. BasicFunction.Queue.groups.forEach(function (val) {
  127. if (val.groupName === groupName) {
  128. gid = val.gid;
  129. }
  130. });
  131. if (gid === -1) {
  132. gid = BasicFunction.Queue.groupsCount;
  133. BasicFunction.Queue.groupsCount++;
  134. BasicFunction.Queue.groups.push({
  135. gid: gid, groupName: groupName, callme: callback, counter: 0
  136. });
  137. }
  138. return gid;
  139. };
  140. this.group_get_data = function (groupName, url, callback) {
  141. let gid = -1;
  142. BasicFunction.Queue.groups.forEach(function (val) {
  143. if (val.groupName === groupName) {
  144. gid = val.gid;
  145. }
  146. });
  147. if (gid === -1) {
  148. BasicFunction.send_alert("Group 方法使用错误!!!")
  149. }
  150. BasicFunction.Queue.list.push({url: url, callback: callback, gid: gid});
  151. };
  152. this.parse_queue = function () {
  153. BasicFunction.logverbose("Queue Length : " + BasicFunction.Queue.list.length);
  154. if (BasicFunction.Queue.temporary > new Date().getTime()) {
  155. for (let i = 0; i < BasicFunction.Queue.list.length; i++) {
  156. BasicFunction.Queue.list.pop();
  157. }
  158. }
  159. BasicFunction.Queue.temporary = 0;
  160. if (BasicFunction.Queue.list.length > 0) {
  161. let one = BasicFunction.Queue.list.pop();
  162. if (one.gid === -1) {
  163. request_data(one.url, one.callback, one.data, one.scope);
  164. } else {
  165. g_request_data(one.url, one.callback, one.gid, one.data, one.scope);
  166. }
  167. }
  168. if (BasicFunction.Queue.shouldStop === false) {
  169. setTimeout(BasicFunction.parse_queue, 50);
  170. }
  171. };
  172. this.parseJSON = function(response) {
  173. return response.json();
  174. };
  175. this.checkStatus = function(response) {
  176. if (response.status >= 200 && response.status < 300) {
  177. return response;
  178. }
  179. const error = new Error(response.statusText);
  180. error.response = response;
  181. throw error;
  182. };
  183. function request_data(url, callback, data, scope) {
  184. var vurl = "";
  185. if(url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1){
  186. vurl = url;
  187. } else {
  188. if(url.length > 2 && url.substring(0,2) === "!!"){
  189. vurl = url.substring(2);
  190. } else {
  191. vurl = BasicFunction.Queue.SVR_URL + url;
  192. }
  193. }
  194. BasicFunction.goajax({
  195. url: vurl,
  196. apiName: url,
  197. data: data,
  198. scope: scope,
  199. sendTime: new Date()
  200. }).then(BasicFunction.checkStatus)
  201. .then(BasicFunction.parseJson)
  202. .then(function(response){return response.json()})
  203. .then(callback)
  204. .catch(BasicFunction.on_fail);
  205. }
  206. function g_request_data(url, callback, gid) {
  207. BasicFunction.goajax({
  208. url: BasicFunction.Queue.SVR_URL + url,
  209. apiName: url,
  210. sendTime: new Date(),
  211. gid: gid,
  212. callme: callback
  213. }).then(BasicFunction.checkStatus)
  214. .then(BasicFunction.parseJson)
  215. .then(function(response){return response.json()})
  216. .then(BasicFunction.onReqeustDataReceived)
  217. .then(callback)
  218. .catch(BasicFunction.on_fail);
  219. }
  220. this.on_gp_success = function(response) {
  221. let obj = response.json();
  222. return obj;
  223. };
  224. this.onReqeustDataReceived = function(responseJson) {
  225. console.warn(responseJson);
  226. let a = responseJson;
  227. if (!BasicFunction.check_if_authfail(a)) {
  228. const error = new Error(responseJson.statusText);
  229. error.response = responseJson;
  230. throw error;
  231. }
  232. if (!BasicFunction.check_if_success(a)) {
  233. const error = new Error(responseJson.statusText);
  234. error.response = responseJson;
  235. throw error;
  236. }
  237. return responseJson;
  238. // BasicFunction.setCookieWithTimeout("doibyUser", "", -10);
  239. // location.href = "sign-in1.html?from=entrance-5&msg=server-redirect-detected";
  240. // return;
  241. };
  242. this.check_if_authfail = function (errormsg) {
  243. BasicFunction.logerror(errormsg);
  244. let a = errormsg;
  245. if (a == null || typeof a !== "string") {
  246. return false;
  247. } else {
  248. if (a.indexOf("login?from=") > 0 || a.startsWith("<!DOCTYPE html>") || a.indexOf("<!-- SME::LOGINPAGE -->") > 0) {
  249. return true;
  250. }
  251. }
  252. return false;
  253. };
  254. this.check_if_success = function (response) {
  255. // this == BasicFunction
  256. BasicFunction.loglog("---------------Check-If-Success----------------");
  257. let a = response.json();
  258. let b = response.status;
  259. if (typeof a === "string") {
  260. try {
  261. a = JSON.parse(a);
  262. } catch (e) {
  263. BasicFunction.logwarn("=---------- 异常 -----------=");
  264. BasicFunction.logwarn(a);
  265. BasicFunction.logwarn("=----------------------------=");
  266. BasicFunction.send_alert("信息失败 : 1 : " + e);
  267. return;
  268. }
  269. } else if (typeof a === "undefined") {
  270. BasicFunction.logwarn("=---------- 异常 -----------=");
  271. BasicFunction.logwarn(a);
  272. BasicFunction.logwarn("=------------------------------=");
  273. BasicFunction.logwarn(b);
  274. BasicFunction.logwarn("=------------------------------=");
  275. BasicFunction.send_alert("信息失败 - 2 " );
  276. return;
  277. }
  278. if (a.ret === "10000") {
  279. return true;
  280. } else {
  281. BasicFunction.logtrace();
  282. BasicFunction.logerror(b);
  283. BasicFunction.logerror(JSON.stringify(a));
  284. BasicFunction.send_alert("查询失败 : 请参阅控制台输出! ");
  285. }
  286. return false;
  287. };
  288. this.on_fail = function (msg) {
  289. alert("网络可能不畅,您的礼物我们十分重视。为了给您更佳的体验,您可以微信搜索支持服务账号 lugt00, 专享人工匹配通道!");
  290. BasicFunction.Queue.errorCount += 1;
  291. if (BasicFunction.Queue.errorCount >= 10) {
  292. BasicFunction.Queue.errorCount = 0;
  293. BasicFunction.Queue.temporary = new Date().getTime() + 30 * 1000;
  294. BasicFunction.Queue.shouldStop = true;
  295. BasicFunction.logwarn("----- Too many failure, temporary stop HTTP ------");
  296. BasicFunction.send_alert("很抱歉,网络错误数量过多,暂时终止HTTP功能30s");
  297. }
  298. BasicFunction.send_alert(" 结果处理代码报错!请检查 。");
  299. BasicFunction.logwarn(msg);
  300. BasicFunction.logwarn("----- 结果处理报错 ---------");
  301. BasicFunction.logwarn(this);
  302. BasicFunction.logwarn("-----------msg-------------");
  303. BasicFunction.logwarn(JSON.stringify(msg));
  304. BasicFunction.logwarn("----------------------------");
  305. };
  306. this.first_parse = function (ajax, obj) {
  307. if (typeof obj === "string") {
  308. obj = JSON.parse(obj);
  309. }
  310. if (typeof obj !== "object") {
  311. BasicFunction.logwarn(ajax);
  312. throw "Error ! Parsing JSON failed ." + JSON.stringify(obj);
  313. }
  314. if (obj.ret === "10000") {
  315. return obj.model;
  316. } else {
  317. BasicFunction.logwarn(ajax);
  318. throw "Error ! Server returned error." + JSON.stringify(obj);
  319. }
  320. };
  321. this.send_alert = function (a, b) {
  322. if (BasicFunction.Queue.shouldStop) return;
  323. if (BasicFunction.AlertClosingTimeout > 0) {
  324. clearTimeout(BasicFunction.AlertClosingTimeout);
  325. }
  326. BasicFunction.logwarn(a);
  327. BasicFunction.logwarn(b);
  328. // alert(a +"\n"+ b);
  329. BasicFunction.AlertClosingTimeout = setTimeout(function () {
  330. //$("#mpAlert").hide();
  331. }, 10000);
  332. };
  333. this.getUserName = function (uid) {
  334. let uname = null;
  335. BasicFunction.Users.list.forEach(function (val, aid) {
  336. BasicFunction.loglog(aid);
  337. if (val.worker.staffId === uid) {
  338. uname = val.worker.staffName;
  339. }
  340. });
  341. if (uname == null) {
  342. if (uid !== 0) {
  343. BasicFunction.get_data("oaStaff/list?staffId=" + uid, BasicFunction.on_username_retn);
  344. return "[用户:" + uid + "]";
  345. } else return "[用户:" + uid + "]";
  346. } else {
  347. return uname;
  348. }
  349. };
  350. this.on_username_retn = function (obj) {
  351. let uid = this.url.substring(this.url.indexOf("staffId=") + 8);
  352. let ruid = parseInt(uid);
  353. let out = BasicFunction.first_parse(this, obj);
  354. if (out.list.length > 0) {
  355. BasicFunction.Users.list.push({
  356. uid: ruid, worker: out.list[0]
  357. });
  358. }
  359. };
  360. this.setCookieWithTimeout = function (name, value, liveMinutes) {
  361. if (liveMinutes === undefined || liveMinutes == null) {
  362. liveMinutes = 60 * 2;
  363. }
  364. if (typeof (liveMinutes) !== 'number') {
  365. liveMinutes = 60 * 2;//默认120分钟
  366. }
  367. let minutes = liveMinutes * 60 * 1000;
  368. let exp = new Date();
  369. exp.setTime(exp.getTime() + minutes + 8 * 3600 * 1000);
  370. //path=/表示全站有效,而不是当前页
  371. document.cookie = name + "=" + value + ";path=/;expires=" + exp.toUTCString();
  372. };
  373. this.setCookie = function (c_name, value, expiredays) {
  374. let exdate = new Date();
  375. exdate.setDate(exdate.getDate() + expiredays);
  376. document.cookie = c_name + "=" + escape(value) +
  377. ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
  378. };
  379. this.getCookie = function (c_name) {
  380. if (document.cookie.length > 0) {
  381. let c_start = document.cookie.indexOf(c_name + "=");
  382. if (c_start !== -1) {
  383. c_start = c_start + c_name.length + 1;
  384. let c_end = document.cookie.indexOf(";", c_start);
  385. if (c_end === -1) c_end = document.cookie.length;
  386. return unescape(document.cookie.substring(c_start, c_end))
  387. }
  388. }
  389. return "";
  390. };
  391. this.getSigned = function(apilist, func) {
  392. let that = func;
  393. this.get_data("!!/wxjs/signed.php?purl=" + encodeURIComponent(location.href),
  394. function(ret){
  395. wx.config({
  396. debug: false,
  397. appId: ret.appId,
  398. timestamp: ret.timestamp,
  399. nonceStr: ret.nonceStr,
  400. signature: ret.signature,
  401. jsApiList: apilist
  402. });
  403. that();
  404. }, "");
  405. };
  406. this.gotoJsLogin = function() {
  407. var APPID = "wx47691e7aabf77631";
  408. var re_uri = "https://gift.fogice.com/wxjs/oauth.php?otp=" + this.utils_get_parm("otp");
  409. var redir = encodeURIComponent(re_uri);
  410. location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ APPID+ "&redirect_uri=" +redir+ "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
  411. };
  412. /*this.userId = utils_get_param("userId");
  413. this.getUserId = function() {
  414. BasicFunction.loglog("Original USERID : " + userId);
  415. let use = getCookie("doibyUser");
  416. if (use == null || use === undefined || use.length <= 0) {
  417. location.href = "sign-in1.html?from=entrance-1&msg=nologin-mustauth";
  418. return;
  419. }
  420. BasicFunction.loglog("Got UID From COOKIE : " + use);
  421. try {
  422. let mm = parseInt(use);
  423. if (mm > 0) {
  424. BasicFunction.userId = mm;
  425. }
  426. } catch (e) {
  427. location.href = "sign-in1.html?from=entrance-1&msg=cookie-wrong-format";
  428. return;
  429. }
  430. BasicFunction.loglog("Got UserId Eventually : " + userId);
  431. };*/
  432. this.get_server_url();
  433. //this.on_document_load();
  434. })();
  435. window.BasicFunction = BasicFunction;
  436. export {
  437. BasicFunction
  438. };