File size: 8,641 Bytes
7107f0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package quqi

import (
	"bufio"
	"context"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	stdpath "path"
	"strings"
	"time"

	"github.com/alist-org/alist/v3/drivers/base"
	"github.com/alist-org/alist/v3/internal/errs"
	"github.com/alist-org/alist/v3/internal/model"
	"github.com/alist-org/alist/v3/internal/stream"
	"github.com/alist-org/alist/v3/pkg/http_range"
	"github.com/alist-org/alist/v3/pkg/utils"
	"github.com/go-resty/resty/v2"
	"github.com/minio/sio"
)

// do others that not defined in Driver interface
func (d *Quqi) request(host string, path string, method string, callback base.ReqCallback, resp interface{}) (*resty.Response, error) {
	var (
		reqUrl = url.URL{
			Scheme: "https",
			Host:   "quqi.com",
			Path:   path,
		}
		req    = base.RestyClient.R()
		result BaseRes
	)

	if host != "" {
		reqUrl.Host = host
	}
	req.SetHeaders(map[string]string{
		"Origin": "https://quqi.com",
		"Cookie": d.Cookie,
	})

	if d.GroupID != "" {
		req.SetQueryParam("quqiid", d.GroupID)
	}

	if callback != nil {
		callback(req)
	}

	res, err := req.Execute(method, reqUrl.String())
	if err != nil {
		return nil, err
	}
	// resty.Request.SetResult cannot parse result correctly sometimes
	err = utils.Json.Unmarshal(res.Body(), &result)
	if err != nil {
		return nil, err
	}
	if result.Code != 0 {
		return nil, errors.New(result.Message)
	}
	if resp != nil {
		err = utils.Json.Unmarshal(res.Body(), resp)
		if err != nil {
			return nil, err
		}
	}
	return res, nil
}

func (d *Quqi) login() error {
	if d.Addition.Cookie != "" {
		d.Cookie = d.Addition.Cookie
	}
	if d.checkLogin() {
		return nil
	}
	if d.Cookie != "" {
		return errors.New("cookie is invalid")
	}
	if d.Phone == "" {
		return errors.New("phone number is empty")
	}
	if d.Password == "" {
		return errs.EmptyPassword
	}

	resp, err := d.request("", "/auth/person/v2/login/password", resty.MethodPost, func(req *resty.Request) {
		req.SetFormData(map[string]string{
			"phone":    d.Phone,
			"password": base64.StdEncoding.EncodeToString([]byte(d.Password)),
		})
	}, nil)
	if err != nil {
		return err
	}

	var cookies []string
	for _, cookie := range resp.RawResponse.Cookies() {
		cookies = append(cookies, fmt.Sprintf("%s=%s", cookie.Name, cookie.Value))
	}
	d.Cookie = strings.Join(cookies, ";")

	return nil
}

func (d *Quqi) checkLogin() bool {
	if _, err := d.request("", "/auth/account/baseInfo", resty.MethodGet, nil, nil); err != nil {
		return false
	}
	return true
}

// rawExt 保留扩展名大小写
func rawExt(name string) string {
	ext := stdpath.Ext(name)
	if strings.HasPrefix(ext, ".") {
		ext = ext[1:]
	}

	return ext
}

// decryptKey 获取密码
func decryptKey(encodeKey string) []byte {
	// 移除非法字符
	u := strings.ReplaceAll(encodeKey, "[^A-Za-z0-9+\\/]", "")

	// 计算输出字节数组的长度
	o := len(u)
	a := 32

	// 创建输出字节数组
	c := make([]byte, a)

	// 编码循环
	s := uint32(0) // 累加器
	f := 0         // 输出数组索引
	for l := 0; l < o; l++ {
		r := l & 3 // 取模4,得到当前字符在四字节块中的位置
		i := u[l]  // 当前字符的ASCII码

		// 编码当前字符
		switch {
		case i >= 65 && i < 91: // 大写字母
			s |= uint32(i-65) << uint32(6*(3-r))
		case i >= 97 && i < 123: // 小写字母
			s |= uint32(i-71) << uint32(6*(3-r))
		case i >= 48 && i < 58: // 数字
			s |= uint32(i+4) << uint32(6*(3-r))
		case i == 43: // 加号
			s |= uint32(62) << uint32(6*(3-r))
		case i == 47: // 斜杠
			s |= uint32(63) << uint32(6*(3-r))
		}

		// 如果累加器已经包含了四个字符,或者是最后一个字符,则写入输出数组
		if r == 3 || l == o-1 {
			for e := 0; e < 3 && f < a; e, f = e+1, f+1 {
				c[f] = byte(s >> (16 >> e & 24) & 255)
			}
			s = 0
		}
	}

	return c
}

func (d *Quqi) linkFromPreview(id string) (*model.Link, error) {
	var getDocResp GetDocRes
	if _, err := d.request("", "/api/doc/getDoc", resty.MethodPost, func(req *resty.Request) {
		req.SetFormData(map[string]string{
			"quqi_id":   d.GroupID,
			"tree_id":   "1",
			"node_id":   id,
			"client_id": d.ClientID,
		})
	}, &getDocResp); err != nil {
		return nil, err
	}
	if getDocResp.Data.OriginPath == "" {
		return nil, errors.New("cannot get link from preview")
	}
	return &model.Link{
		URL: getDocResp.Data.OriginPath,
		Header: http.Header{
			"Origin": []string{"https://quqi.com"},
			"Cookie": []string{d.Cookie},
		},
	}, nil
}

func (d *Quqi) linkFromDownload(id string) (*model.Link, error) {
	var getDownloadResp GetDownloadResp
	if _, err := d.request("", "/api/doc/getDownload", resty.MethodGet, func(req *resty.Request) {
		req.SetQueryParams(map[string]string{
			"quqi_id":     d.GroupID,
			"tree_id":     "1",
			"node_id":     id,
			"url_type":    "undefined",
			"entry_type":  "undefined",
			"client_id":   d.ClientID,
			"no_redirect": "1",
		})
	}, &getDownloadResp); err != nil {
		return nil, err
	}
	if getDownloadResp.Data.Url == "" {
		return nil, errors.New("cannot get link from download")
	}

	return &model.Link{
		URL: getDownloadResp.Data.Url,
		Header: http.Header{
			"Origin": []string{"https://quqi.com"},
			"Cookie": []string{d.Cookie},
		},
	}, nil
}

func (d *Quqi) linkFromCDN(id string) (*model.Link, error) {
	downloadLink, err := d.linkFromDownload(id)
	if err != nil {
		return nil, err
	}

	var urlExchangeResp UrlExchangeResp
	if _, err = d.request("api.quqi.com", "/preview/downloadInfo/url/exchange", resty.MethodGet, func(req *resty.Request) {
		req.SetQueryParam("url", downloadLink.URL)
	}, &urlExchangeResp); err != nil {
		return nil, err
	}
	if urlExchangeResp.Data.Url == "" {
		return nil, errors.New("cannot get link from cdn")
	}

	// 假设存在未加密的情况
	if !urlExchangeResp.Data.IsEncrypted {
		return &model.Link{
			URL: urlExchangeResp.Data.Url,
			Header: http.Header{
				"Origin": []string{"https://quqi.com"},
				"Cookie": []string{d.Cookie},
			},
		}, nil
	}

	// 根据sio(https://github.com/minio/sio/blob/master/DARE.md)描述及实际测试,得出以下结论:
	// 1. 加密后大小(encrypted_size)-原始文件大小(size) = 加密包的头大小+身份验证标识 = (16+16) * N  ->  N为加密包的数量
	// 2. 原始文件大小(size)+64*1024-1 / (64*1024) = N  ->  每个包的有效负载为64K
	remoteClosers := utils.EmptyClosers()
	payloadSize := int64(1 << 16)
	expiration := time.Until(time.Unix(urlExchangeResp.Data.ExpiredTime, 0))
	resultRangeReader := func(ctx context.Context, httpRange http_range.Range) (io.ReadCloser, error) {
		encryptedOffset := httpRange.Start / payloadSize * (payloadSize + 32)
		decryptedOffset := httpRange.Start % payloadSize
		encryptedLength := (httpRange.Length+httpRange.Start+payloadSize-1)/payloadSize*(payloadSize+32) - encryptedOffset
		if httpRange.Length < 0 {
			encryptedLength = httpRange.Length
		} else {
			if httpRange.Length+httpRange.Start >= urlExchangeResp.Data.Size || encryptedLength+encryptedOffset >= urlExchangeResp.Data.EncryptedSize {
				encryptedLength = -1
			}
		}
		//log.Debugf("size: %d\tencrypted_size: %d", urlExchangeResp.Data.Size, urlExchangeResp.Data.EncryptedSize)
		//log.Debugf("http range offset: %d, length: %d", httpRange.Start, httpRange.Length)
		//log.Debugf("encrypted offset: %d, length: %d, decrypted offset: %d", encryptedOffset, encryptedLength, decryptedOffset)

		rrc, err := stream.GetRangeReadCloserFromLink(urlExchangeResp.Data.EncryptedSize, &model.Link{
			URL: urlExchangeResp.Data.Url,
			Header: http.Header{
				"Origin": []string{"https://quqi.com"},
				"Cookie": []string{d.Cookie},
			},
		})
		if err != nil {
			return nil, err
		}

		rc, err := rrc.RangeRead(ctx, http_range.Range{Start: encryptedOffset, Length: encryptedLength})
		remoteClosers.AddClosers(rrc.GetClosers())
		if err != nil {
			return nil, err
		}

		decryptReader, err := sio.DecryptReader(rc, sio.Config{
			MinVersion:     sio.Version10,
			MaxVersion:     sio.Version20,
			CipherSuites:   []byte{sio.CHACHA20_POLY1305, sio.AES_256_GCM},
			Key:            decryptKey(urlExchangeResp.Data.EncryptedKey),
			SequenceNumber: uint32(httpRange.Start / payloadSize),
		})
		if err != nil {
			return nil, err
		}
		bufferReader := bufio.NewReader(decryptReader)
		bufferReader.Discard(int(decryptedOffset))

		return utils.NewReadCloser(bufferReader, func() error {
			return nil
		}), nil
	}

	return &model.Link{
		Header: http.Header{
			"Origin": []string{"https://quqi.com"},
			"Cookie": []string{d.Cookie},
		},
		RangeReadCloser: &model.RangeReadCloser{RangeReader: resultRangeReader, Closers: remoteClosers},
		Expiration:      &expiration,
	}, nil
}