Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { computed, ref } from 'vue'
3 :
4 : import type { UserDataFullInfo } from '@comfyorg/api-client/types'
5 : import { api } from '@/scripts/api'
6 : import type { TreeExplorerNode } from '@/types/treeExplorerTypes'
7 : import { getPathDetails } from '@/utils/formatUtil'
8 : import { syncEntities } from '@/utils/syncUtil'
9 : import { buildTree } from '@/utils/treeUtil'
10 :
11 : /**
12 : * Normalizes a timestamp value that may be either a number (milliseconds)
13 : * or an ISO 8601 string (from Go's time.Time JSON serialization) into
14 : * a consistent millisecond timestamp.
15 : */
16 121 : function normalizeTimestamp(value: number | string): number {
17 121 : if (typeof value === 'string') {
18 0 : const ms = new Date(value).getTime()
19 0 : return Number.isNaN(ms) ? Date.now() : ms
20 : }
21 121 : return value
22 : }
23 :
24 : /**
25 : * Represents a file in the user's data directory.
26 : */
27 2356 : export class UserFile {
28 : /**
29 : * Various path components.
30 : * Example:
31 : * - path: 'dir/file.txt'
32 : * - directory: 'dir'
33 : * - fullFilename: 'file.txt'
34 : * - filename: 'file'
35 : * - suffix: 'txt'
36 : */
37 : directory: string
38 : fullFilename: string
39 : filename: string
40 : suffix: string | null
41 :
42 : isLoading: boolean = false
43 : content: string | null = null
44 : originalContent: string | null = null
45 :
46 : constructor(
47 : /**
48 : * Path relative to ComfyUI/user/ directory.
49 : */
50 268681 : public path: string,
51 : /**
52 : * Last modified timestamp.
53 : */
54 268681 : public lastModified: number,
55 : /**
56 : * File size in bytes. -1 for temporary files.
57 : */
58 268681 : public size: number
59 : ) {
60 268681 : const details = getPathDetails(path)
61 268681 : this.directory = details.directory
62 268681 : this.fullFilename = details.fullFilename
63 268681 : this.filename = details.filename
64 268681 : this.suffix = details.suffix
65 : }
66 :
67 : updatePath(newPath: string) {
68 100 : const details = getPathDetails(newPath)
69 100 : this.path = newPath
70 100 : this.directory = details.directory
71 100 : this.fullFilename = details.fullFilename
72 100 : this.filename = details.filename
73 100 : this.suffix = details.suffix
74 : }
75 :
76 : static createTemporary(path: string): UserFile {
77 0 : return new UserFile(path, Date.now(), -1)
78 : }
79 :
80 : get isTemporary() {
81 453091 : return this.size === -1
82 : }
83 :
84 : get isPersisted() {
85 136913 : return !this.isTemporary
86 : }
87 :
88 : get key(): string {
89 0 : return this.path
90 : }
91 :
92 : get isLoaded() {
93 0 : return this.content !== null
94 : }
95 :
96 : get isModified() {
97 0 : return this.content !== this.originalContent
98 : }
99 :
100 : /**
101 : * Loads the file content from the remote storage.
102 : */
103 : async load({
104 : force = false
105 : }: { force?: boolean } = {}): Promise<LoadedUserFile> {
106 266622 : if (this.isTemporary || (!force && this.isLoaded))
107 266346 : return this as LoadedUserFile
108 :
109 276 : this.isLoading = true
110 276 : const resp = await api.getUserData(this.path)
111 30330 : if (resp.status !== 200) {
112 0 : throw new Error(`Failed to load file: ${resp.status} ${resp.statusText}`)
113 : }
114 266 : this.content = await resp.text()
115 262 : this.originalContent = this.content
116 262 : this.isLoading = false
117 262 : return this as LoadedUserFile
118 : }
119 :
120 : /**
121 : * Unloads the file content from memory
122 : */
123 : unload(): void {
124 31 : this.content = null
125 31 : this.originalContent = null
126 31 : this.isLoading = false
127 : }
128 :
129 : async saveAs(newPath: string): Promise<UserFile> {
130 0 : const tempFile = this.isTemporary ? this : UserFile.createTemporary(newPath)
131 0 : tempFile.content = this.content
132 0 : await tempFile.save()
133 0 : return tempFile
134 : }
135 :
136 : /**
137 : * Saves the file to the remote storage.
138 : * @param force Whether to force the save even if the file is not modified.
139 : */
140 : async save({ force = false }: { force?: boolean } = {}): Promise<UserFile> {
141 122 : if (this.isPersisted && !this.isModified && !force) return this
142 :
143 : const resp = await api.storeUserData(this.path, this.content, {
144 : overwrite: this.isPersisted,
145 : throwOnError: true,
146 : full_info: true
147 : })
148 :
149 : // Note: Backend supports full_info=true feature after
150 : // https://github.com/comfyanonymous/ComfyUI/pull/5446
151 122 : const updatedFile = (await resp.json()) as string | UserDataFullInfo
152 121 : if (typeof updatedFile === 'object') {
153 121 : this.lastModified = normalizeTimestamp(updatedFile.modified)
154 121 : this.size = updatedFile.size
155 : }
156 121 : this.originalContent = this.content
157 121 : return this
158 : }
159 :
160 : async delete(): Promise<void> {
161 19 : if (this.isTemporary) return
162 :
163 19 : const resp = await api.deleteUserData(this.path)
164 19 : if (resp.status !== 204) {
165 0 : throw new Error(
166 : `Failed to delete file '${this.path}': ${resp.status} ${resp.statusText}`
167 : )
168 : }
169 : }
170 :
171 : async rename(newPath: string): Promise<UserFile> {
172 100 : if (this.isTemporary) {
173 98 : this.updatePath(newPath)
174 98 : return this
175 : }
176 :
177 2 : const resp = await api.moveUserData(this.path, newPath)
178 8 : if (resp.status !== 200) {
179 0 : throw new Error(
180 : `Failed to rename file '${this.path}': ${resp.status} ${resp.statusText}`
181 : )
182 : }
183 2 : this.updatePath(newPath)
184 : // Note: Backend supports full_info=true feature after
185 : // https://github.com/comfyanonymous/ComfyUI/pull/5446
186 2 : const updatedFile = (await resp.json()) as string | UserDataFullInfo
187 3 : if (typeof updatedFile === 'object') {
188 0 : this.lastModified = normalizeTimestamp(updatedFile.modified)
189 0 : this.size = updatedFile.size
190 : }
191 2 : return this
192 : }
193 : }
194 :
195 : interface LoadedUserFile extends UserFile {
196 : isLoaded: true
197 : originalContent: string
198 : content: string
199 : }
200 :
201 2356 : export const useUserFileStore = defineStore('userFile', () => {
202 0 : const userFilesByPath = ref<Record<string, UserFile>>({})
203 :
204 0 : const userFiles = computed(() => Object.values(userFilesByPath.value))
205 0 : const modifiedFiles = computed(() =>
206 : userFiles.value.filter((file: UserFile) => file.isModified)
207 : )
208 0 : const loadedFiles = computed(() =>
209 : userFiles.value.filter((file: UserFile) => file.isLoaded)
210 : )
211 :
212 0 : const fileTree = computed<TreeExplorerNode<UserFile>>(() =>
213 : buildTree<UserFile>(userFiles.value, (userFile: UserFile) =>
214 : userFile.path.split('/')
215 : )
216 : )
217 :
218 : /**
219 : * Syncs the files in the given directory with the API.
220 : * @param dir The directory to sync.
221 : */
222 0 : const syncFiles = async (dir: string = '') => {
223 0 : await syncEntities(
224 : dir,
225 : userFilesByPath.value,
226 : (file) => new UserFile(file.path, file.modified, file.size),
227 : (existingFile, file) => {
228 0 : existingFile.lastModified = file.modified
229 0 : existingFile.size = file.size
230 0 : existingFile.unload()
231 : }
232 : )
233 : }
234 :
235 0 : return {
236 : userFiles,
237 : modifiedFiles,
238 : loadedFiles,
239 : fileTree,
240 : syncFiles
241 : }
242 : })
|