15815213711
2024-08-26 67b8b6731811983447e053d4396b3708c14dfe3c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const debug = require('debug')('ee-core:ipcServer');
const is = require('is-type-of');
const { ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const globby = require('globby');
const Utils = require('../core/lib/utils');
const Wrap = require('../utils/wrap');
const Log = require('../log');
 
class IpcServer {
  constructor (app) {
    this.app = app;
    this.register();
  }
 
  register () {
    const self = this;
    // 遍历方法
    const files = Utils.filePatterns();
    const directory = path.join(this.app.config.baseDir, 'controller');
    const filepaths = globby.sync(files, { cwd: directory });
 
    for (const filepath of filepaths) {
      const fullpath = path.join(directory, filepath);
      if (!fs.statSync(fullpath).isFile()) continue;
 
      const properties = Wrap.getProperties(filepath, {caseStyle: 'lower'});
      const pathName = directory.split(/[/\\]/).slice(-1) + '.' + properties.join('.');
 
      let fileObj = Utils.loadFile(fullpath);
      const fns = {};
      // 为了统一,仅支持class文件
      if (is.class(fileObj) || Utils.isBytecodeClass(fileObj)) {
        let proto = fileObj.prototype;
        // 不遍历父类的方法
        //while (proto !== Object.prototype) {
          const keys = Object.getOwnPropertyNames(proto);
          for (const key of keys) {
            if (key === 'constructor') {
              continue;
            }
            const d = Object.getOwnPropertyDescriptor(proto, key);
            if (is.function(d.value) && !fns.hasOwnProperty(key)) {
              fns[key] = 1;
            }
          }
          //proto = Object.getPrototypeOf(proto);
        //}
      }
 
      debug('register class %s fns %j', pathName, fns);
 
      for (const key in fns) {
        let channel = pathName + '.' + key;
        debug('register channel %s', channel);
 
        function findFn (app, c) {
          try {
            // 找函数
            const cmd = c;
            let fn = null;
            if (is.string(cmd)) {
              const actions = cmd.split('.');
              let obj = app;
              actions.forEach(key => {
                obj = obj[key];
                if (!obj) throw new Error(`class or function '${key}' not exists`);
              });
              fn = obj;
            }
            if (!fn) throw new Error('function not exists');
            
            return fn;
          } catch (err) {
            Log.coreLogger.error('[ee-core] [socket/IpcServer] throw error:', err);
          }
          return null;
        }
 
        // send/on 模型
        ipcMain.on(channel, async (event, params) => {
          try {
            const fn = findFn(self.app, channel);
            const result = await fn.call(self.app, params, event);
  
            event.returnValue = result;
            event.reply(`${channel}`, result);
          } catch(e) {
            Log.coreLogger.error('[ee-core] [socket/IpcServer] send/on throw error:', e);
            // event.returnValue = e;
            // event.reply(`${channel}`, e);
          }
        });
 
        // invoke/handle 模型
        ipcMain.handle(channel, async (event, params) => {
          try {
            const fn = findFn(self.app, channel);
            const result = await fn.call(self.app, params, event);
  
            return result;
          } catch(e) {
            Log.coreLogger.error('[ee-core] [socket/IpcServer] invoke/handle throw error:', e);
            return e
          }
        });
      }
    }
  }
}
 
module.exports = IpcServer;