forked from fluidd-core/fluidd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.ts
283 lines (242 loc) · 8.12 KB
/
files.ts
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
import type { AppFile, FilesUpload, AppFileThumbnail, KlipperFileMeta } from '@/store/files/types'
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import type { AxiosRequestConfig, AxiosProgressEvent } from 'axios'
import { httpClientActions } from '@/api/httpClientActions'
import type { FileWithPath } from '@/types'
import consola from 'consola'
@Component
export default class FilesMixin extends Vue {
get apiUrl (): string {
return this.$store.state.config.apiUrl as string
}
get isTrustedUser (): boolean {
return this.$store.getters['auth/getCurrentUser']?.username === '_TRUSTED_USER_'
}
getThumbUrl (meta: KlipperFileMeta, root: string, path: string, large: boolean, date?: number) {
const thumb = this.getThumb(meta, root, path, large, date)
return thumb?.url ?? ''
}
getThumb (meta: KlipperFileMeta, root: string, path: string, large = true, date?: number): AppFileThumbnail | undefined {
if (meta.thumbnails?.length) {
const thumb = meta.thumbnails.reduce((a, b) => (a.size > b.size) === large ? a : b)
if (thumb.relative_path) {
const filepath = path ? `${root}/${path}` : root
return {
...thumb,
url: this.createFileUrl(thumb.relative_path, filepath, date)
}
}
}
}
/**
* Loads a gcode file and parses for the gcode-viewer.
*/
async getGcode (file: AppFile) {
const sizeInMB = file.size / 1024 / 1024
const result = (
sizeInMB < 100 ||
await this.$confirm(
this.$t('app.gcode.msg.confirm', {
filename: file.filename,
size: this.$filters.getReadableFileSizeString(file.size)
}).toString(), {
title: this.$tc('app.general.title.gcode_preview'),
color: 'card-heading',
icon: '$error'
})
)
if (result) {
const path = file.path ? `gcodes/${file.path}` : 'gcodes'
return await this.getFile<string>(file.filename, path, file.size, {
responseType: 'text',
transformResponse: [v => v]
})
}
}
/**
* Will retrieve a file blob for independent processing.
* @param filename The filename to retrieve
* @param path The path to the file
*/
async getFile<T = any> (filename: string, path: string, size = 0, options?: AxiosRequestConfig) {
// Sort out the filepath
const filepath = path ? `${path}/${filename}` : filename
try {
const abortController = new AbortController()
// Add an entry to vuex indicating we're downloading a file.
this.$store.dispatch('files/updateFileDownload', {
filepath,
size,
loaded: 0,
percent: 0,
speed: 0,
abortController
})
const response = await httpClientActions.serverFilesGet<T>(filepath, {
...options,
signal: abortController.signal,
onDownloadProgress: (event: AxiosProgressEvent) => {
if (abortController.signal.aborted) {
return
}
const progress = event.progress ?? (
size > 0
? event.loaded / size
: 0
)
const payload: any = {
filepath,
loaded: event.loaded,
percent: Math.round(progress * 100),
speed: event.rate ?? 0
}
if (event.total) {
size = payload.size = event.total
}
this.$store.dispatch('files/updateFileDownload', payload)
}
})
abortController.abort()
return response
} finally {
this.$store.dispatch('files/removeFileDownload')
}
}
/**
* Will download a file by filepath via a standard browser link.
* @param filename The filename to retrieve.
* @param path The path to the file.
*/
async downloadFile (filename: string, path: string) {
// Grab a oneshot.
try {
const url = await this.createFileUrlWithToken(filename, path)
// Create a link, handle its click - and finally remove it again.
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
link.setAttribute('target', '_blank')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// Likely a 401.
}
}
/**
* Creates a url for a file by filepath.
* Implements a oneshot.
* @param filename The filename.
* @param path The path to the file.
* @returns The url for the requested file
*/
createFileUrl (filename: string, path: string, date?: number) {
const filepath = (path) ? `${path}/${filename}` : `${filename}`
return `${this.apiUrl}/server/files/${encodeURI(filepath)}?date=${date || Date.now()}`
}
async createFileUrlWithToken (filename: string, path: string, date?: number) {
const url = this.createFileUrl(filename, path, date)
return this.isTrustedUser
? url
: `${url}&token=${(await httpClientActions.accessOneshotTokenGet()).data.result}`
}
/**
* Uploads a single file via moonraker.
* @param file The file object. Contains the filename.
* @param path The path we're uploading to.
* @param root The root we're downloading from.
* @param andPrint If we should attempt to print this file or not.
* @param options Axios request options
*/
async uploadFile (file: File, path: string, root: string, andPrint: boolean, options?: AxiosRequestConfig) {
const filepath = path
? `${path}/${file.name}`
: file.name
try {
const abortController = new AbortController()
this.$store.dispatch('files/updateFileUpload', {
filepath,
size: file.size,
loaded: 0,
percent: 0,
speed: 0,
cancelled: false,
abortController
})
const response = await httpClientActions.serverFilesUploadPost(file, path, root, andPrint, {
...options,
signal: abortController.signal,
onUploadProgress: (event: AxiosProgressEvent) => {
if (abortController.signal.aborted) {
return
}
this.$store.dispatch('files/updateFileUpload', {
filepath,
loaded: event.loaded,
percent: event.progress ? Math.round(event.progress * 100) : 0,
speed: event.rate ?? 0
})
}
})
abortController.abort()
return response
} finally {
this.$store.dispatch('files/removeFileUpload', filepath)
}
}
getFullPathAndFile (rootPath: string, file: File | FileWithPath): [string, File] {
if ('path' in file) {
return [
[rootPath, file.path]
.filter(path => !!path)
.join('/'),
file.file
]
} else {
return [
rootPath,
file
]
}
}
// Upload some files.
async uploadFiles (files: FileList | File[] | FileWithPath[], path: string, root: string, andPrint: boolean) {
// For each file, adds the associated state.
for (const file of files) {
const [fullPath, fileObject] = this.getFullPathAndFile(path, file)
const filepath = fullPath
? `${fullPath}/${fileObject.name}`
: fileObject.name
this.$store.dispatch('files/updateFileUpload', {
filepath,
size: fileObject.size,
loaded: 0,
percent: 0,
speed: 0,
unit: 'kB',
cancelled: false
})
}
// Async uploads cause issues in moonraker / klipper.
// So instead, upload sequentially waiting for moonraker to finish
// processing of each file.
if (files.length > 1) andPrint = false
for (const file of files) {
const [fullPath, fileObject] = this.getFullPathAndFile(path, file)
const filepath = fullPath
? `${fullPath}/${fileObject.name}`
: fileObject.name
const fileState = this.$store.state.files.uploads.find((u: FilesUpload) => u.filepath === filepath)
if (fileState && !fileState?.cancelled) {
try {
await this.uploadFile(fileObject, fullPath, root, andPrint)
} catch (error: unknown) {
consola.error('[FileUpload] file', error)
}
} else {
this.$store.dispatch('files/removeFileUpload', filepath)
}
}
}
}