-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.ts
56 lines (47 loc) · 1.6 KB
/
convert.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
import { Buffer } from 'buffer'
import Long from 'long'
import beapi from '@berty/api'
import { ParsedInteraction } from './types.gen'
export const parseInteraction = (
i: beapi.messenger.IInteraction | beapi.messenger.Interaction,
): ParsedInteraction => {
try {
if (typeof (i as any).toJSON === 'function') {
i = (i as any).toJSON()
}
const typeName =
beapi.messenger.AppMessage.Type[i.type || beapi.messenger.AppMessage.Type.Undefined]
if (!typeName) {
console.warn('failed to get AppMessage type name', i.type)
return { ...i, type: beapi.messenger.AppMessage.Type.Undefined, payload: undefined }
}
const name = typeName.substring('Type'.length)
const pbobj = (beapi.messenger.AppMessage as any)[name as any]
if (!pbobj) {
throw new Error(`pbobj not found for ${typeName}`)
}
let pl = i.payload
if (typeof pl === 'string') {
pl = Buffer.from(pl, 'base64')
}
const { member, conversation, ...rest } = i // eslint-disable-line @typescript-eslint/no-unused-vars
return {
...rest,
type:
(beapi.messenger.AppMessage.Type[typeName as any] as unknown as number) ||
beapi.messenger.AppMessage.Type.Undefined,
payload: pl && pbobj.decode(pl).toJSON(),
}
} catch (err) {
console.log('failed to parse interaction:', i, err)
return { ...i, type: beapi.messenger.AppMessage.Type.Undefined, payload: undefined }
}
}
export const pbDateToNum = (pbTimestamp?: number | Long | string | null): number => {
try {
return !pbTimestamp ? 0 : parseInt(pbTimestamp as string, 10)
} catch (e) {
console.warn(`Error parsing date ${pbTimestamp}; returning zero`)
return 0
}
}