Completed
Push — master ( db3748...452316 )
by Equim
01:06
created

co.wrap   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 57
rs 9.0309

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
'use strict';
2
3
const
4
    superagent = require('superagent'),
5
    co         = require('co'),
6
    thunkify   = require('thunkify');
7
8
superagent.Request.prototype.endThunk = thunkify(superagent.Request.prototype.end);
9
10
// 直接从主页上扒下来的,加密算法
11
const encodeInp = (input) => {
12
    const keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
13
    let output = '';
14
    let chr1, chr2, chr3 = '';
15
    let enc1, enc2, enc3, enc4 = '';
16
    let i = 0;
17
    do {
18
        chr1 = input.charCodeAt(i++);
19
        chr2 = input.charCodeAt(i++);
20
        chr3 = input.charCodeAt(i++);
21
        enc1 = chr1 >> 2;
22
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
23
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
24
        enc4 = chr3 & 63;
25
        if (isNaN(chr2)) {
26
            enc3 = enc4 = 64;
27
        } else if (isNaN(chr3)) {
28
            enc4 = 64;
29
        }
30
        output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
31
    } while (i < input.length);
32
    return output;
33
};
34
35
module.exports = {
36
    // 登入模块
37
    login: co.wrap(function *(id, pwd) {
38
        let ires, iires;
39
40
        // 通过GET首页,来获取cookie
41
        try {
42
            ires = yield superagent
43
                .get('http://csujwc.its.csu.edu.cn/jsxsd')
44
                .endThunk();
45
        } catch (err) {
46
            err.eqMessage = {
47
                inner: `Failed to get the Cookie for login.\n${err.stack}`,
48
                public: '获取Cookie失败'
49
            };
50
            throw err;
51
        }
52
53
        const headers = {
54
            Host: 'csujwc.its.csu.edu.cn',
55
            Connection: 'keep-alive',
56
            'Cache-Control': 'max-age=0',
57
            Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
58
            Origin: 'http://csujwc.its.csu.edu.cn',
59
            'Upgrade-Insecure-Requests': 1,
60
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
61
            'Content-Type': 'application/x-www-form-urlencoded',
62
            Referer: 'http://csujwc.its.csu.edu.cn/jsxsd/',
63
            'Accept-Encoding': 'gzip, deflate',
64
            'Accept-Language': 'zh-CN,zh;q=0.8',
65
            Cookie: ires.headers['set-cookie']
66
        };
67
68
        try {
69
            iires = yield superagent
70
                .post('http://csujwc.its.csu.edu.cn/jsxsd/xk/LoginToXk')
71
                .set(headers)
72
                .type('form')
73
                .send({ encoded: `${encodeInp(id)}%%%${encodeInp(pwd)}` })
74
                .endThunk();
75
        } catch (err) {
76
            err.eqMessage = {
77
                inner: `Failed to login\n${err.stack}`,
78
                public: '登录失败'
79
            };
80
            throw err;
81
        }
82
83
        if (/POST/i.test(iires.req.method)) {
84
            let err = new Error('The request method to the logged in page is POST instead of GET');
85
            err.eqMessage = {
86
                inner: `Failed to login (possibily id or password provided were wrong)\n${err.stack}`,
87
                public: '登录失败,可能是用户名或密码错误,请确认参数已URL转义'
88
            };
89
            throw err;
90
        }
91
92
        return headers;
93
    }),
94
    // 登出模块
95
    logout: co.wrap(function *(headers) {
96
        try {
97
            yield superagent
98
                .get(`http://csujwc.its.csu.edu.cn/jsxsd/xk/LoginToXk?method=exit&tktime=${new Date().getTime()}`)
99
                .set(headers)
100
                .endThunk();
101
        } catch (err) {
102
            // res已经sent了,所以没有public的message
103
            err.eqMessage = {
104
                inner: `Failed to logout\n${err.stack}`
105
            };
106
            throw err;
107
        }
108
    })
109
};
110