api.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. (function () {
  2. const TOKEN_KEY = 'pouchlab.token.v1';
  3. const bindWaiters = [];
  4. function langHeader() {
  5. const lang = window.PL && window.PL.i18n ? window.PL.i18n.getLang() : 'zh';
  6. return lang === 'en' ? 'en' : 'zh-CN';
  7. }
  8. function tr(s) {
  9. return window.PL && window.PL.t ? window.PL.t(s) : s;
  10. }
  11. function token() {
  12. try { return localStorage.getItem(TOKEN_KEY) || ''; } catch (e) { return ''; }
  13. }
  14. function setToken(v) {
  15. try {
  16. if (v) localStorage.setItem(TOKEN_KEY, v);
  17. else localStorage.removeItem(TOKEN_KEY);
  18. } catch (e) {}
  19. }
  20. function request(method, path, body, opts) {
  21. opts = opts || {};
  22. const headers = {};
  23. if (body !== undefined) headers['Content-Type'] = 'application/json';
  24. headers['Accept-Language'] = langHeader();
  25. const t = token();
  26. if (t) headers['Authorization'] = 'Bearer ' + t;
  27. const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
  28. const timer = controller ? setTimeout(function () { controller.abort(); }, opts.timeout || 30000) : null;
  29. return fetch('/api' + path, {
  30. method: method,
  31. headers: headers,
  32. body: body !== undefined ? JSON.stringify(body) : undefined,
  33. signal: controller ? controller.signal : undefined
  34. }).then(function (res) {
  35. if (timer) clearTimeout(timer);
  36. if (res.status === 401) {
  37. setToken('');
  38. document.dispatchEvent(new CustomEvent('pl:auth-expired'));
  39. }
  40. return res.json().catch(function () { return {}; }).then(function (data) {
  41. if (res.status === 403 && data.detail && data.detail.code === 'bind-email') {
  42. return new Promise(function (resolve, reject) {
  43. bindWaiters.push(function () { request(method, path, body, opts).then(resolve, reject); });
  44. document.dispatchEvent(new CustomEvent('pl:bind-email-required',
  45. { detail: { message: data.detail.message } }));
  46. });
  47. }
  48. if (!res.ok) {
  49. const msg = data.detail && data.detail.message ? data.detail.message : data.detail;
  50. const err = new Error(msg || tr('请求失败(' + res.status + ')'));
  51. err.status = res.status;
  52. throw err;
  53. }
  54. return data;
  55. });
  56. }, function (e) {
  57. if (timer) clearTimeout(timer);
  58. if (e && e.name === 'AbortError') {
  59. const err = new Error(tr('请求超时,请重试'));
  60. err.network = true;
  61. throw err;
  62. }
  63. const err = new Error(tr('无法连接服务器'));
  64. err.network = true;
  65. throw err;
  66. });
  67. }
  68. // 带鉴权的文件下载(DXF/预览图/设计稿),转为浏览器下载
  69. function download(path, filename) {
  70. const t = token();
  71. return fetch('/api' + path, { headers: Object.assign({ 'Accept-Language': langHeader() }, t ? { Authorization: 'Bearer ' + t } : {}) }).then(function (res) {
  72. if (!res.ok) {
  73. return res.json().catch(function () { return {}; }).then(function (d) {
  74. throw new Error(d.detail || tr('下载失败(' + res.status + ')'));
  75. });
  76. }
  77. return res.blob();
  78. }).then(function (blob) {
  79. const url = URL.createObjectURL(blob);
  80. const a = document.createElement('a');
  81. a.href = url;
  82. a.download = filename || '';
  83. document.body.appendChild(a);
  84. a.click();
  85. a.remove();
  86. setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
  87. });
  88. }
  89. // SVG 字符串 → PNG dataURL(下单时生成本地预览,服务端与管理后台直接展示)
  90. function svgToPng(svg, maxW) {
  91. return new Promise(function (resolve, reject) {
  92. const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
  93. const url = URL.createObjectURL(blob);
  94. const img = new Image();
  95. img.onload = function () {
  96. const scale = Math.min(1, (maxW || 1000) / (img.width || 1));
  97. const canvas = document.createElement('canvas');
  98. canvas.width = Math.max(1, Math.round((img.width || 1) * scale));
  99. canvas.height = Math.max(1, Math.round((img.height || 1) * scale));
  100. const ctx = canvas.getContext('2d');
  101. ctx.fillStyle = '#ffffff';
  102. ctx.fillRect(0, 0, canvas.width, canvas.height);
  103. ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  104. URL.revokeObjectURL(url);
  105. resolve(canvas.toDataURL('image/png'));
  106. };
  107. img.onerror = function () {
  108. URL.revokeObjectURL(url);
  109. reject(new Error(tr('预览图生成失败')));
  110. };
  111. img.src = url;
  112. });
  113. }
  114. window.PL = window.PL || {};
  115. window.PL.api = {
  116. token: token,
  117. setToken: setToken,
  118. request: request,
  119. download: download,
  120. svgToPng: svgToPng,
  121. get: function (p, o) { return request('GET', p, undefined, o); },
  122. post: function (p, b, o) { return request('POST', p, b, o); },
  123. patch: function (p, b, o) { return request('PATCH', p, b, o); },
  124. flushBind: function () {
  125. const list = bindWaiters.splice(0);
  126. list.forEach(function (run) { try { run(); } catch (e) {} });
  127. }
  128. };
  129. })();