main.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const {
  2. Router
  3. } = require('express');
  4. const {
  5. join
  6. } = require('path');
  7. let analyticsFileName = 'cocosAnalytics.min.2.2.1.js';
  8. const Paths = {
  9. sdkPath: join(__dirname, analyticsFileName),
  10. sdkURL: 'ccservices-scripts/' + analyticsFileName,
  11. };
  12. const appid = '623706372';
  13. const store = '';
  14. module.exports = {
  15. router: null,
  16. load() {
  17. this.hookPreviewServer();
  18. },
  19. unload() {
  20. this.unhookPreviewServer();
  21. },
  22. insertSDK(settings, url) {
  23. let newSettings = null;
  24. if (settings.match(/jsList/)) {
  25. newSettings = settings.replace(/,\s*jsList\s*:\s*\[/, '$&' + JSON.stringify(url) + ', ');
  26. } else {
  27. var str = ',\n\tjsList: [' + JSON.stringify(url) + '],\n\tlaunchScene:';
  28. newSettings = settings.replace(/,\s*launchScene\s*:/, str);
  29. }
  30. if (newSettings === settings) {
  31. Editor.warn('Failed to send My Awesome SDK to the web preview.');
  32. }
  33. return newSettings;
  34. },
  35. getSettings(req, res, next) {
  36. let sendVendor = res.send;
  37. res.send = (content) => {
  38. content = this.insertSDK(content, Paths.sdkURL);
  39. content = this.insertSDK(content, "ccservices-scripts/cocos-analytics-init.js");
  40. sendVendor.call(res, content);
  41. };
  42. next();
  43. },
  44. getSDK(req, res) {
  45. res.setHeader("Content-Type", "text/javascript");
  46. if (req.params[0] === "cocos-analytics-init.js") {
  47. var analyticsInit = `(function () {
  48. let runIdx = 1;
  49. let timer = setInterval(() => {
  50. if (typeof cocosAnalytics !== 'undefined') {
  51. clearInterval(timer);
  52. cocosAnalytics.init({appID: '${appid}', storeID: '${store}',engine: 'cocos', callNumber: ''});
  53. }
  54. }, 100);
  55. })();`;
  56. res.send(analyticsInit);
  57. } else
  58. res.sendFile(Paths.sdkPath);
  59. },
  60. hookPreviewServer() {
  61. if (this.router) {
  62. return;
  63. }
  64. this.router = Router();
  65. Editor.PreviewServer.userMiddlewares.push(this.router);
  66. this.router.get('/settings.js', this.getSettings.bind(this));
  67. this.router.get('/plugins/ccservices-scripts/*', this.getSDK.bind(this));
  68. this.router.get('/res/raw-ccservices-scripts/*', this.getSDK.bind(this));
  69. },
  70. unhookPreviewServer() {
  71. cc.js.array.remove(Editor.PreviewServer.userMiddlewares, this.router);
  72. this.router = null;
  73. },
  74. };