Completed
Push — master ( 1cb6cd...b745b3 )
by Equim
01:20 queued 19s
created

app.js (3 issues)

1
'use strict';
2
3
const
4
    express    = require('express'),
5
    superagent = require('superagent'),
6
    cheerio    = require('cheerio'),
7
    colors     = require('colors'),
0 ignored issues
show
The constant colors seems to be never used. Consider removing it.
Loading history...
8
    program    = require('commander'),
9
    moment     = require('moment'),
10
    co         = require('co'),
11
    thunkify   = require('thunkify'),
12
    access     = require('./lib/access.js');
13
14
program
15
    .option('-h, --help')
16
    .option('-v, --version')
17
    .option('-p, --port [value]', parseInt)
0 ignored issues
show
The variable parseInt seems to be never declared. If this is a global, consider adding a /** global: parseInt */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
18
    .option('-f, --fullLog')
19
    .parse(process.argv);
20
21
// 别问我为什么这里逻辑这么奇怪……测试的结果确实是这样的啊hhh
22
if (!program.help || !program.version) {
23
    console.log(
24
`${`CSUEMS API v${require('./package').version}
25
by The Liberators`.rainbow}${program.help ? '' :
26
`
27
28
Preparation:
29
  ${'(This section is WIP)'.grey}
30
31
Usage:
32
  npm start [-- <options...>]
33
34
Options:
35
  -h, --help          print this message and exit.
36
  -v, --version       print the version and exit.
37
  -f, --fullLog       enable full log, by default only errors are logged.
38
  -p, --port [value]  specify a port to listen, process.env.PORT || 2333 by default.
39
40
Examples:
41
  $ npm start -- -p 43715               # listening to 43715
42
  $ forever start app.js                # deploy with forever as daemon (root access recommended)
43
  $ pm2 start -i 0 -n "csuapi" app.js   # deploy with pm2 as daemon  (root access recommended)`}`);
44
    process.exit(0);
45
}
46
47
superagent.Request.prototype.endThunk = thunkify(superagent.Request.prototype.end);
48
49
const
50
    logging = (log) => console.log(`${moment().format('[[]YY-MM-DD HH:mm:ss[]]')} ${log}`),
51
    fullLogging = (log) => program.fullLog && logging(log),
52
    getSem = () => {
53
        // 以系统时间获取当前学期
54
        let now = new Date();
55
        let month = now.getMonth();
56
        let year = now.getFullYear();
57
        if (month <= 6) {
58
            return `${year - 1}-${year}-${month > 0 ? 2 : 1}`;
59
        }
60
        return `${year}-${year + 1}-1`;
61
    },
62
//  wait = (ms) => (callback) => setTimeout(callback, ms),
63
    port = program.port || process.env.PORT || 2333,
64
    app = express();
65
66
// 获取文档
67
app.get('/doc', (req, res) => res.sendFile(`${__dirname}/doc/API.html`));
68
69
// 查成绩API,通过GET传入用户名和密码
70
app.get(/^\/g(?:|rades)$/, co.wrap(function *(req, res) {
71
    if (!req.query.id || !req.query.pwd || (req.query.sem && !(/^20\d{2}-20\d{2}-[1-2]$/).test(req.query.sem))) {
72
        res.status(404).send({ error: "参数不正确" });
73
        return;
74
    }
75
76
    let start = new Date();
77
    fullLogging('Started to query the grades: '.cyan + req.query.id.yellow);
78
79
    let headers;
80
    try {
81
        headers = yield access.login(req.query.id, req.query.pwd);
82
    } catch (err) {
83
        logging(err.eqMessage.inner.red);
84
        res.status(404).send({ error: err.eqMessage.public });
85
        return;
86
    }
87
    fullLogging('Successfully logged in.'.green);
88
89
    let ires;
90
    try {
91
        // 实际上xnxq01id为空的时候和GET这个URL的效果是一样的,都是查询所有学期
92
        ires = yield superagent
93
            .post('http://csujwc.its.csu.edu.cn/jsxsd/kscj/yscjcx_list')
94
            .set(headers)
95
            .type('form')
96
            .send({ xnxq01id: req.query.sem })
97
            .endThunk();
98
    } catch (err) {
99
        logging(`Failed to get grades page\n${err.stack}`.red);
100
        res.status(404).send({ error: '无法进入成绩页面' });
101
        return;
102
    } finally {
103
        // 直接异步进行?
104
        co(function *() {
105
            try {
106
                yield access.logout(headers);
107
            } catch (err) {
108
                logging(err.eqMessage.inner.red);
109
                return;
0 ignored issues
show
Comprehensibility Bug introduced by
Usage of the return statement in a finally clause is discouraged. This construct may mask errors and makes debugging difficult.
Loading history...
110
            }
111
            fullLogging('Successfully logged out: '.green + req.query.id.yellow);
112
        });
113
    }
114
    fullLogging('Successfully entered grades page.'.green);
115
116
    let $ = cheerio.load(ires.text);
117
118
    let top = $('#Top1_divLoginName').text();
119
    let result = {
120
        name: top.match(/\s.+\(/)[0].replace(/\s|\(/g, ''),
121
        id: top.match(/\(.+\)/)[0].replace(/\(|\)/g, ''),
122
        grades: {},
123
        'subject-count': 0,
124
        failed: {},
125
        'failed-count': 0,
126
    };
127
    // 获取成绩列表
128
    $('#dataList tr').each(function (index) {
129
        if (index === 0) {
130
            return;
131
        }
132
133
        let element = $(this).find('td');
134
135
        let title = element.eq(3).text().match(/].+$/)[0].substring(1);
136
        let item = {
137
            sem: element.eq(2).text(),
138
            reg: element.eq(4).text(),
139
            exam: element.eq(5).text(),
140
            overall: element.eq(6).text()
141
        };
142
        if (req.query.details) {
143
            item.id = element.eq(3).text().match(/\[.+\]/)[0].replace(/\[|\]/g, '');
144
            item.attr = element.eq(8).text();
145
            item.genre = element.eq(9).text();
146
            item.credit = element.eq(7).text();
147
        }
148
149
        // 如果有补考记录,则以最高分的为准(暂不考虑NaN)
150
        if (title in result.grades && item.overall < result.grades[title].overall) {
151
            return;
152
        }
153
154
        result.grades[title] = item;
155
156
        // 挂科判定
157
        if (element.eq(6).css('color')) {
158
            result.failed[title] = item;
159
        } else {
160
            delete result.failed[title];
161
        }
162
    });
163
164
    result['subject-count'] = Object.keys(result.grades).length;
165
    result['failed-count'] = Object.keys(result.failed).length;
166
167
    res.send(JSON.stringify(result));
168
    fullLogging(`Successfully responded. (req -> res processed in ${new Date() - start} ms)`.green);
169
}));
170
171
// 查考试API,通过GET传入用户名和密码
172
app.get(/^\/e(?:|xams)$/, co.wrap(function *(req, res) {
173
    if (!req.query.id || !req.query.pwd || (req.query.sem && !(/^20\d{2}-20\d{2}-[1-2]$/).test(req.query.sem))) {
174
        res.status(404).send({ error: "参数不正确" });
175
        return;
176
    }
177
178
    let start = new Date();
179
    fullLogging('Started to query the exams: '.cyan + req.query.id.yellow);
180
181
    let headers;
182
    try {
183
        headers = yield access.login(req.query.id, req.query.pwd);
184
    } catch (err) {
185
        logging(err.eqMessage.inner.red);
186
        res.status(404).send({ error: err.eqMessage.public });
187
        return;
188
    }
189
    fullLogging('Successfully logged in.'.green);
190
191
    let ires;
192
    let _sem = req.query.sem || getSem();
193
    try {
194
        ires = yield superagent
195
            .post('http://csujwc.its.csu.edu.cn/jsxsd/xsks/xsksap_list')
196
            .set(headers)
197
            .type('form')
198
            .send({
199
                xqlbmc: '',
200
                xnxqid: _sem,
201
                xqlb: ''
202
            })
203
            .endThunk();
204
    } catch (err) {
205
        logging(`Failed to reach exams page\n${err.stack}`.red);
206
        res.status(404).send({ error: '无法进入考试页面' });
207
        return;
208
    } finally {
209
        co(function *() {
210
            try {
211
                yield access.logout(headers);
212
            } catch (err) {
213
                logging(err.eqMessage.inner.red);
214
            }
215
            fullLogging('Successfully logged out: '.green + req.query.id.yellow);
216
        });
217
    }
218
    fullLogging('Successfully entered exams page.'.green);
219
220
    let $ = cheerio.load(ires.text);
221
222
    let top = $('#Top1_divLoginName').text();
223
    let result = {
224
        name: top.match(/\s.+\(/)[0].replace(/\s|\(/g, ''),
225
        id: top.match(/\(.+\)/)[0].replace(/\(|\)/g, ''),
226
        sem: _sem,
227
        exams: {},
228
        'exams-count': 0,
229
    };
230
    $('#dataList tr').each(function (index) {
231
        if (index === 0) {
232
            return;
233
        }
234
235
        let element = $(this).find('td');
236
237
        let title = element.eq(3).text();
238
        let item = {
239
            time: element.eq(4).text(),
240
            location: element.eq(5).text(),
241
            seat: element.eq(6).text()
242
        };
243
244
        result.exams[title] = item;
245
        result['exams-count']++;
246
    });
247
248
    res.send(JSON.stringify(result));
249
    fullLogging(`Successfully responded. (req -> res processed in ${new Date() - start} ms)`.green);
250
}));
251
252
app.listen(port, () => {
253
    logging(`The API is now running on port ${port}. Full logging is ${program.fullLog ? 'enabled' : 'disabled'}`.green);
254
});
255