2017-11-20 19:40:09 +01:00
|
|
|
import $ from 'cafy';
|
2018-11-02 05:47:44 +01:00
|
|
|
import define from '../../define';
|
2019-04-24 01:11:19 +02:00
|
|
|
import { fetchMeta } from '../../../../misc/fetch-meta';
|
2019-04-07 14:50:36 +02:00
|
|
|
import { genId } from '../../../../misc/gen-id';
|
|
|
|
import { SwSubscriptions } from '../../../../models';
|
2017-11-20 19:40:09 +01:00
|
|
|
|
2018-07-16 21:36:44 +02:00
|
|
|
export const meta = {
|
2019-02-23 03:20:58 +01:00
|
|
|
tags: ['account'],
|
|
|
|
|
2020-02-15 13:33:32 +01:00
|
|
|
requireCredential: true as const,
|
2018-07-16 21:36:44 +02:00
|
|
|
|
2018-11-02 04:49:08 +01:00
|
|
|
params: {
|
|
|
|
endpoint: {
|
|
|
|
validator: $.str
|
|
|
|
},
|
|
|
|
|
|
|
|
auth: {
|
|
|
|
validator: $.str
|
|
|
|
},
|
2017-11-20 19:40:09 +01:00
|
|
|
|
2018-11-02 04:49:08 +01:00
|
|
|
publickey: {
|
|
|
|
validator: $.str
|
|
|
|
}
|
2021-03-06 14:34:11 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
res: {
|
|
|
|
type: 'object' as const,
|
|
|
|
optional: false as const, nullable: false as const,
|
|
|
|
properties: {
|
|
|
|
state: {
|
|
|
|
type: 'string' as const,
|
|
|
|
optional: false as const, nullable: false as const,
|
|
|
|
enum: ['already-subscribed', 'subscribed']
|
|
|
|
},
|
|
|
|
key: {
|
|
|
|
type: 'string' as const,
|
|
|
|
optional: false as const, nullable: false as const
|
|
|
|
}
|
|
|
|
}
|
2018-11-02 04:49:08 +01:00
|
|
|
}
|
|
|
|
};
|
2017-11-20 19:40:09 +01:00
|
|
|
|
2019-02-22 03:46:58 +01:00
|
|
|
export default define(meta, async (ps, user) => {
|
2017-11-20 19:40:09 +01:00
|
|
|
// if already subscribed
|
2019-04-07 14:50:36 +02:00
|
|
|
const exist = await SwSubscriptions.findOne({
|
|
|
|
userId: user.id,
|
2018-11-02 04:49:08 +01:00
|
|
|
endpoint: ps.endpoint,
|
|
|
|
auth: ps.auth,
|
|
|
|
publickey: ps.publickey,
|
2017-11-20 19:40:09 +01:00
|
|
|
});
|
|
|
|
|
2019-04-24 01:11:19 +02:00
|
|
|
const instance = await fetchMeta(true);
|
2018-12-19 20:08:13 +01:00
|
|
|
|
2018-09-01 01:13:18 +02:00
|
|
|
if (exist != null) {
|
2019-02-22 03:46:58 +01:00
|
|
|
return {
|
2018-09-01 01:13:18 +02:00
|
|
|
state: 'already-subscribed',
|
2018-12-19 20:08:13 +01:00
|
|
|
key: instance.swPublicKey
|
2019-02-22 03:46:58 +01:00
|
|
|
};
|
2017-11-20 19:40:09 +01:00
|
|
|
}
|
|
|
|
|
2021-03-21 13:27:09 +01:00
|
|
|
await SwSubscriptions.insert({
|
2019-04-07 14:50:36 +02:00
|
|
|
id: genId(),
|
2019-04-15 09:37:54 +02:00
|
|
|
createdAt: new Date(),
|
2019-04-07 14:50:36 +02:00
|
|
|
userId: user.id,
|
2018-11-02 04:49:08 +01:00
|
|
|
endpoint: ps.endpoint,
|
|
|
|
auth: ps.auth,
|
|
|
|
publickey: ps.publickey
|
2017-11-20 19:40:09 +01:00
|
|
|
});
|
|
|
|
|
2019-02-22 03:46:58 +01:00
|
|
|
return {
|
2018-09-01 01:13:18 +02:00
|
|
|
state: 'subscribed',
|
2018-12-19 20:08:13 +01:00
|
|
|
key: instance.swPublicKey
|
2019-02-22 03:46:58 +01:00
|
|
|
};
|
|
|
|
});
|