forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileSystem.js
More file actions
208 lines (187 loc) · 5.96 KB
/
Copy pathfileSystem.js
File metadata and controls
208 lines (187 loc) · 5.96 KB
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
import path from 'path'
import crypto from 'crypto'
import { clipboard } from 'electron'
import fs from 'fs-extra'
import dayjs from 'dayjs'
import Octokit from '@octokit/rest'
import { ensureDirSync } from 'common/filesystem'
import { isImageFile } from 'common/filesystem/paths'
import { dataURItoBlob } from './index'
import axios from '../axios'
export const create = (pathname, type) => {
if (type === 'directory') {
return fs.ensureDir(pathname)
} else {
return fs.outputFile(pathname, '')
}
}
export const paste = ({ src, dest, type }) => {
return type === 'cut' ? fs.move(src, dest) : fs.copy(src, dest)
}
export const rename = (src, dest) => {
return fs.move(src, dest)
}
export const getHash = (content, encoding, type) => {
return crypto.createHash(type).update(content, encoding).digest('hex')
}
export const getContentHash = content => {
return getHash(content, 'utf8', 'sha1')
}
export const moveToRelativeFolder = async (cwd, imagePath, relativeName) => {
if (!relativeName) {
// Use fallback name according settings description
relativeName = 'assets'
} else if (path.isAbsolute(relativeName)) {
throw new Error('Invalid relative directory name')
}
// Path combination:
// - markdown file directory + relative directory name or
// - root directory + relative directory name
const absPath = path.resolve(cwd, relativeName)
const dstPath = path.resolve(absPath, path.basename(imagePath))
ensureDirSync(absPath)
await fs.move(imagePath, dstPath, { overwrite: true })
// dstRelPath: relative directory name + image file name
const dstRelPath = path.join(relativeName, path.basename(imagePath))
return dstRelPath
}
export const moveImageToFolder = async (pathname, image, dir) => {
ensureDirSync(dir)
const isPath = typeof image === 'string'
if (isPath) {
const dirname = path.dirname(pathname)
const imagePath = path.resolve(dirname, image)
const isImage = isImageFile(imagePath)
if (isImage) {
const filename = path.basename(imagePath)
const extname = path.extname(imagePath)
const noHashPath = path.join(dir, filename)
if (noHashPath === imagePath) {
return imagePath
}
const hash = getContentHash(imagePath)
// To avoid name conflict.
const hashFilePath = path.join(dir, `${hash}${extname}`)
await fs.copy(imagePath, hashFilePath)
return hashFilePath
} else {
return Promise.resolve(image)
}
} else {
const imagePath = path.join(dir, `${dayjs().format('YYYY-MM-DD-HH-mm-ss')}-${image.name}`)
const binaryString = await new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = () => {
resolve(fileReader.result)
}
fileReader.readAsBinaryString(image)
})
await fs.writeFile(imagePath, binaryString, 'binary')
return imagePath
}
}
/**
* @jocs todo, rewrite it use class
*/
export const uploadImage = async (pathname, image, preferences) => {
const { currentUploader } = preferences
const { owner, repo, branch } = preferences.imageBed.github
const token = preferences.githubToken
const isPath = typeof image === 'string'
const MAX_SIZE = 5 * 1024 * 1024
let re
let rj
const promise = new Promise((resolve, reject) => {
re = resolve
rj = reject
})
const uploadToSMMS = file => {
const api = 'https://sm.ms/api/upload'
const formData = new window.FormData()
formData.append('smfile', file)
axios({
method: 'post',
url: api,
data: formData
}).then((res) => {
// TODO: "res.data.data.delete" should emit "image-uploaded"/handleUploadedImage in editor.js. Maybe add to image manager too.
// This notification will be removed when the image manager implemented.
const notice = new Notification('Copy delete URL', {
body: 'Click to copy the delete URL to clipboard.'
})
notice.onclick = () => {
clipboard.writeText(res.data.data.delete)
}
re(res.data.data.url)
})
.catch(_ => {
rj('Upload failed, the image will be copied to the image folder')
})
}
const uploadByGithub = (content, filename) => {
const octokit = new Octokit({
auth: `token ${token}`
})
const path = dayjs().format('YYYY/MM') + `/${dayjs().format('DD-HH-mm-ss')}-${filename}`
const message = `Upload by Mark Text at ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`
var payload = {
owner,
repo,
path,
branch,
message,
content
}
if (!branch) {
delete payload.branch
}
octokit.repos.createFile(payload).then(result => {
re(result.data.content.download_url)
})
.catch(_ => {
rj('Upload failed, the image will be copied to the image folder')
})
}
const notification = () => {
rj('Cannot upload more than 5M image, the image will be copied to the image folder')
}
if (isPath) {
const dirname = path.dirname(pathname)
const imagePath = path.resolve(dirname, image)
const isImage = isImageFile(imagePath)
if (isImage) {
const { size } = await fs.stat(imagePath)
if (size > MAX_SIZE) {
notification()
} else {
const imageFile = await fs.readFile(imagePath)
const blobFile = new Blob([imageFile])
if (currentUploader === 'smms') {
uploadToSMMS(blobFile)
} else {
const base64 = Buffer.from(imageFile).toString('base64')
uploadByGithub(base64, path.basename(imagePath))
}
}
} else {
re(image)
}
} else {
const { size } = image
if (size > MAX_SIZE) {
notification()
} else {
const reader = new FileReader()
reader.onload = async () => {
const blobFile = dataURItoBlob(reader.result, image.name)
if (currentUploader === 'smms') {
uploadToSMMS(blobFile)
} else {
uploadByGithub(reader.result, image.name)
}
}
reader.readAsDataURL(image)
}
}
return promise
}