-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathalexandria-documents.js
215 lines (193 loc) · 6.29 KB
/
alexandria-documents.js
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
import { action } from "@ember/object";
import Service, { inject as service } from "@ember/service";
import { tracked } from "@glimmer/tracking";
import { task } from "ember-concurrency";
import { saveAs } from "file-saver";
import mime from "mime";
import { ErrorHandler } from "ember-alexandria/utils/error-handler";
export default class AlexandriaDocumentsService extends Service {
@service store;
@service("alexandria-config") config;
@service router;
@service notification;
@service intl;
@service fetch;
@tracked selectedDocuments = [];
@tracked shortcutsDisabled = false;
constructor(...args) {
super(...args);
// Initialise the selected documents based on the query params of the route
const documentQueryParam =
this.router.externalRouter?.currentRoute?.queryParams?.document;
if (documentQueryParam) {
documentQueryParam.split(",").map(async (id) => {
this.selectDocument(await this.store.findRecord("document", id));
});
}
}
/**
* Updates the route depending to reflect the currently selected documents
*/
updateRoute() {
const docs =
this.selectedDocuments.length === 0
? undefined
: this.selectedDocuments.map((d) => d.id);
this.router.transitionTo(this.router.currentRouteName, {
queryParams: {
document: docs,
},
});
}
/**
* Uploads one or multiple files and creates the necessary document and
* files entries on the API.
*
* @param {Object|String|Number} category Either an ID or category instance.
* @param {Array<File>} files The file(s) from input[type=file].
*/
async upload(category, files) {
if (!category.id) {
category =
this.store.peekRecord("category", category) ||
(await this.store.findRecord("category", category));
}
for (const file of files) {
if (
category.allowedMimeTypes &&
!category.allowedMimeTypes.includes(
file.type ?? mime.getType(file.name.split(".").pop()),
)
) {
return this.notification.danger(
this.intl.t("alexandria.errors.invalid-file-type", {
category: category.name,
types: category.allowedMimeTypes
.map((t) => mime.getExtension(t))
.join(", "),
}),
);
}
}
try {
const uploaded = await Promise.all(
Array.from(files).map(async (file) => {
const documentModel = this.store.createRecord("document", {
category,
metainfo: this.config.defaultModelMeta.document,
createdByGroup: this.config.activeGroup,
modifiedByGroup: this.config.activeGroup,
content: file,
});
// must be set outside for localized model
documentModel.title = file.name;
await documentModel.save();
return documentModel;
}),
);
this.notification.success(
this.intl.t("alexandria.success.upload-document", {
count: files.length,
}),
);
return uploaded;
} catch (error) {
new ErrorHandler(this, error).notify(
"alexandria.errors.upload-document",
{
count: files.length,
},
);
}
}
/**
* Uploads a new version of a file and creates the necessary API entry.
*
* @param {Object} document A document instance.
* @param {File} file The file from input[type=file].
*/
async replace(document, file) {
const fileModel = this.store.createRecord("file", {
name: file.name,
variant: "original",
document,
createdByGroup: this.config.activeGroup,
modifiedByGroup: this.config.activeGroup,
content: file,
});
await fileModel.save();
}
/**
* Clears the document selection
*/
@action clearDocumentSelection() {
this.selectedDocuments = [];
this.updateRoute();
}
/**
* Checks if the document is selected
*
* @param {Object} doc an EmberData representation of a Document
* @returns {Boolean} If the document is selected
*/
@action documentIsSelected(doc) {
return !!this.selectedDocuments.find((d) => d.id === doc.id);
}
/**
* Selects the document
* @param {Object} doc an EmberData representation of a Document
*/
@action selectDocument(doc) {
if (!this.selectedDocuments.includes(doc)) {
this.selectedDocuments = [...this.selectedDocuments, doc];
this.updateRoute();
}
}
/**
* Removes a document from the document selection
* @param {Object} doc an EmberData representation of a Document
*/
@action deselectDocument(doc) {
this.selectedDocuments = this.selectedDocuments.filter(
(d) => d.id !== doc.id,
);
this.updateRoute();
}
enableShortcuts() {
this.shortcutsDisabled = false;
}
disableShortcuts() {
this.shortcutsDisabled = true;
}
download = task({ drop: true }, async (documents) => {
try {
if (documents.length === 1) {
const doc = documents[0];
await doc.reload(); // always reload the document to get the latest file (webdav)
await doc.latestFile.promise;
const file = doc.latestFile.value;
return await file.download.perform();
}
// If we want to save a zip of files we need to do some more stuff
// Compile an array of original file PKs
const originalFilePKs = encodeURIComponent(
documents.map((doc) => doc.latestFile.value.id).join(","),
);
let url = this.config?.zipDownloadHost || ""; // in case we need to send the zipDownload to another URL
url += this.config?.zipDownloadNamespace || ""; // in case we need to namespace the alexandria api
url += "/api/v1/files/multi";
url += `?filter[files]=${originalFilePKs}`; // list of files we want to download
// Some alexandria applications require the document-meta as well
if (this.config.modelMetaFilters.document) {
url += `&filter[document-metainfo]=${encodeURIComponent(
JSON.stringify(this.config.modelMetaFilters.document),
)}`;
}
const transfer = await this.fetch.fetch(url, { mode: "cors" });
const bytes = await transfer.blob();
saveAs(bytes, `Download-${documents.length}-files.zip`);
} catch (error) {
new ErrorHandler(this, error).notify("alexandria.errors.save-file");
}
});
}