misskey/src/server/api/endpoints/sw/register.ts

57 lines
1.0 KiB
TypeScript
Raw Normal View History

2017-11-20 19:40:09 +01:00
import $ from 'cafy';
2018-03-29 13:32:18 +02:00
import Subscription from '../../../../models/sw-subscription';
2018-06-18 02:54:53 +02:00
import { ILocalUser } from '../../../../models/user';
2018-09-01 01:13:18 +02:00
import config from '../../../../config';
2018-11-02 04:49:08 +01:00
import getParams from '../../get-params';
2017-11-20 19:40:09 +01:00
2018-07-16 21:36:44 +02:00
export const meta = {
2018-11-02 04:49:08 +01:00
requireCredential: true,
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
}
}
};
2017-11-20 19:40:09 +01:00
2018-11-02 04:49:08 +01:00
export default async (params: any, user: ILocalUser) => new Promise(async (res, rej) => {
const [ps, psErr] = getParams(meta, params);
if (psErr) return rej(psErr);
2017-11-20 19:40:09 +01:00
// if already subscribed
const exist = await Subscription.findOne({
2018-03-29 07:48:47 +02:00
userId: user._id,
2018-11-02 04:49:08 +01:00
endpoint: ps.endpoint,
auth: ps.auth,
publickey: ps.publickey,
2018-03-29 07:48:47 +02:00
deletedAt: { $exists: false }
2017-11-20 19:40:09 +01:00
});
2018-09-01 01:13:18 +02:00
if (exist != null) {
return res({
state: 'already-subscribed',
key: config.sw.public_key
});
2017-11-20 19:40:09 +01:00
}
await Subscription.insert({
2018-03-29 07:48:47 +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
});
2018-09-01 01:13:18 +02:00
res({
state: 'subscribed',
key: config.sw.public_key
});
2017-11-20 19:40:09 +01:00
});