-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathavatars.js
More file actions
244 lines (204 loc) · 6.31 KB
/
Copy pathavatars.js
File metadata and controls
244 lines (204 loc) · 6.31 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
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
const { PassThrough } = require('stream');
const { URL } = require('url');
const pump = require('pump');
const isStream = require('is-stream');
const imageType = require('image-type');
const props = require('p-props');
const DefaultStore = require('fs-blob-store');
const PermissionError = require('../errors/PermissionError');
function toImageStream(input) {
const output = new PassThrough();
input.pipe(output);
return new Promise((resolve, reject) => {
input.once('data', (chunk) => {
const type = imageType(chunk);
if (!type) {
input.destroy();
output.destroy();
reject(new Error('toImageStream: Not an image.'));
}
if (type.mime !== 'image/png' && type.mime !== 'image/jpeg') {
input.destroy();
output.destroy();
reject(new Error('toImageStream: Only PNG and JPEG are allowed.'));
}
Object.assign(output, type);
resolve(output);
});
});
}
async function assertPermission(user, permission) {
const allowed = await user.can(permission);
if (!allowed) {
throw new PermissionError(`User does not have the "${permission}" role.`);
}
return true;
}
const defaultOptions = {
sigil: true,
store: null,
};
class Avatars {
constructor(uw, options) {
this.uw = uw;
this.options = { ...defaultOptions, ...options };
this.store = this.options.store;
if (typeof this.store === 'string') {
this.store = new DefaultStore({
path: this.store,
});
}
if (typeof this.store === 'object' && this.store != null
&& typeof this.options.publicPath !== 'string') {
throw new TypeError('`publicPath` is not set, but it is required because `store` is set.');
}
this.magicAvatars = new Map();
if (this.options.sigil) {
this.addMagicAvatar(
'sigil',
user => `https://sigil.u-wave.net/${user.id}`,
);
}
}
/**
* Define an avatar type, that can generate avatar URLs for
* any user. eg. gravatar or an identicon service
*/
addMagicAvatar(name, generator) {
if (this.magicAvatars.has(name)) {
throw new Error(`Magic avatar "${name}" already exists.`);
}
if (typeof name !== 'string') {
throw new Error('Magic avatar name must be a string.');
}
if (typeof generator !== 'function') {
throw new Error('Magic avatar generator must be a function.');
}
this.magicAvatars.set(name, generator);
}
/**
* Get the available magic avatars for a user.
*/
async getMagicAvatars(userID) {
const { users } = this.uw;
const user = await users.getUser(userID);
const promises = new Map();
this.magicAvatars.forEach((generator, name) => {
promises.set(name, generator(user));
});
const avatars = await props(promises);
return Array.from(avatars).map(([name, url]) => ({
type: 'magic',
name,
url,
})).filter(({ url }) => url != null);
}
async setMagicAvatar(userID, name) {
const { users } = this.uw;
if (!this.magicAvatars.has(name)) {
throw new Error(`Magic avatar ${name} does not exist.`);
}
const user = await users.getUser(userID);
const generator = this.magicAvatars.get(name);
const url = await generator(user);
await user.update({ avatar: url });
}
/**
* Get the available social avatars for a user.
*/
async getSocialAvatars(userID) {
const { users } = this.uw;
const { Authentication } = this.uw.models;
const user = await users.getUser(userID);
const socialAvatars = await Authentication
.find({
$comment: 'Find social avatars for a user.',
user,
type: { $ne: 'local' },
avatar: { $exists: true, $ne: null },
})
.select({ type: true, avatar: true })
.lean();
return socialAvatars.map(({ type, avatar }) => ({
type: 'social',
service: type,
url: avatar,
}));
}
/**
* Use the avatar from the given third party service.
*/
async setSocialAvatar(userID, service) {
const { users } = this.uw;
const { Authentication } = this.uw.models;
const user = await users.getUser(userID);
const auth = await Authentication.findOne({ user, type: service });
if (!auth || !auth.avatar) {
throw new Error(`No avatar available for ${service}.`);
}
try {
new URL(auth.avatar); // eslint-disable-line no-new
} catch {
throw new Error(`Invalid avatar URL for ${service}.`);
}
await user.setAvatar(auth.avatar);
}
/**
* Check if custom avatar support is enabled.
*/
supportsCustomAvatars() {
return typeof this.options.publicPath === 'string'
&& typeof this.store === 'object';
}
/**
* Use a custom avatar, read from a stream.
*/
async setCustomAvatar(userID, stream) {
const { users } = this.uw;
if (!this.supportsCustomAvatars()) {
throw new PermissionError('Custom avatars are not enabled.');
}
const user = await users.getUser(userID);
await assertPermission(user, 'avatar.custom');
if (!isStream(stream)) {
throw new TypeError('Custom avatar must be a stream (eg. a http Request instance).');
}
const imageStream = await toImageStream(stream);
const metadata = await new Promise((resolve, reject) => {
const writeStream = this.store.createWriteStream({
key: `${user.id}.${imageStream.type}`,
}, (err, meta) => {
if (err) reject(err);
else resolve(meta);
});
pump(imageStream, writeStream);
});
const finalKey = metadata.key;
const url = new URL(finalKey, this.options.publicPath);
await user.setAvatar(url);
}
async getAvailableAvatars(userID) {
const { users } = this.uw;
const user = await users.getUser(userID);
const all = await Promise.all([
this.getMagicAvatars(user),
this.getSocialAvatars(user),
]);
// flatten
return [].concat(...all);
}
async setAvatar(userID, avatar) {
if (avatar.type === 'magic') {
return this.setMagicAvatar(userID, avatar.name);
}
if (avatar.type === 'social') {
return this.setSocialAvatar(userID, avatar.service);
}
throw new Error(`Unknown avatar type "${avatar.type}"`);
}
}
module.exports = function avatarsPlugin(options = {}) {
return (uw) => {
uw.avatars = new Avatars(uw, options); // eslint-disable-line no-param-reassign
};
}