oasis/src/models.js

1495 lines
42 KiB
JavaScript
Raw Normal View History

2020-01-22 00:22:19 +00:00
"use strict";
2019-08-15 01:10:22 +00:00
2020-01-22 00:22:19 +00:00
const debug = require("debug")("oasis");
const { isRoot, isReply } = require("ssb-thread-schema");
const lodash = require("lodash");
const prettyMs = require("pretty-ms");
const pullParallelMap = require("pull-paramap");
const pull = require("pull-stream");
const pullSort = require("pull-sort");
const ssbRef = require("ssb-ref");
const crypto = require("crypto");
2019-11-13 04:24:19 +00:00
// HACK: https://github.com/ssbc/ssb-thread-schema/issues/4
2020-01-22 00:22:19 +00:00
const isNestedReply = require("ssb-thread-schema/post/nested-reply/validator");
2019-10-01 00:46:04 +00:00
2020-01-22 00:22:19 +00:00
const nullImage = `&${"0".repeat(43)}=.sha256`;
2020-01-08 21:35:20 +00:00
const defaultOptions = {
private: true,
reverse: true,
meta: true,
2020-01-22 00:22:19 +00:00
};
2020-01-08 21:35:20 +00:00
const publicOnlyFilter = pull.filter(
(message) => lodash.get(message, "value.meta.private", false) === false
);
/** @param {object[]} customOptions */
2020-01-08 21:35:20 +00:00
const configure = (...customOptions) =>
2020-01-22 00:22:19 +00:00
Object.assign({}, defaultOptions, ...customOptions);
2020-01-08 21:35:20 +00:00
module.exports = ({ cooler, isPublic }) => {
2020-01-22 00:22:19 +00:00
const models = {};
/**
* The SSB-About plugin is a thin wrapper around the SSB-Social-Index plugin.
* Unfortunately, this plugin has two problems that make it incompatible with
* our needs:
*
* - We want to get the latest value from an author, like what someone calls
* themselves, **not what other people call them**.
* - The plugin has a bug where `false` isn't handled correctly, which is very
* important since we use `publicWebHosting`, a boolean field.
*
* It feels very silly to have to maintain an alternative implementation of
* SSB-About, but this is much smaller code and doesn't have either of the
* above problems. Maybe this should be moved somewhere else in the future?
*/
const getAbout = async ({ key, feedId }) => {
const ssb = await cooler.open();
const source = ssb.backlinks.read({
reverse: true,
query: [
{
$filter: {
dest: feedId,
value: {
author: feedId,
content: { type: "about", about: feedId },
},
},
},
],
});
return new Promise((resolve, reject) =>
pull(
source,
pull.find(
(message) => message.value.content[key] !== undefined,
(err, message) => {
if (err) {
reject(err);
} else {
if (message === null) {
resolve(null);
} else {
resolve(message.value.content[key]);
}
}
}
)
)
);
};
2020-01-09 17:04:46 +00:00
models.about = {
publicWebHosting: async (feedId) => {
const result = await getAbout({
key: "publicWebHosting",
feedId,
});
return result === true;
},
name: async (feedId) => {
if (isPublic && (await models.about.publicWebHosting(feedId)) === false) {
return "Redacted";
}
return (
(await getAbout({
key: "name",
feedId,
})) || feedId.slice(1, 1 + 8)
); // First 8 chars of public key
2020-01-09 17:04:46 +00:00
},
image: async (feedId) => {
if (isPublic && (await models.about.publicWebHosting(feedId)) === false) {
return nullImage;
}
const raw = await getAbout({
2020-01-22 00:22:19 +00:00
key: "image",
feedId,
2020-01-22 00:22:19 +00:00
});
2020-01-09 17:04:46 +00:00
if (raw == null || raw.link == null) {
2020-01-22 00:22:19 +00:00
return nullImage;
}
2020-01-22 00:22:19 +00:00
if (typeof raw.link === "string") {
return raw.link;
}
2020-01-22 00:22:19 +00:00
return raw;
2020-01-09 17:04:46 +00:00
},
description: async (feedId) => {
if (isPublic && (await models.about.publicWebHosting(feedId)) === false) {
return "Redacted";
}
const raw =
(await getAbout({
key: "description",
feedId,
})) || "";
return raw;
},
2020-01-22 00:22:19 +00:00
};
2020-01-09 17:04:46 +00:00
models.blob = {
get: async ({ blobId }) => {
2020-01-22 00:22:19 +00:00
debug("get blob: %s", blobId);
const ssb = await cooler.open();
return ssb.blobs.get(blobId);
2020-01-09 17:04:46 +00:00
},
want: async ({ blobId }) => {
2020-01-22 00:22:19 +00:00
debug("want blob: %s", blobId);
const ssb = await cooler.open();
2020-01-09 17:04:46 +00:00
// This does not wait for the blob.
ssb.blobs.want(blobId);
},
2020-01-22 00:22:19 +00:00
};
2020-01-09 17:04:46 +00:00
models.friend = {
isFollowing: async (feedId) => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const { id } = ssb;
const isFollowing = await ssb.friends.isFollowing({
2020-01-22 00:22:19 +00:00
source: id,
dest: feedId,
2020-01-22 00:22:19 +00:00
});
return isFollowing;
2020-01-09 17:04:46 +00:00
},
setFollowing: async ({ feedId, following }) => {
const ssb = await cooler.open();
const content = {
2020-01-22 00:22:19 +00:00
type: "contact",
contact: feedId,
following,
2020-01-22 00:22:19 +00:00
};
return ssb.publish(content);
},
follow: async (feedId) => {
2020-01-22 00:22:19 +00:00
const isFollowing = await models.friend.isFollowing(feedId);
if (!isFollowing) {
2020-01-22 00:22:19 +00:00
await models.friend.setFollowing({ feedId, following: true });
}
},
unfollow: async (feedId) => {
2020-01-22 00:22:19 +00:00
const isFollowing = await models.friend.isFollowing(feedId);
if (isFollowing) {
2020-01-22 00:22:19 +00:00
await models.friend.setFollowing({ feedId, following: false });
}
},
getRelationship: async (feedId) => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const { id } = ssb;
2020-01-09 17:04:46 +00:00
if (feedId === id) {
return null;
}
const isFollowing = await ssb.friends.isFollowing({
2020-01-22 00:22:19 +00:00
source: id,
dest: feedId,
2020-01-22 00:22:19 +00:00
});
const isBlocking = await ssb.friends.isBlocking({
2020-01-22 00:22:19 +00:00
source: id,
dest: feedId,
2020-01-22 00:22:19 +00:00
});
return {
following: isFollowing,
blocking: isBlocking,
};
},
2020-01-22 00:22:19 +00:00
};
2020-01-09 17:04:46 +00:00
models.meta = {
myFeedId: async () => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const { id } = ssb;
return id;
2020-01-09 17:04:46 +00:00
},
get: async (msgId) => {
const ssb = await cooler.open();
return ssb.get({
2020-01-09 17:04:46 +00:00
id: msgId,
meta: true,
private: true,
2020-01-22 00:22:19 +00:00
});
2020-01-09 17:04:46 +00:00
},
status: async () => {
const ssb = await cooler.open();
return ssb.status();
2020-01-09 17:04:46 +00:00
},
peers: async () => {
const ssb = await cooler.open();
const peersSource = await ssb.conn.peers();
2020-01-09 17:04:46 +00:00
return new Promise((resolve, reject) => {
pull(
peersSource,
// https://github.com/staltz/ssb-conn/issues/9
pull.take(1),
pull.collect((err, val) => {
2020-01-22 00:22:19 +00:00
if (err) return reject(err);
resolve(val[0]);
2020-01-09 17:04:46 +00:00
})
2020-01-22 00:22:19 +00:00
);
});
},
connStop: async () => {
const ssb = await cooler.open();
try {
const result = await ssb.conn.stop();
return result;
} catch (e) {
const expectedName = "TypeError";
const expectedMessage = "Cannot read property 'close' of null";
if (e.name === expectedName && e.message === expectedMessage) {
// https://github.com/staltz/ssb-lan/issues/5
debug("ssbConn is already stopped -- caught error");
} else {
throw new Error(e);
}
}
},
connStart: async () => {
const ssb = await cooler.open();
const result = await ssb.conn.start();
return result;
},
connRestart: async () => {
await models.meta.connStop();
await models.meta.connStart();
},
acceptInvite: async (invite) => {
const ssb = await cooler.open();
return await ssb.invite.accept(invite);
},
2020-01-22 00:22:19 +00:00
};
const isPost = (message) =>
2020-01-22 00:22:19 +00:00
lodash.get(message, "value.content.type") === "post" &&
lodash.get(message, "value.content.text") != null;
const isLooseRoot = (message) => {
2020-01-09 17:04:46 +00:00
const conditions = [
isPost(message),
2020-01-22 00:22:19 +00:00
lodash.get(message, "value.content.root") == null,
lodash.get(message, "value.content.fork") == null,
2020-01-22 00:22:19 +00:00
];
return conditions.every((x) => x);
2020-01-22 00:22:19 +00:00
};
const isLooseReply = (message) => {
2020-01-09 17:04:46 +00:00
const conditions = [
isPost(message),
2020-01-22 00:22:19 +00:00
lodash.get(message, "value.content.root") != null,
lodash.get(message, "value.content.fork") != null,
2020-01-22 00:22:19 +00:00
];
return conditions.every((x) => x);
2020-01-22 00:22:19 +00:00
};
const isLooseComment = (message) => {
2020-01-09 17:04:46 +00:00
const conditions = [
isPost(message),
2020-01-22 00:22:19 +00:00
lodash.get(message, "value.content.root") != null,
lodash.get(message, "value.content.fork") == null,
2020-01-22 00:22:19 +00:00
];
return conditions.every((x) => x === true);
2020-01-22 00:22:19 +00:00
};
2020-01-22 00:22:19 +00:00
const maxMessages = 64;
2019-06-28 20:55:05 +00:00
2020-01-22 00:22:19 +00:00
const getMessages = async ({
myFeedId,
customOptions,
ssb,
query,
filter = null,
2020-01-22 00:22:19 +00:00
}) => {
const options = configure({ query, index: "DTA" }, customOptions);
2019-06-28 20:55:05 +00:00
const source = ssb.backlinks.read(options);
const basicSocialFilter = await socialFilter();
2020-01-09 17:04:46 +00:00
return new Promise((resolve, reject) => {
pull(
2020-01-09 17:04:46 +00:00
source,
basicSocialFilter,
2020-01-22 00:22:19 +00:00
pull.filter(
(msg) =>
2020-01-22 00:22:19 +00:00
typeof msg.value.content !== "string" &&
msg.value.content.type === "post" &&
(filter == null || filter(msg) === true)
2020-01-09 17:04:46 +00:00
),
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
2020-01-22 00:22:19 +00:00
reject(err);
} else {
2020-01-22 00:22:19 +00:00
resolve(transform(ssb, collectedMessages, myFeedId));
}
})
2020-01-22 00:22:19 +00:00
);
});
};
2020-01-09 17:04:46 +00:00
/**
* Returns a function that filters messages based on who published the message.
*
* `null` means we don't care, `true` means it must be true, and `false` means
* that the value must be false. For example, if you set `me = true` then it
* will only allow messages that are from you. If you set `blocking = true`
* then you only see message from people you block.
*/
const socialFilter = async ({
following = null,
blocking = false,
me = null,
} = {}) => {
const ssb = await cooler.open();
const { id } = ssb;
const relationshipObject = await ssb.friends.get({
source: id,
});
const followingList = Object.entries(relationshipObject)
.filter(([, val]) => val === true)
.map(([key]) => key);
const blockingList = Object.entries(relationshipObject)
.filter(([, val]) => val === false)
.map(([key]) => key);
return pull.filter((message) => {
if (message.value.author === id) {
return me !== false;
} else {
return (
(following === null ||
followingList.includes(message.value.author) === following) &&
(blocking === null ||
blockingList.includes(message.value.author) === blocking)
);
}
});
};
2020-01-09 17:04:46 +00:00
const transform = (ssb, messages, myFeedId) =>
2020-01-22 00:22:19 +00:00
Promise.all(
messages.map(async (msg) => {
2020-01-22 00:22:19 +00:00
debug("transforming %s", msg.key);
2020-01-22 00:22:19 +00:00
if (msg == null) {
return null;
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
const filterQuery = {
$filter: {
dest: msg.key,
},
2020-01-22 00:22:19 +00:00
};
const referenceStream = ssb.backlinks.read({
2020-01-22 00:22:19 +00:00
query: [filterQuery],
index: "DTA", // use asserted timestamps
private: true,
meta: true,
2020-01-22 00:22:19 +00:00
});
2020-01-22 00:22:19 +00:00
const rawVotes = await new Promise((resolve, reject) => {
pull(
referenceStream,
pull.filter(
(ref) =>
2020-01-22 00:22:19 +00:00
typeof ref.value.content !== "string" &&
ref.value.content.type === "vote" &&
ref.value.content.vote &&
typeof ref.value.content.vote.value === "number" &&
ref.value.content.vote.value >= 0 &&
ref.value.content.vote.link === msg.key
),
pull.collect((err, collectedMessages) => {
if (err) {
reject(err);
} else {
resolve(collectedMessages);
}
})
);
});
// { @key: 1, @key2: 0, @key3: 1 }
//
// only one vote per person!
const reducedVotes = rawVotes.reduce((acc, vote) => {
acc[vote.value.author] = vote.value.content.vote.value;
return acc;
}, {});
// gets *only* the people who voted 1
// [ @key, @key, @key ]
const voters = Object.entries(reducedVotes)
.filter(([, value]) => value === 1)
.map(([key]) => key);
const pendingName = models.about.name(msg.value.author);
const pendingAvatarMsg = models.about.image(msg.value.author);
2020-01-22 00:22:19 +00:00
const pending = [pendingName, pendingAvatarMsg];
const [name, avatarMsg] = await Promise.all(pending);
2019-11-29 20:50:18 +00:00
if (isPublic) {
const publicOptIn = await models.about.publicWebHosting(
msg.value.author
);
if (publicOptIn === false) {
lodash.set(
msg,
"value.content.text",
"This is a public message that has been redacted because Oasis is running in public mode. This redaction is only meant to make Oasis consistent with other public SSB viewers. Please do not mistake this for privacy. All public messages are public. Any peer on the SSB network can see this message."
);
if (msg.value.content.contentWarning != null) {
msg.value.content.contentWarning = "Redacted";
}
}
}
const channel = lodash.get(msg, "value.content.channel");
const hasChannel = typeof channel === "string" && channel.length > 2;
if (hasChannel) {
msg.value.content.text += `\n\n#${channel}`;
}
2020-01-22 00:22:19 +00:00
const avatarId =
avatarMsg != null && typeof avatarMsg.link === "string"
? avatarMsg.link || nullImage
: avatarMsg || nullImage;
2020-01-22 00:22:19 +00:00
const avatarUrl = `/image/64/${encodeURIComponent(avatarId)}`;
2020-01-22 00:22:19 +00:00
const ts = new Date(msg.value.timestamp);
let isoTs;
2020-01-22 00:22:19 +00:00
try {
isoTs = ts.toISOString();
} catch (e) {
// Just in case it's an invalid date. :(
debug(e);
const receivedTs = new Date(msg.timestamp);
isoTs = receivedTs.toISOString();
}
2019-07-03 17:53:11 +00:00
2020-01-22 00:22:19 +00:00
lodash.set(msg, "value.meta.timestamp.received.iso8601", isoTs);
const ago = Date.now() - Number(ts);
const prettyAgo = prettyMs(ago, { compact: true });
lodash.set(msg, "value.meta.timestamp.received.since", prettyAgo);
lodash.set(msg, "value.meta.author.name", name);
lodash.set(msg, "value.meta.author.avatar", {
id: avatarId,
url: avatarUrl,
2020-01-22 00:22:19 +00:00
});
const isPost =
lodash.get(msg, "value.content.type") === "post" &&
lodash.get(msg, "value.content.text") != null;
const hasRoot = lodash.get(msg, "value.content.root") != null;
const hasFork = lodash.get(msg, "value.content.fork") != null;
if (isPost && hasRoot === false && hasFork === false) {
lodash.set(msg, "value.meta.postType", "post");
} else if (isPost && hasRoot && hasFork === false) {
lodash.set(msg, "value.meta.postType", "comment");
} else if (isPost && hasRoot && hasFork) {
lodash.set(msg, "value.meta.postType", "reply");
} else {
lodash.set(msg, "value.meta.postType", "mystery");
}
2020-01-22 00:22:19 +00:00
lodash.set(msg, "value.meta.votes", voters);
lodash.set(msg, "value.meta.voted", voters.includes(myFeedId));
2019-07-26 17:06:47 +00:00
2020-01-22 00:22:19 +00:00
return msg;
})
);
2019-07-26 17:06:47 +00:00
2020-01-09 17:04:46 +00:00
const post = {
fromPublicFeed: async (feedId, customOptions = {}) => {
const ssb = await cooler.open();
2019-07-26 17:06:47 +00:00
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-22 00:22:19 +00:00
const options = configure({ id: feedId }, customOptions);
const source = ssb.createUserStream(options);
2019-07-03 17:53:11 +00:00
2020-01-09 17:04:46 +00:00
const messages = await new Promise((resolve, reject) => {
pull(
source,
2020-01-22 00:22:19 +00:00
pull.filter(
(msg) =>
lodash.get(msg, "value.meta.private", false) === false &&
2020-01-22 00:22:19 +00:00
msg.value.content.type === "post"
),
2020-01-09 17:04:46 +00:00
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
2020-01-22 00:22:19 +00:00
reject(err);
2020-01-09 17:04:46 +00:00
} else {
2020-01-22 00:22:19 +00:00
resolve(transform(ssb, collectedMessages, myFeedId));
2020-01-09 17:04:46 +00:00
}
})
2020-01-22 00:22:19 +00:00
);
});
2019-07-03 17:53:11 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
mentionsMe: async (customOptions = {}) => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-22 00:22:19 +00:00
const query = [
{
$filter: {
dest: myFeedId,
},
},
2020-01-22 00:22:19 +00:00
];
2020-01-09 17:04:46 +00:00
const messages = await getMessages({
myFeedId,
customOptions,
ssb,
query,
filter: (msg) =>
msg.value.author !== myFeedId &&
lodash.get(msg, "value.meta.private") !== true,
2020-01-22 00:22:19 +00:00
});
2019-12-16 17:15:34 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
fromHashtag: async (hashtag, customOptions = {}) => {
const ssb = await cooler.open();
2019-12-16 17:15:34 +00:00
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2019-12-16 17:15:34 +00:00
2020-01-22 00:22:19 +00:00
const query = [
{
$filter: {
dest: `#${hashtag}`,
},
},
2020-01-22 00:22:19 +00:00
];
2019-10-01 00:37:30 +00:00
2020-01-22 00:22:19 +00:00
const messages = await getMessages({
myFeedId,
customOptions,
ssb,
query,
2020-01-22 00:22:19 +00:00
});
2019-10-01 00:37:30 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
threadReplies: async (rootId, customOptions = {}) => {
const ssb = await cooler.open();
2019-10-01 00:37:30 +00:00
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
const query = [
{
$filter: {
dest: rootId,
},
},
2020-01-22 00:22:19 +00:00
];
2020-01-09 17:04:46 +00:00
const messages = await getMessages({
myFeedId,
customOptions,
ssb,
query,
filter: (msg) =>
msg.value.content.root === rootId && msg.value.content.fork == null,
2020-01-22 00:22:19 +00:00
});
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
likes: async ({ feed }, customOptions = {}) => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const query = [
{
$filter: {
value: {
author: feed,
timestamp: { $lte: Date.now() },
2020-01-22 00:22:19 +00:00
content: {
type: "vote",
},
},
},
},
2020-01-22 00:22:19 +00:00
];
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
const options = configure(
{
query,
reverse: true,
2020-01-22 00:22:19 +00:00
},
customOptions
);
2020-01-09 17:04:46 +00:00
const source = await ssb.query.read(options);
2019-10-01 00:37:30 +00:00
2020-01-09 17:04:46 +00:00
const messages = await new Promise((resolve, reject) => {
pull(
source,
pull.filter((msg) => {
2020-01-22 00:22:19 +00:00
return (
typeof msg.value.content === "object" &&
msg.value.author === feed &&
typeof msg.value.content.vote === "object" &&
typeof msg.value.content.vote.link === "string"
);
2020-01-09 17:04:46 +00:00
}),
pull.take(maxMessages),
pullParallelMap(async (val, cb) => {
2020-01-22 00:22:19 +00:00
const msg = await post.get(val.value.content.vote.link);
cb(null, msg);
2020-01-09 17:04:46 +00:00
}),
pull.collect((err, collectedMessages) => {
if (err) {
2020-01-22 00:22:19 +00:00
reject(err);
2020-01-09 17:04:46 +00:00
} else {
2020-01-22 00:22:19 +00:00
resolve(collectedMessages);
2020-01-09 17:04:46 +00:00
}
})
2020-01-22 00:22:19 +00:00
);
});
2019-12-07 23:22:00 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
search: async ({ query }) => {
const ssb = await cooler.open();
2019-12-07 23:22:00 +00:00
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2019-12-07 23:22:00 +00:00
2020-01-09 17:04:46 +00:00
const options = configure({
query,
2020-01-22 00:22:19 +00:00
});
2019-12-07 23:22:00 +00:00
const source = await ssb.search.query(options);
const basicSocialFilter = await socialFilter();
2019-12-07 23:22:00 +00:00
2020-01-09 17:04:46 +00:00
const messages = await new Promise((resolve, reject) => {
pull(
source,
basicSocialFilter,
2020-01-22 00:22:19 +00:00
pull.filter(
(
message // avoid private messages (!)
) => typeof message.value.content !== "string"
2020-01-09 17:04:46 +00:00
),
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
2020-01-22 00:22:19 +00:00
reject(err);
2020-01-09 17:04:46 +00:00
} else {
2020-01-22 00:22:19 +00:00
resolve(transform(ssb, collectedMessages, myFeedId));
2020-01-09 17:04:46 +00:00
}
})
2020-01-22 00:22:19 +00:00
);
});
2019-07-03 17:53:11 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
latest: async () => {
const ssb = await cooler.open();
2019-07-03 17:53:11 +00:00
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
const source = ssb.query.read(
configure({
query: [
{
$filter: {
value: {
timestamp: { $lte: Date.now() },
content: {
type: "post",
},
},
},
},
],
})
);
const followingFilter = await socialFilter({ following: true });
2020-01-09 17:04:46 +00:00
const messages = await new Promise((resolve, reject) => {
pull(
source,
followingFilter,
publicOnlyFilter,
2020-01-09 17:04:46 +00:00
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
2020-01-22 00:22:19 +00:00
reject(err);
2020-01-09 17:04:46 +00:00
} else {
2020-01-22 00:22:19 +00:00
resolve(transform(ssb, collectedMessages, myFeedId));
2020-01-09 17:04:46 +00:00
}
})
2020-01-22 00:22:19 +00:00
);
});
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
latestExtended: async () => {
const ssb = await cooler.open();
const myFeedId = ssb.id;
const source = ssb.query.read(
configure({
query: [
{
$filter: {
value: {
timestamp: { $lte: Date.now() },
content: {
type: "post",
},
},
},
},
],
})
);
const extendedFilter = await socialFilter({
following: false,
me: false,
});
const messages = await new Promise((resolve, reject) => {
pull(
source,
publicOnlyFilter,
extendedFilter,
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
reject(err);
} else {
resolve(transform(ssb, collectedMessages, myFeedId));
}
})
);
});
return messages;
},
latestTopics: async () => {
const ssb = await cooler.open();
const myFeedId = ssb.id;
const source = ssb.query.read(
configure({
query: [
{
$filter: {
value: {
timestamp: { $lte: Date.now() },
content: {
type: "post",
},
},
},
},
],
})
);
const extendedFilter = await socialFilter({
following: true,
});
const messages = await new Promise((resolve, reject) => {
pull(
source,
publicOnlyFilter,
pull.filter((message) => message.value.content.root == null),
extendedFilter,
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
reject(err);
} else {
resolve(transform(ssb, collectedMessages, myFeedId));
}
})
);
});
return messages;
},
latestSummaries: async () => {
const ssb = await cooler.open();
const myFeedId = ssb.id;
const options = configure({
type: "post",
private: false,
});
const source = ssb.messagesByType(options);
const extendedFilter = await socialFilter({
following: true,
});
const messages = await new Promise((resolve, reject) => {
pull(
source,
pull.filter(
(message) =>
typeof message.value.content !== "string" &&
message.value.content.root == null
),
extendedFilter,
pull.take(maxMessages),
pullParallelMap(async (message, cb) => {
// Retrieve a preview of this post's comments / thread
const thread = await post.fromThread(message.key);
lodash.set(
message,
"value.meta.thread",
await transform(ssb, thread, myFeedId)
);
cb(null, message);
}),
pull.collect((err, collectedMessages) => {
if (err) {
reject(err);
} else {
resolve(transform(ssb, collectedMessages, myFeedId));
}
})
);
});
return messages;
},
latestThreads: async () => {
const ssb = await cooler.open();
const myFeedId = ssb.id;
const options = configure({
type: "post",
private: false
});
const source = ssb.messagesByType(options);
const messages = await new Promise((resolve, reject) => {
pull(
source,
pull.filter(
message =>
typeof message.value.content !== "string" &&
message.value.content.root == null
),
pull.take(maxMessages),
pullParallelMap(async (message, cb) => {
// Retrieve a preview of this post's comments / thread
const thread = await post.fromThread(message.key);
lodash.set(
message,
"value.meta.thread",
await transform(ssb, thread, myFeedId)
);
cb(null, message);
}),
pull.filter(message => message.value.meta.thread.length > 1),
pull.collect((err, collectedMessages) => {
if (err) {
reject(err);
} else {
resolve(transform(ssb, collectedMessages, myFeedId));
}
})
);
});
return messages;
},
2020-01-09 17:04:46 +00:00
popular: async ({ period }) => {
const ssb = await cooler.open();
2020-01-09 17:04:46 +00:00
const periodDict = {
day: 1,
week: 7,
month: 30.42,
year: 365,
2020-01-22 00:22:19 +00:00
};
2020-01-09 17:04:46 +00:00
if (period in periodDict === false) {
2020-01-22 00:22:19 +00:00
throw new Error("invalid period");
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-22 00:22:19 +00:00
const now = new Date();
const earliest = Number(now) - 1000 * 60 * 60 * 24 * periodDict[period];
const source = ssb.query.read(
configure({
query: [
{
$filter: {
value: {
timestamp: { $gte: earliest },
content: {
type: "vote",
},
},
},
},
],
})
);
const basicSocialFilter = await socialFilter();
2020-01-09 17:04:46 +00:00
const messages = await new Promise((resolve, reject) => {
pull(
source,
publicOnlyFilter,
pull.filter((msg) => {
2020-01-22 00:22:19 +00:00
return (
typeof msg.value.content === "object" &&
typeof msg.value.content.vote === "object" &&
typeof msg.value.content.vote.link === "string" &&
typeof msg.value.content.vote.value === "number"
2020-01-22 00:22:19 +00:00
);
2020-01-09 17:04:46 +00:00
}),
2020-01-22 00:22:19 +00:00
pull.reduce(
(acc, cur) => {
const author = cur.value.author;
const target = cur.value.content.vote.link;
const value = cur.value.content.vote.value;
if (acc[author] == null) {
acc[author] = {};
}
2020-01-22 00:22:19 +00:00
// Only accept values between -1 and 1
acc[author][target] = Math.max(-1, Math.min(1, value));
2020-01-22 00:22:19 +00:00
return acc;
},
{},
(err, obj) => {
if (err) {
return reject(err);
}
2020-01-22 00:22:19 +00:00
// HACK: Can we do this without a reduce()? I think this makes the
// stream much slower than it needs to be. Also, we should probably
// be indexing these rather than building the stream on refresh.
2020-01-22 00:22:19 +00:00
const adjustedObj = Object.entries(obj).reduce(
2020-01-09 17:04:46 +00:00
(acc, [author, values]) => {
if (author === myFeedId) {
2020-01-22 00:22:19 +00:00
return acc;
}
2020-01-22 00:22:19 +00:00
const entries = Object.entries(values);
const total = 1 + Math.log(entries.length);
2020-01-09 17:04:46 +00:00
entries.forEach(([link, value]) => {
if (acc[link] == null) {
2020-01-22 00:22:19 +00:00
acc[link] = 0;
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
acc[link] += value / total;
});
return acc;
2020-01-09 17:04:46 +00:00
},
[]
2020-01-22 00:22:19 +00:00
);
const arr = Object.entries(adjustedObj);
const length = arr.length;
pull(
pull.values(arr),
pullSort(([, aVal], [, bVal]) => bVal - aVal),
pull.take(Math.min(length, maxMessages)),
pull.map(([key]) => key),
pullParallelMap(async (key, cb) => {
try {
2020-02-17 11:57:01 +00:00
const msg = await post.get(key);
cb(null, msg);
2020-01-22 00:22:19 +00:00
} catch (e) {
2020-02-17 11:57:01 +00:00
cb(null, null);
2020-01-22 00:22:19 +00:00
}
}),
// avoid private messages (!) and non-posts
2020-01-22 00:22:19 +00:00
pull.filter(
(message) =>
message &&
typeof message.value.content !== "string" &&
message.value.content.type === "post"
2020-01-22 00:22:19 +00:00
),
basicSocialFilter,
2020-01-22 00:22:19 +00:00
pull.collect((err, collectedMessages) => {
if (err) {
2020-02-17 11:57:01 +00:00
reject(err);
2020-01-22 00:22:19 +00:00
} else {
2020-02-17 11:57:01 +00:00
resolve(transform(ssb, collectedMessages, myFeedId));
2020-01-22 00:22:19 +00:00
}
})
2020-02-17 11:57:01 +00:00
);
2020-01-22 00:22:19 +00:00
}
)
);
});
2019-07-03 17:53:11 +00:00
2020-01-22 00:22:19 +00:00
return messages;
2020-01-09 17:04:46 +00:00
},
fromThread: async (msgId, customOptions) => {
2020-01-22 00:22:19 +00:00
debug("thread: %s", msgId);
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-22 00:22:19 +00:00
const options = configure({ id: msgId }, customOptions);
return ssb
.get(options)
.then(async (rawMsg) => {
debug("got raw message");
const parents = [];
const getRootAncestor = (msg) =>
new Promise((resolve, reject) => {
if (msg.key == null) {
debug("something is very wrong, we used `{ meta: true }`");
resolve(parents);
} else {
debug("getting root ancestor of %s", msg.key);
if (typeof msg.value.content === "string") {
// Private message we can't decrypt, stop looking for parents.
debug("private message");
if (parents.length > 0) {
// If we already have some parents, return those.
resolve(parents);
} else {
// If we don't know of any parents, resolve this message.
resolve(msg);
}
} else if (msg.value.content.type !== "post") {
debug("not a post");
resolve(msg);
} else if (
isLooseReply(msg) &&
ssbRef.isMsg(msg.value.content.fork)
) {
debug("reply, get the parent");
try {
// It's a message reply, get the parent!
ssb
.get({
id: msg.value.content.fork,
meta: true,
private: true,
})
.then((fork) => {
resolve(getRootAncestor(fork));
})
.catch(reject);
} catch (e) {
debug(e);
resolve(msg);
2020-01-22 00:22:19 +00:00
}
} else if (
isLooseComment(msg) &&
ssbRef.isMsg(msg.value.content.root)
) {
debug("comment: %s", msg.value.content.root);
try {
// It's a thread reply, get the parent!
ssb
.get({
id: msg.value.content.root,
meta: true,
private: true,
})
.then((root) => {
resolve(getRootAncestor(root));
})
.catch(reject);
} catch (e) {
debug(e);
resolve(msg);
2020-01-22 00:22:19 +00:00
}
} else if (isLooseRoot(msg)) {
debug("got root ancestor");
resolve(msg);
} else {
// type !== "post", probably
// this should show up as JSON
debug(
"got mysterious root ancestor that fails all known schemas"
);
debug("%O", msg);
resolve(msg);
}
}
});
const getReplies = (key) =>
new Promise((resolve, reject) => {
const filterQuery = {
$filter: {
dest: key,
},
};
const referenceStream = ssb.backlinks.read({
query: [filterQuery],
index: "DTA", // use asserted timestamps
});
pull(
referenceStream,
pull.filter((msg) => {
const isPost =
lodash.get(msg, "value.content.type") === "post";
if (isPost === false) {
return false;
}
const root = lodash.get(msg, "value.content.root");
const fork = lodash.get(msg, "value.content.fork");
if (root !== key && fork !== key) {
// mention
return false;
}
if (fork === key) {
// not a reply to this post
// it's a reply *to a reply* of this post
return false;
}
return true;
}),
pull.collect((err, messages) => {
if (err) {
reject(err);
} else {
resolve(messages || undefined);
}
})
);
});
2020-01-22 00:22:19 +00:00
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
const flattenDeep = (arr1) =>
arr1.reduce(
(acc, val) =>
Array.isArray(val)
? acc.concat(flattenDeep(val))
: acc.concat(val),
[]
2020-01-22 00:22:19 +00:00
);
const getDeepReplies = (key) =>
new Promise((resolve, reject) => {
const oneDeeper = async (replyKey, depth) => {
const replies = await getReplies(replyKey);
debug(
"replies",
replies.map((m) => m.key)
);
debug("found %s replies for %s", replies.length, replyKey);
if (replies.length === 0) {
return replies;
}
return Promise.all(
replies.map(async (reply) => {
const deeperReplies = await oneDeeper(reply.key, depth + 1);
lodash.set(reply, "value.meta.thread.depth", depth);
lodash.set(reply, "value.meta.thread.reply", true);
return [reply, deeperReplies];
})
);
};
oneDeeper(key, 0)
.then((nested) => {
const nestedReplies = [...nested];
const deepReplies = flattenDeep(nestedReplies);
resolve(deepReplies);
})
.catch(reject);
});
2020-01-22 00:22:19 +00:00
debug("about to get root ancestor");
const rootAncestor = await getRootAncestor(rawMsg);
debug("got root ancestors");
const deepReplies = await getDeepReplies(rootAncestor.key);
debug("got deep replies");
2020-01-22 00:22:19 +00:00
const allMessages = [rootAncestor, ...deepReplies].map((message) => {
const isThreadTarget = message.key === msgId;
lodash.set(message, "value.meta.thread.target", isThreadTarget);
return message;
});
2020-01-22 00:22:19 +00:00
return await transform(ssb, allMessages, myFeedId);
})
.catch((err) => {
if (err.name === "NotFoundError") {
throw new Error(
"Message not found in the database. You've done nothing wrong. Maybe try again later?"
);
} else {
throw err;
}
});
2020-01-09 17:04:46 +00:00
},
get: async (msgId, customOptions) => {
2020-01-22 00:22:19 +00:00
debug("get: %s", msgId);
const ssb = await cooler.open();
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
const options = configure({ id: msgId }, customOptions);
const rawMsg = await ssb.get(options);
2020-01-22 00:22:19 +00:00
debug("got raw message");
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
const transformed = await transform(ssb, [rawMsg], myFeedId);
debug("transformed: %O", transformed);
return transformed[0];
2020-01-09 17:04:46 +00:00
},
publish: async (options) => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const body = { type: "post", ...options };
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
debug("Published: %O", body);
return ssb.publish(body);
2020-01-09 17:04:46 +00:00
},
publishProfileEdit: async ({ name, description, image }) => {
const ssb = await cooler.open();
if (image.length > 0) {
// 5 MiB check
const mebibyte = Math.pow(2, 20);
const maxSize = 5 * mebibyte;
if (image.length > maxSize) {
throw new Error("Image file is too big, maximum size is 5 mebibytes");
}
const algorithm = "sha256";
const hash = crypto
.createHash(algorithm)
.update(image)
.digest("base64");
const blobId = `&${hash}.${algorithm}`;
return new Promise((resolve, reject) => {
pull(
pull.values([image]),
ssb.blobs.add(blobId, (err) => {
if (err) {
reject(err);
} else {
const body = {
type: "about",
about: ssb.id,
name,
description,
image: blobId,
};
debug("Published: %O", body);
resolve(ssb.publish(body));
}
})
);
});
} else {
const body = { type: "about", about: ssb.id, name, description };
debug("Published: %O", body);
return ssb.publish(body);
}
},
publishCustom: async (options) => {
2020-02-14 19:50:36 +00:00
const ssb = await cooler.open();
debug("Published: %O", options);
return ssb.publish(options);
},
2020-01-09 17:04:46 +00:00
reply: async ({ parent, message }) => {
2020-01-22 00:22:19 +00:00
message.root = parent.key;
message.fork = lodash.get(parent, "value.content.root");
message.branch = await post.branch({ root: parent.key });
message.type = "post"; // redundant but used for validation
2020-01-09 17:04:46 +00:00
if (isNestedReply(message) !== true) {
2020-01-22 00:22:19 +00:00
const messageString = JSON.stringify(message, null, 2);
throw new Error(`message should be valid reply: ${messageString}`);
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
return post.publish(message);
2020-01-09 17:04:46 +00:00
},
root: async (options) => {
2020-01-22 00:22:19 +00:00
const message = { type: "post", ...options };
2020-01-09 17:04:46 +00:00
if (isRoot(message) !== true) {
2020-01-22 00:22:19 +00:00
const messageString = JSON.stringify(message, null, 2);
throw new Error(`message should be valid root post: ${messageString}`);
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
return post.publish(message);
2020-01-09 17:04:46 +00:00
},
comment: async ({ parent, message }) => {
// Set `root` to `parent`'s root.
// If `parent` doesn't have a root, use the parent's key.
// If `parent` has a fork, you must use the parent's key.
2020-01-22 00:22:19 +00:00
const parentKey = parent.key;
const parentFork = lodash.get(parent, "value.content.fork");
const parentRoot = lodash.get(parent, "value.content.root", parentKey);
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
const isPrivate = lodash.get(parent, "value.meta.private", false);
2020-01-09 17:04:46 +00:00
if (isPrivate) {
message.recps = lodash
.get(parent, "value.content.recps", [])
.map((recipient) => {
if (
typeof recipient === "object" &&
typeof recipient.link === "string" &&
recipient.link.length
) {
// Some interfaces, like Patchbay, put `{ name, link }` objects in
// `recps`. The reply schema says this is invalid, so we want to
// fix the `recps` before publishing.
return recipient.link;
} else {
return recipient;
}
});
if (message.recps.length === 0) {
throw new Error("Refusing to publish message with no recipients");
}
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
const parentHasFork = parentFork != null;
2020-01-22 00:22:19 +00:00
message.root = parentHasFork ? parentKey : parentRoot;
message.branch = await post.branch({ root: parent.key });
message.type = "post"; // redundant but used for validation
2020-01-09 17:04:46 +00:00
if (isReply(message) !== true) {
2020-01-22 00:22:19 +00:00
const messageString = JSON.stringify(message, null, 2);
throw new Error(`message should be valid comment: ${messageString}`);
2020-01-09 17:04:46 +00:00
}
2020-01-22 00:22:19 +00:00
return post.publish(message);
2020-01-09 17:04:46 +00:00
},
branch: async ({ root }) => {
const ssb = await cooler.open();
const keys = await ssb.tangle.branch(root);
2020-01-22 00:22:19 +00:00
return keys;
2020-01-09 17:04:46 +00:00
},
inbox: async (customOptions = {}) => {
const ssb = await cooler.open();
2020-01-22 00:22:19 +00:00
const myFeedId = ssb.id;
2020-01-22 00:22:19 +00:00
const options = configure(
{
query: [{ $filter: { dest: ssb.id } }],
2020-01-22 00:22:19 +00:00
},
customOptions
);
const source = ssb.backlinks.read(options);
2020-01-09 17:04:46 +00:00
const messages = await new Promise((resolve, reject) => {
pull(
source,
// Make sure we're only getting private messages that are posts.
2020-01-22 00:22:19 +00:00
pull.filter(
(message) =>
2020-01-22 00:22:19 +00:00
typeof message.value.content !== "string" &&
lodash.get(message, "value.meta.private") &&
lodash.get(message, "value.content.type") === "post"
2020-01-09 17:04:46 +00:00
),
pull.unique((message) => {
2020-01-22 00:22:19 +00:00
const { root } = message.value.content;
2020-01-09 17:04:46 +00:00
if (root == null) {
2020-01-22 00:22:19 +00:00
return message.key;
2020-01-09 17:04:46 +00:00
} else {
2020-01-22 00:22:19 +00:00
return root;
2020-01-09 17:04:46 +00:00
}
}),
pull.take(maxMessages),
pull.collect((err, collectedMessages) => {
if (err) {
2020-01-22 00:22:19 +00:00
reject(err);
2020-01-09 17:04:46 +00:00
} else {
2020-01-22 00:22:19 +00:00
resolve(transform(ssb, collectedMessages, myFeedId));
2020-01-09 17:04:46 +00:00
}
})
2020-01-22 00:22:19 +00:00
);
});
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
return messages;
},
2020-01-22 00:22:19 +00:00
};
models.post = post;
2020-01-09 17:04:46 +00:00
models.vote = {
/** @param {{messageKey: string, value: {}, recps: []}} input */
2020-01-09 17:04:46 +00:00
publish: async ({ messageKey, value, recps }) => {
const ssb = await cooler.open();
const branch = await ssb.tangle.branch(messageKey);
2020-01-09 17:04:46 +00:00
await ssb.publish({
2020-01-22 00:22:19 +00:00
type: "vote",
2020-01-09 17:04:46 +00:00
vote: {
link: messageKey,
value: Number(value),
2020-01-09 17:04:46 +00:00
},
branch,
recps,
2020-01-22 00:22:19 +00:00
});
},
2020-01-22 00:22:19 +00:00
};
2020-01-09 17:04:46 +00:00
2020-01-22 00:22:19 +00:00
return models;
};