privatemessages_model.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const pull = require('../server/node_modules/pull-stream');
  2. const util = require('../server/node_modules/util');
  3. module.exports = ({ cooler }) => {
  4. let ssb;
  5. let userId;
  6. const openSsb = async () => {
  7. if (!ssb) {
  8. ssb = await cooler.open();
  9. userId = ssb.id;
  10. }
  11. return ssb;
  12. };
  13. return {
  14. type: 'post',
  15. async sendMessage(recipients = [], subject = '', text = '') {
  16. const ssbClient = await openSsb();
  17. const content = {
  18. type: 'post',
  19. from: userId,
  20. to: recipients,
  21. subject,
  22. text,
  23. sentAt: new Date().toISOString(),
  24. private: true
  25. };
  26. const publishAsync = util.promisify(ssbClient.private.publish);
  27. return publishAsync(content, recipients);
  28. },
  29. async deleteMessageById(messageId) {
  30. const ssbClient = await openSsb();
  31. const rawMsg = await new Promise((resolve, reject) =>
  32. ssbClient.get(messageId, (err, m) =>
  33. err ? reject(new Error("Error retrieving message.")) : resolve(m)
  34. )
  35. );
  36. let decrypted;
  37. try {
  38. decrypted = ssbClient.private.unbox({
  39. key: messageId,
  40. value: rawMsg,
  41. timestamp: rawMsg.timestamp || Date.now()
  42. });
  43. } catch {
  44. throw new Error("Malformed message.");
  45. }
  46. const content = decrypted?.value?.content;
  47. const author = decrypted?.value?.author;
  48. const recps = content?.to;
  49. if (!content || !author || !Array.isArray(recps)) throw new Error("Malformed message.");
  50. if (content.type === 'tombstone') throw new Error("Message already deleted.");
  51. const tombstone = {
  52. type: 'tombstone',
  53. target: messageId,
  54. deletedAt: new Date().toISOString(),
  55. private: true
  56. };
  57. const publishAsync = util.promisify(ssbClient.private.publish);
  58. return publishAsync(tombstone, recps);
  59. }
  60. };
  61. };