|
| 1 | +import fs from 'fs' |
| 2 | +import path from 'path' |
| 3 | +import axios from 'axios' |
| 4 | +import normalizePath from 'normalize-path' |
| 5 | +import crypto from 'crypto' |
| 6 | +import util from 'util' |
| 7 | +import Model from '../../model' |
| 8 | +import { IApplication } from '../../interfaces/application' |
| 9 | + |
| 10 | +const asyncReadFile = util.promisify(fs.readFile) |
| 11 | + |
| 12 | +export default class NetlifyApi extends Model { |
| 13 | + private apiUrl: string |
| 14 | + |
| 15 | + private accessToken: string |
| 16 | + |
| 17 | + private siteId: string |
| 18 | + |
| 19 | + private inputDir: string |
| 20 | + |
| 21 | + constructor(appInstance: IApplication) { |
| 22 | + super(appInstance) |
| 23 | + this.apiUrl = 'https://api.netlify.com/api/v1/' |
| 24 | + this.accessToken = appInstance.db.setting.netlifyAccessToken |
| 25 | + this.siteId = appInstance.db.setting.netlifySiteId |
| 26 | + this.inputDir = appInstance.buildDir |
| 27 | + } |
| 28 | + |
| 29 | + async request(method: 'GET' | 'PUT' | 'POST', endpoint: string, data?: any) { |
| 30 | + const endpointUrl = this.apiUrl + endpoint.replace(':site_id', this.siteId) |
| 31 | + const { setting } = this.db |
| 32 | + const proxy = setting.enabledProxy ? { |
| 33 | + host: setting.proxyPath, |
| 34 | + port: Number(setting.proxyPort), |
| 35 | + } : undefined |
| 36 | + |
| 37 | + return axios( |
| 38 | + endpointUrl, |
| 39 | + { |
| 40 | + method, |
| 41 | + headers: { |
| 42 | + 'User-Agent': 'Gridea', |
| 43 | + 'Authorization': `Bearer ${this.accessToken}`, |
| 44 | + }, |
| 45 | + data, |
| 46 | + proxy, |
| 47 | + }, |
| 48 | + ) |
| 49 | + } |
| 50 | + |
| 51 | + async remoteDetect() { |
| 52 | + try { |
| 53 | + const res = await this.request('GET', 'sites/:site_id/') |
| 54 | + if (res.status === 200) { |
| 55 | + return { |
| 56 | + success: true, |
| 57 | + message: res.data, |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return { |
| 62 | + success: false, |
| 63 | + message: res.data, |
| 64 | + } |
| 65 | + } catch (e) { |
| 66 | + return { |
| 67 | + success: false, |
| 68 | + message: e, |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + async publish() { |
| 74 | + const result = { |
| 75 | + success: true, |
| 76 | + message: '同步成功', |
| 77 | + data: null, |
| 78 | + } |
| 79 | + |
| 80 | + try { |
| 81 | + const localFilesList = await this.prepareLocalFilesList() |
| 82 | + const deployData = await this.request('POST', 'sites/:site_id/deploys', localFilesList) |
| 83 | + const deployId = deployData.data.id |
| 84 | + const hashOfFilesToUpload = deployData.data.required |
| 85 | + const filesToUpload = this.getFilesToUpload(localFilesList, hashOfFilesToUpload) |
| 86 | + |
| 87 | + for (let i = 0; i < filesToUpload.length; i += 1) { |
| 88 | + const filePath = filesToUpload[i] |
| 89 | + |
| 90 | + try { |
| 91 | + // eslint-disable-next-line no-await-in-loop |
| 92 | + const res = await this.uploadFile(filePath, deployId) |
| 93 | + |
| 94 | + if (res.status === 422) { |
| 95 | + return Promise.reject(res) |
| 96 | + } |
| 97 | + } catch (e) { |
| 98 | + try { |
| 99 | + // eslint-disable-next-line no-await-in-loop |
| 100 | + const res = await this.uploadFile(filePath, deployId) |
| 101 | + |
| 102 | + if (res.status === 422) { |
| 103 | + return Promise.reject(res) |
| 104 | + } |
| 105 | + } catch (error) { |
| 106 | + return Promise.reject(error) |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + return result |
| 112 | + } catch (e) { |
| 113 | + result.success = false |
| 114 | + result.message = `[Server] 同步失败: ${e.message}` |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + async prepareLocalFilesList() { |
| 119 | + const tempFileList: any = this.readDirRecursiveSync(this.inputDir) |
| 120 | + const fileList: any = {} |
| 121 | + |
| 122 | + for (const filePath of tempFileList) { |
| 123 | + if (fs.lstatSync(path.join(this.inputDir, filePath)).isDirectory()) { |
| 124 | + continue |
| 125 | + } |
| 126 | + |
| 127 | + // eslint-disable-next-line no-await-in-loop |
| 128 | + const fileHash = await this.getFileHash(path.join(this.inputDir, filePath)) |
| 129 | + const fileKey = `/${filePath}`.replace(/\/\//gmi, '/') |
| 130 | + fileList[fileKey] = fileHash |
| 131 | + } |
| 132 | + |
| 133 | + return Promise.resolve({ files: fileList }) |
| 134 | + } |
| 135 | + |
| 136 | + readDirRecursiveSync(dir: string, fileList?: any) { |
| 137 | + const files = fs.readdirSync(dir) |
| 138 | + fileList = fileList || [] |
| 139 | + |
| 140 | + files.forEach((file) => { |
| 141 | + if (this.fileIsDirectory(dir, file)) { |
| 142 | + fileList = this.readDirRecursiveSync(path.join(dir, file), fileList) |
| 143 | + return |
| 144 | + } |
| 145 | + |
| 146 | + if (this.fileIsNotExcluded(file)) { |
| 147 | + fileList.push(this.getFilePath(dir, file)) |
| 148 | + } |
| 149 | + }) |
| 150 | + |
| 151 | + return fileList |
| 152 | + } |
| 153 | + |
| 154 | + fileIsDirectory(dir: string, file: string) { |
| 155 | + return fs.statSync(path.join(dir, file)).isDirectory() |
| 156 | + } |
| 157 | + |
| 158 | + fileIsNotExcluded(file: string) { |
| 159 | + return file.indexOf('.') !== 0 || file === '.htaccess' || file === '_redirects' |
| 160 | + } |
| 161 | + |
| 162 | + getFilePath(dir: string, file: string, includeInputDir = false) { |
| 163 | + if (!includeInputDir) { |
| 164 | + dir = dir.replace(this.inputDir, '') |
| 165 | + } |
| 166 | + |
| 167 | + return normalizePath(path.join(dir, file)) |
| 168 | + } |
| 169 | + |
| 170 | + getFileHash(fileName: string) { |
| 171 | + return new Promise((resolve, reject) => { |
| 172 | + const shaSumCalculator = crypto.createHash('sha1') |
| 173 | + |
| 174 | + try { |
| 175 | + const fileStream = fs.createReadStream(fileName) |
| 176 | + fileStream.on('data', fileContentChunk => shaSumCalculator.update(fileContentChunk)) |
| 177 | + fileStream.on('end', () => resolve(shaSumCalculator.digest('hex'))) |
| 178 | + } catch (e) { |
| 179 | + return reject(e) |
| 180 | + } |
| 181 | + }) |
| 182 | + } |
| 183 | + |
| 184 | + getFilesToUpload(filesList: any, hashesToUpload: any) { |
| 185 | + const filePaths = Object.keys(filesList.files) |
| 186 | + const filesToUpload = [] |
| 187 | + const foundedHashes = [] |
| 188 | + |
| 189 | + for (let i = 0; i < filePaths.length; i++) { |
| 190 | + const filePath = filePaths[i] |
| 191 | + |
| 192 | + if (hashesToUpload.indexOf(filesList.files[filePath]) > -1) { |
| 193 | + filesToUpload.push(filePath.replace(/\/\//gmi, '/')) |
| 194 | + foundedHashes.push(filesList.files[filePath]) |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + return filesToUpload |
| 199 | + } |
| 200 | + |
| 201 | + async uploadFile(filePath: any, deployID: any) { |
| 202 | + const endpointUrl = `${this.apiUrl}deploys/${deployID}/files${filePath}` |
| 203 | + const fullFilePath = this.getFilePath(this.inputDir, filePath, true) |
| 204 | + const fileContent = await asyncReadFile(fullFilePath) |
| 205 | + |
| 206 | + return axios(endpointUrl, { |
| 207 | + method: 'PUT', |
| 208 | + headers: { |
| 209 | + 'User-Agent': 'Gridea', |
| 210 | + 'Content-Type': 'application/octet-stream', |
| 211 | + 'Authorization': `Bearer ${this.accessToken}`, |
| 212 | + }, |
| 213 | + data: fileContent, |
| 214 | + }) |
| 215 | + } |
| 216 | +} |
0 commit comments