| 5 | import { BaiduFileReader, BaiduFileWriter } from "./rw"; |
| 6 | |
| 7 | export default class BaiduFileSystem implements FileSystem { |
| 8 | accessToken?: string; |
| 9 | |
| 10 | path: string; |
| 11 | |
| 12 | constructor(path?: string, accessToken?: string) { |
| 13 | this.path = path || "/apps"; |
| 14 | this.accessToken = accessToken; |
| 15 | } |
| 16 | |
| 17 | async verify(): Promise<void> { |
| 18 | const token = await AuthVerify("baidu"); |
| 19 | this.accessToken = token; |
| 20 | return this.list().then(); |
| 21 | } |
| 22 | |
| 23 | async open(file: FileInfo): Promise<FileReader> { |
| 24 | // 获取fsid |
| 25 | return new BaiduFileReader(this, file); |
| 26 | } |
| 27 | |
| 28 | async openDir(path: string): Promise<FileSystem> { |
| 29 | return new BaiduFileSystem(joinPath(this.path, path), this.accessToken); |
| 30 | } |
| 31 | |
| 32 | async create(path: string, _opts?: FileCreateOptions): Promise<FileWriter> { |
| 33 | return new BaiduFileWriter(this, joinPath(this.path, path)); |
| 34 | } |
| 35 | |
| 36 | async createDir(dir: string, _opts?: FileCreateOptions): Promise<void> { |
| 37 | dir = joinPath(this.path, dir); |
| 38 | const urlencoded = new URLSearchParams(); |
| 39 | urlencoded.append("path", dir); |
| 40 | urlencoded.append("size", "0"); |
| 41 | urlencoded.append("isdir", "1"); |
| 42 | urlencoded.append("rtype", "3"); |
| 43 | const myHeaders = new Headers(); |
| 44 | myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); |
| 45 | const data = await this.request( |
| 46 | `https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${this.accessToken}`, |
| 47 | { |
| 48 | method: "POST", |
| 49 | headers: myHeaders, |
| 50 | body: urlencoded, |
| 51 | redirect: "follow", |
| 52 | } |
| 53 | ); |
| 54 | if (data.errno) { |
| 55 | throw new Error(JSON.stringify(data)); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | async request(url: string, config?: RequestInit) { |
| 60 | config = config || {}; |
| 61 | const headers = <Headers>config.headers || new Headers(); |
| 62 | config.headers = headers; |
| 63 | // 对百度网盘请求显式禁用 cookie,避免依赖全局 DNR 规则造成并发竞态 |
| 64 | config.credentials = "omit"; |
nothing calls this directly
no outgoing calls
no test coverage detected