-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
phase3-sticker-functions.ts
247 lines (212 loc) · 6.67 KB
/
phase3-sticker-functions.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
// Copyright 2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import sharp from 'sharp';
import pify from 'pify';
import { readFile } from 'fs';
import { noop, uniqBy } from 'lodash';
import { ipcRenderer as ipc } from 'electron';
import {
deriveStickerPackKey,
encryptAttachment,
getRandomBytes,
} from '../../ts/Crypto';
import * as Bytes from '../../ts/Bytes';
import { SignalService as Proto } from '../../ts/protobuf';
import { initialize as initializeWebAPI } from '../../ts/textsecure/WebAPI';
import { SignalContext } from '../../ts/windows/context';
import { getAnimatedPngDataIfExists } from '../../ts/util/getAnimatedPngDataIfExists';
const STICKER_SIZE = 512;
const MIN_STICKER_DIMENSION = 10;
const MAX_STICKER_DIMENSION = STICKER_SIZE;
const MAX_STICKER_BYTE_LENGTH = 300 * 1024;
const { config } = SignalContext;
const WebAPI = initializeWebAPI({
url: config.serverUrl,
storageUrl: config.storageUrl,
updatesUrl: config.updatesUrl,
resourcesUrl: config.resourcesUrl,
directoryConfig: config.directoryConfig,
cdnUrlObject: {
0: config.cdnUrl0,
2: config.cdnUrl2,
},
certificateAuthority: config.certificateAuthority,
contentProxyUrl: config.contentProxyUrl,
proxyUrl: config.proxyUrl,
version: config.version,
});
function processStickerError(message: string, i18nKey: string): Error {
const result = new Error(message);
result.errorMessageI18nKey = i18nKey;
return result;
}
window.processStickerImage = async (path: string | undefined) => {
if (!path) {
throw new Error(`Path ${path} is not valid!`);
}
const imgBuffer = await pify(readFile)(path);
const sharpImg = sharp(imgBuffer);
const meta = await sharpImg.metadata();
const { width, height } = meta;
if (!width || !height) {
throw processStickerError(
'Sticker height or width were falsy',
'StickerCreator--Toasts--errorProcessing'
);
}
let contentType;
let processedBuffer;
// [Sharp doesn't support APNG][0], so we do something simpler: validate the file size
// and dimensions without resizing, cropping, or converting. In a perfect world, we'd
// resize and convert any animated image (GIF, animated WebP) to APNG.
// [0]: https://github.com/lovell/sharp/issues/2375
const animatedPngDataIfExists = getAnimatedPngDataIfExists(imgBuffer);
if (animatedPngDataIfExists) {
if (imgBuffer.byteLength > MAX_STICKER_BYTE_LENGTH) {
throw processStickerError(
'Sticker file was too large',
'StickerCreator--Toasts--tooLarge'
);
}
if (width !== height) {
throw processStickerError(
'Sticker must be square',
'StickerCreator--Toasts--APNG--notSquare'
);
}
if (width > MAX_STICKER_DIMENSION) {
throw processStickerError(
'Sticker dimensions are too large',
'StickerCreator--Toasts--APNG--dimensionsTooLarge'
);
}
if (width < MIN_STICKER_DIMENSION) {
throw processStickerError(
'Sticker dimensions are too small',
'StickerCreator--Toasts--APNG--dimensionsTooSmall'
);
}
if (animatedPngDataIfExists.numPlays !== Infinity) {
throw processStickerError(
'Animated stickers must loop forever',
'StickerCreator--Toasts--mustLoopForever'
);
}
contentType = 'image/png';
processedBuffer = imgBuffer;
} else {
contentType = 'image/webp';
processedBuffer = await sharpImg
.resize({
width: STICKER_SIZE,
height: STICKER_SIZE,
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.webp()
.toBuffer();
if (processedBuffer.byteLength > MAX_STICKER_BYTE_LENGTH) {
throw processStickerError(
'Sticker file was too large',
'StickerCreator--Toasts--tooLarge'
);
}
}
return {
path,
buffer: processedBuffer,
src: `data:${contentType};base64,${processedBuffer.toString('base64')}`,
meta,
};
};
window.encryptAndUpload = async (
manifest,
stickers,
cover,
onProgress = noop
) => {
const usernameItem = await window.Signal.Data.getItemById('uuid_id');
const oldUsernameItem = await window.Signal.Data.getItemById('number_id');
const passwordItem = await window.Signal.Data.getItemById('password');
const username = usernameItem?.value || oldUsernameItem?.value;
if (!username || !passwordItem?.value) {
const { message } =
window.localeMessages['StickerCreator--Authentication--error'];
ipc.send('show-message-box', {
type: 'warning',
message,
});
throw new Error(message);
}
const { value: password } = passwordItem;
const packKey = getRandomBytes(32);
const encryptionKey = deriveStickerPackKey(packKey);
const iv = getRandomBytes(16);
const server = WebAPI.connect({
username,
password,
useWebSocket: false,
hasStoriesDisabled: true,
});
const manifestProto = new Proto.StickerPack();
manifestProto.title = manifest.title;
manifestProto.author = manifest.author;
manifestProto.stickers = stickers.map(({ emoji }, id) => {
const s = new Proto.StickerPack.Sticker();
s.id = id;
if (emoji) {
s.emoji = emoji;
}
return s;
});
const uniqueStickers = uniqBy(
[...stickers, { imageData: cover }],
'imageData'
);
const coverStickerIndex = uniqueStickers.findIndex(
item => item.imageData?.src === cover.src
);
const coverStickerId = coverStickerIndex >= 0 ? coverStickerIndex : 0;
const coverStickerData = stickers[coverStickerId];
if (!coverStickerData) {
window.SignalContext.log.warn(
'encryptAndUpload: No coverStickerData with ' +
`index ${coverStickerId} and ${stickers.length} total stickers`
);
}
const coverSticker = new Proto.StickerPack.Sticker();
coverSticker.id = coverStickerId;
if (coverStickerData?.emoji && coverSticker) {
coverSticker.emoji = coverStickerData.emoji;
} else {
coverSticker.emoji = '';
}
manifestProto.cover = coverSticker;
const encryptedManifest = await encrypt(
Proto.StickerPack.encode(manifestProto).finish(),
encryptionKey,
iv
);
const encryptedStickers = uniqueStickers.map(({ imageData }) => {
if (!imageData?.buffer) {
throw new Error('encryptStickers: Missing image data on sticker');
}
return encrypt(imageData.buffer, encryptionKey, iv);
});
const packId = await server.putStickers(
encryptedManifest,
encryptedStickers,
onProgress
);
const hexKey = Bytes.toHex(packKey);
ipc.send('install-sticker-pack', packId, hexKey);
return { packId, key: hexKey };
};
function encrypt(
data: Uint8Array,
key: Uint8Array,
iv: Uint8Array
): Uint8Array {
const { ciphertext } = encryptAttachment(data, key, iv);
return ciphertext;
}