Compare commits

...

9 Commits

43 changed files with 4120 additions and 310 deletions

1
.gitignore vendored
View File

@@ -2,6 +2,7 @@ node_modules/
dist/
config/
log/
media/
!config/default.js
assets/js/config/
!assets/js/config/default.js

235
; Normal file
View File

@@ -0,0 +1,235 @@
<template>
<div class="post">
<div class="votes">
<div
class="vote bump"
:class="{ active: post.hasBump }"
@click="vote(1)"
>+</div>
<div class="tally">{{ tally }}</div>
<div
class="vote sink"
:class="{ active: post.hasSink }"
@click="vote(-1)"
>-</div>
</div>
<a
:href="post.link || `/s/${post.shelf.slug}/post/${post.id}`"
target="_blank"
class="title-link"
>
<img
class="thumbnail"
:src="blockedIcon"
>
</a>
<div class="body">
<div class="header">
<h2 class="title">
<a
:href="`/s/${post.shelf.slug}/post/${post.id}`"
class="title-link"
>{{ post.title }}</a>
</h2>
<a
v-if="post.link"
:href="post.link"
target="_blank"
class="link"
>{{ post.link }}</a>
</div>
<div class="meta">
<a
:href="`/s/${post.shelf.slug}`"
class="shelf link"
>s/{{ post.shelf.slug }}</a>
<a
:href="`/user/${post.user.username}`"
class="username link"
>u/{{ post.user.username }}</a>
<span
:title="format(post.createdAt, 'MMMM d, yyyy hh:mm:ss')"
class="timestamp"
>{{ formatDistance(post.createdAt, now, { includeSeconds: true }) }} ago</span>
</div>
<div class="actions">
<a
:href="`/s/${post.shelf.slug}/post/${post.id}`"
class="link comments"
>{{ post.commentCount }} comments</a>
</div>
</div>
<a
:href="`/s/${post.shelf.slug}/post/${post.id}`"
class="fill"
/>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { format, formatDistance } from 'date-fns';
import blockedIcon from '../../assets/icons/blocked.svg?url'; // eslint-disable-line import/no-unresolved
import { usePageContext } from '../../renderer/usePageContext';
import * as api from '../../assets/js/api';
const { now } = usePageContext();
const props = defineProps({
post: {
type: Object,
default: null,
},
shelf: {
type: Object,
default: null,
},
});
const tally = ref(props.post.tally);
async function vote(value) {
const effect = props.post.hasBump || props.post.hasSink ? 0 : value;
await api.post(`/posts/${props.post.id}/votes`, { value: effect });
tally.value += effect;
}
</script>
<style scoped>
.post {
display: flex;
color: var(--text);
border-radius: .25rem;
margin-bottom: .25rem;
background: var(--background);
text-decoration: none;
& :hover {
cursor: pointer;
.title {
color: var(--text);
}
}
}
.body {
margin-left: 1rem;
}
.header {
display: flex;
align-items: center;
}
.title {
display: inline-block;
padding: .25rem 0;
margin: .25rem 1rem 0 0;
font-size: 1rem;
font-weight: bold;
color: var(--grey-dark-30);
}
.title-link {
color: inherit;
text-decoration: none;
}
.thumbnail {
width: 7rem;
height: 4rem;
box-sizing: border-box;
padding: 1rem;
border-radius: .25rem;
margin: .5rem;
background: var(--grey-light-10);
opacity: .25;
}
.votes {
width: 2rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.vote,
.tally {
display: flex;
align-items: center;
height: 1rem;
font-weight: bold;
}
.vote {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1rem;
box-sizing: border-box;
padding: .6rem;
margin: .25rem 0;
border-radius: .5rem;
background: var(--shadow-weak-40);
}
.tally {
color: var(--shadow-strong-20);
font-size: .9rem;
}
.bump.active {
color: var(--text-light);
background: var(--bump);
}
.sink.active {
color: var(--text-light);
background: var(--sink);
}
.meta {
display: flex;
gap: 1rem;
margin-bottom: .25rem;
font-size: .9rem;
}
.username {
color: inherit;
}
.shelf {
color: inherit;
font-weight: bold;
}
.timestamp {
color: var(--grey-dark-20);
}
.comments {
color: inherit;
font-size: .9rem;
}
.fill {
flex-grow: 1;
}
</style>

View File

@@ -22,6 +22,12 @@
font-size: 1rem;
font-weight: bold;
&:hover {
cursor: pointer;
background: var(--primary);
color: var(--text-light);
}
&:focus {
outline: none;
}
@@ -41,6 +47,21 @@
}
}
.button-cancel {
background: none;
color: var(--shadow-strong-10);
font-weight: normal;
&:hover:not(:disabled) {
color: var(--error);
cursor: pointer;
}
&:disabled {
color: var(--shadow-weak-10);
}
}
.radio {
margin: 0 .5rem 0 0;
}

View File

@@ -24,6 +24,23 @@
text-decoration: none;
}
.nolink-active {
display: inline-block;
color: inherit;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.nobutton {
background: none;
border: none;
font-size: 1rem;
padding: 0;
}
.nobar {
scrollbar-width: none;
-mis-overflow-style: none;

View File

@@ -3,6 +3,7 @@
@import 'inputs';
@import 'forms';
@import 'markdown';
@import 'tooltip';
html,
body,

View File

@@ -22,6 +22,7 @@
--background-dark-10: #f8f8f8;
--background: #fff;
--shadow-weak-40: rgba(0, 0, 0, .05);
--shadow-weak-30: rgba(0, 0, 0, .1);
--shadow-weak-20: rgba(0, 0, 0, .2);
--shadow-weak-10: rgba(0, 0, 0, .35);
@@ -35,4 +36,9 @@
--link: #48f;
--error: #f66;
--bump: var(--primary);
--sink: var(--error);
--op: #5be;
}

6
assets/css/tooltip.css Normal file
View File

@@ -0,0 +1,6 @@
.tooltip {}
.menu-item {
display: block;
padding: .5rem;
}

View File

@@ -14,7 +14,7 @@ function getQuery(data) {
return `?${new URLSearchParams(data).toString()}`;
}
export async function get(path, query = {}) {
async function get(path, query = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`);
const body = await res.json();
@@ -25,7 +25,7 @@ export async function get(path, query = {}) {
throw new Error(body.message);
}
export async function post(path, data, { query } = {}) {
async function post(path, data, { query } = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`, {
method: 'POST',
body: JSON.stringify(data),
@@ -45,7 +45,7 @@ export async function post(path, data, { query } = {}) {
throw new Error(body.statusMessage);
}
export async function patch(path, data, { query } = {}) {
async function patch(path, data, { query } = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`, {
method: 'PATCH',
body: JSON.stringify(data),
@@ -65,7 +65,7 @@ export async function patch(path, data, { query } = {}) {
throw new Error(body.message);
}
export async function del(path, { data, query } = {}) {
async function del(path, { data, query } = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`, {
method: 'DELETE',
body: JSON.stringify(data),
@@ -84,3 +84,11 @@ export async function del(path, { data, query } = {}) {
throw new Error(body.message);
}
export {
get,
post,
patch,
del,
del as delete,
};

View File

@@ -1,5 +1,5 @@
// centralize navigation to simplify switching between client and server routing
export default function navigate(path) {
export function navigate(path) {
window.location.href = path;
}

View File

@@ -1,23 +1,84 @@
<template>
<div class="comment">
<div class="header">
<a
:href="`/user/${comment.user.username}`"
class="username link"
>u/{{ comment.user.username }}</a>
<div class="container">
<div class="frame">
<div class="crumbs">
<div
v-for="index in depth"
:key="`${comment.id}-${index}`"
:style="{ color: `hsl(${index * 60}, 50%, 75%)`, 'border-color': `hsl(${index * 60}, 50%, 90%)` }"
class="crumb"
>{{ String.fromCharCode(96 + index) }}</div>
</div>
<span
:title="format(comment.createdAt, 'MMM d, yyyy hh:mm:ss')"
class="timestamp"
>{{ formatDistance(comment.createdAt, now, { includeSeconds: true }) }} ago</span>
<div
class="comment"
:class="{ nested: comment.parentId }"
:style="{ 'border-left': `solid 2px hsl(${(depth + 1) * 60}, 50%, 90%)` }"
>
<div class="header">
<img
src="/assets/icons/blocked.svg"
class="avatar"
>
<a
:href="`/user/${comment.user.username}`"
class="username link"
>u/{{ comment.user.username }}</a>
<ul class="labels nolist">
<li
v-if="comment.user.id === post.user.id"
class="label op"
>op</li>
</ul>
<span
:title="format(comment.createdAt, 'MMM d, yyyy hh:mm:ss')"
class="timestamp"
>{{ formatDistance(comment.createdAt, now, { includeSeconds: true }) }} ago</span>
</div>
<p class="body">{{ comment.body }}</p>
<div class="actions">
<button
type="button"
class="action link nobutton"
@click="isReplying = !isReplying"
>reply</button>
</div>
<Writer
v-if="isReplying"
:comment="comment"
:post="post"
@cancel="isReplying = false"
/>
</div>
</div>
<p class="body">{{ comment.body }}</p>
<ul class="replies nolist">
<li
v-for="reply in comment.comments"
:key="reply.id"
>
<Comment
:comment="reply"
:post="post"
:depth="depth + 1"
/>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { format, formatDistance } from 'date-fns';
import Writer from './writer.vue';
import { usePageContext } from '../../renderer/usePageContext';
const { now } = usePageContext();
@@ -27,20 +88,37 @@ defineProps({
type: Object,
default: null,
},
post: {
type: Object,
default: null,
},
depth: {
type: Number,
default: 0,
},
});
const isReplying = ref(false);
</script>
<style scoped>
.comment {
display: block;
flex-grow: 1;
background: var(--background);
padding: .5rem;
border-radius: .25rem;
margin-bottom: .25rem;
box-sizing: border-box;
border-radius: .25rem .25rem .25rem 0;
margin: .25rem 0;
&.nested {
position: relative;
}
}
.header {
display: flex;
font-size: .9rem;
margin-bottom: .5rem;
padding: .5rem .5rem .25rem .5rem;
}
.username {
@@ -54,6 +132,67 @@ defineProps({
}
.body {
padding: .25rem .5rem .5rem .5rem;
margin: 0;
}
.actions {
border-top: solid 1px var(--shadow-weak-40);
}
.action {
padding: .5rem;
color: var(--grey-dark-20);
cursor: pointer;
}
.labels {
display: inline-block;
margin-right: .5rem;
}
.label {
background: var(--grey);
border-radius: .25rem;
color: var(--text-light);
font-weight: bold;
&.op {
color: var(--op);
background: none;
}
}
.avatar {
width: 1rem;
height: 1rem;
margin-right: .5rem;
opacity: .25;
}
.replies {
display: flex;
flex-direction: column;
}
.frame {
display: flex;
align-items: stretch;
}
.crumbs {
display: flex;
align-items: stretch;
margin-top: -.5rem;
}
.crumb {
display: flex;
align-items: center;
box-sizing: border-box;
padding: .5rem;
border-left: solid 2px var(--shadow-weak-40);
color: var(--shadow-weak-20);
font-size: .8rem;
}
</style>

View File

@@ -0,0 +1,88 @@
<template>
<form
class="writer"
@submit.prevent="addComment"
>
<textarea
ref="inputRef"
v-model="body"
placeholder="Write a new comment"
class="input"
/>
<div class="actions">
<button
:disabled="body.length === 0"
class="button button-submit action submit"
>Comment</button>
<button
v-if="comment"
type="button"
class="button button-cancel action cancel"
@click="$emit('cancel')"
>Cancel</button>
</div>
</form>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import * as api from '../../assets/js/api';
import { reload } from '../../assets/js/navigate';
const props = defineProps({
comment: {
type: Object,
default: null,
},
post: {
type: Object,
default: null,
},
});
const body = ref('');
const inputRef = ref(null);
async function addComment() {
await api.post(`/posts/${props.post.id}/comments`, {
body: body.value,
parentId: props.comment?.id,
});
reload();
}
onMounted(() => {
if (props.comment) {
inputRef.value.focus();
}
});
</script>
<style scoped>
.writer {
width: 100%;
background: var(--background);
box-sizing: border-box;
padding: .5rem;
border-radius: .5rem;
margin-bottom: .5rem;
}
.input {
width: 100%;
margin-bottom: .25rem;
}
.actions {
display: flex;
justify-content: flex-start;
}
.action {
margin-right: .25rem;
}
</style>

View File

@@ -1,12 +1,40 @@
<template>
<div class="post">
<div class="votes noselect">
<div
class="vote bump"
:class="{ active: hasBump }"
title="Bump"
@click="submitVote(1)"
>+</div>
<div
class="tally"
:title="`${post.vote.total} ${post.vote.total === 1 ? 'vote' : 'votes'}`"
>{{ tally }}</div>
<div
class="vote sink"
:class="{ active: hasSink }"
title="Sink"
@click="submitVote(-1)"
>-</div>
</div>
<a
:href="post.link || `/s/${post.shelf.slug}/post/${post.id}`"
:href="post.link || `/s/${post.shelf.slug}/post/${post.id}/${post.slug}`"
target="_blank"
class="title-link"
>
<img
v-if="post.hasThumbnail"
class="thumbnail"
:src="`/media/thumbnails/${post.id}.jpeg`"
>
<img
v-else
class="thumbnail missing"
:src="blockedIcon"
>
</a>
@@ -15,7 +43,7 @@
<div class="header">
<h2 class="title">
<a
:href="`/s/${post.shelf.slug}/post/${post.id}`"
:href="`/s/${post.shelf.slug}/post/${post.id}/${post.slug}`"
class="title-link"
>{{ post.title }}</a>
</h2>
@@ -47,32 +75,61 @@
<div class="actions">
<a
:href="`/s/shack/post/${post.id}`"
:href="`/s/${post.shelf.slug}/post/${post.id}`"
class="link comments"
>{{ post.commentCount }} comments</a>
</div>
</div>
<a
:href="`/s/shack/post/${post.id}`"
:href="`/s/${post.shelf.slug}/post/${post.id}/${post.slug}`"
class="fill"
/>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { format, formatDistance } from 'date-fns';
import blockedIcon from '../../assets/icons/blocked.svg?url'; // eslint-disable-line import/no-unresolved
import { usePageContext } from '../../renderer/usePageContext';
import * as api from '../../assets/js/api';
const { now } = usePageContext();
const { me, now } = usePageContext();
defineProps({
const props = defineProps({
post: {
type: Object,
default: null,
},
shelf: {
type: Object,
default: null,
},
});
const tally = ref(props.post.vote.tally);
const hasBump = ref(props.post.vote.bump);
const hasSink = ref(props.post.vote.sink);
const voting = ref(false);
async function submitVote(value) {
if (!me || voting.value) {
return;
}
voting.value = true;
const undo = (value > 0 && hasBump.value) || (value < 0 && hasSink.value);
const vote = await api.post(`/posts/${props.post.id}/votes`, { value: undo ? 0 : value });
tally.value = vote.tally;
hasBump.value = vote.bump;
hasSink.value = vote.sink;
voting.value = false;
}
</script>
<style scoped>
@@ -83,6 +140,7 @@ defineProps({
margin-bottom: .25rem;
background: var(--background);
text-decoration: none;
overflow: hidden;
& :hover {
cursor: pointer;
@@ -100,6 +158,7 @@ defineProps({
.header {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.title {
@@ -120,16 +179,66 @@ defineProps({
width: 7rem;
height: 4rem;
box-sizing: border-box;
padding: 1rem;
border-radius: .25rem;
margin: .5rem;
background: var(--grey-light-10);
opacity: .25;
object-fit: cover;
&.missing {
padding: 1rem;
background: var(--grey-light-10);
opacity: .25;
object-fit: contain;
}
}
.votes {
width: 3rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.vote,
.tally {
display: flex;
align-items: center;
height: 1rem;
font-weight: bold;
}
.vote {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1rem;
box-sizing: border-box;
padding: .6rem;
margin: .25rem 0;
border-radius: .5rem;
background: var(--shadow-weak-40);
}
.tally {
color: var(--shadow-strong-20);
font-size: .9rem;
}
.bump.active {
color: var(--text-light);
background: var(--bump);
}
.sink.active {
color: var(--text-light);
background: var(--sink);
}
.meta {
display: flex;
gap: 1rem;
flex-wrap: wrap;
gap: 0 1rem;
margin-bottom: .25rem;
font-size: .9rem;
}

View File

@@ -39,6 +39,8 @@ export async function up(knex) {
table.increments('id');
table.text('slug')
.unique()
.index()
.notNullable();
table.integer('founder_id')
@@ -74,6 +76,24 @@ export async function up(knex) {
table.boolean('is_nsfw');
});
await knex.schema.createTable('shelves_subscriptions', (table) => {
table.increments('id');
table.integer('shelf_id')
.references('id')
.inTable('shelves');
table.integer('user_id')
.references('id')
.inTable('users');
table.unique(['shelf_id', 'user_id']);
table.datetime('created_at')
.notNullable()
.defaultTo(knex.fn.now());
});
await knex.schema.createTable('posts', (table) => {
table.text('id', 8)
.primary()
@@ -95,6 +115,10 @@ export async function up(knex) {
.references('id')
.inTable('users');
table.text('thumbnail')
.notNullable()
.default(false);
table.datetime('created_at')
.notNullable()
.defaultTo(knex.fn.now());
@@ -102,6 +126,30 @@ export async function up(knex) {
await knex.raw('ALTER TABLE posts ADD CONSTRAINT post_content CHECK (body IS NOT NULL OR link IS NOT NULL)');
await knex.schema.createTable('posts_votes', (table) => {
table.increments('id');
table.tinyint('value')
.notNullable()
.defaultTo(1);
table.integer('user_id')
.notNullable()
.references('id')
.inTable('users');
table.string('post_id')
.notNullable()
.references('id')
.inTable('posts');
table.datetime('created_at')
.notNullable()
.defaultTo(knex.fn.now());
table.unique(['user_id', 'post_id']);
});
await knex.schema.createTable('comments', (table) => {
table.text('id', 8)
.primary()
@@ -112,7 +160,7 @@ export async function up(knex) {
.references('id')
.inTable('posts');
table.integer('parent_comment_id')
table.text('parent_id')
.references('id')
.inTable('comments');
@@ -123,6 +171,32 @@ export async function up(knex) {
table.text('body');
table.boolean('deleted')
.notNullable()
.defaultTo(false);
table.datetime('created_at')
.notNullable()
.defaultTo(knex.fn.now());
});
await knex.schema.createTable('comments_votes', (table) => {
table.increments('id');
table.tinyint('value')
.notNullable()
.defaultTo(1);
table.integer('user_id')
.notNullable()
.references('id')
.inTable('users');
table.string('comment_id')
.notNullable()
.references('id')
.inTable('comments');
table.datetime('created_at')
.notNullable()
.defaultTo(knex.fn.now());
@@ -130,11 +204,14 @@ export async function up(knex) {
}
export async function down(knex) {
await knex.schema.dropTable('comments');
await knex.schema.dropTable('posts');
await knex.schema.dropTable('shelves_settings');
await knex.schema.dropTable('shelves');
await knex.schema.dropTable('users');
await knex.schema.dropTableIfExists('comments_votes');
await knex.schema.dropTableIfExists('comments');
await knex.schema.dropTableIfExists('posts_votes');
await knex.schema.dropTableIfExists('posts');
await knex.schema.dropTableIfExists('shelves_settings');
await knex.schema.dropTableIfExists('shelves_subscriptions');
await knex.schema.dropTableIfExists('shelves');
await knex.schema.dropTableIfExists('users');
await knex.raw(`
DROP FUNCTION IF EXISTS shack_id;

2471
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "shack",
"version": "0.2.0",
"version": "0.5.0",
"description": "Shack is a self-hosted social news aggregate",
"main": "src/web/server.js",
"type": "module",
@@ -20,6 +20,7 @@
"build": "vite build",
"server": "node --experimental-specifier-resolution=node ./src/web/server",
"server:prod": "cross-env NODE_ENV=production node ./src/web/server",
"thumbs": "node --experimental-specifier-resolution=node ./src/cli thumbs",
"migrate-make": "knex migrate:make",
"migrate": "knex migrate:latest",
"rollback": "knex migrate:rollback"
@@ -47,6 +48,7 @@
"express": "^4.18.1",
"express-promise-router": "^4.1.1",
"express-session": "^1.17.3",
"floating-vue": "^2.0.0-beta.22",
"ip-cidr": "^3.1.0",
"knex": "^2.4.2",
"knex-migrate": "^1.7.4",
@@ -54,8 +56,10 @@
"pg": "^8.11.0",
"pinia": "^2.1.3",
"redis": "^4.6.6",
"sharp": "^0.32.1",
"short-uuid": "^4.2.2",
"sirv": "^2.0.2",
"unprint": "^0.9.3",
"vite": "^4.0.3",
"vite-plugin-ssr": "^0.4.126",
"vite-plugin-vue-markdown": "^0.23.5",

View File

@@ -88,7 +88,7 @@ import VueHcaptcha from '@hcaptcha/vue3-hcaptcha';
import Checkbox from '../../components/form/checkbox.vue';
import navigate from '../../assets/js/navigate';
import { navigate } from '../../assets/js/navigate';
import { post } from '../../assets/js/api';
const config = CONFIG;
@@ -121,7 +121,9 @@ async function signup() {
<style scoped>
.content {
display: flex;
flex-direction: column;
justify-content: center;
flex-grow: 1;
align-items: center;
}

View File

@@ -65,7 +65,7 @@ import { ref } from 'vue';
import VueHcaptcha from '@hcaptcha/vue3-hcaptcha';
import { post } from '../../assets/js/api';
import navigate from '../../assets/js/navigate';
import { navigate } from '../../assets/js/navigate';
const config = CONFIG;
@@ -91,6 +91,8 @@ async function signup() {
<style scoped>
.content {
display: flex;
flex-grow: 1;
flex-direction: column;
justify-content: center;
align-items: center;
}

View File

@@ -1,10 +1,12 @@
import { fetchShelves } from '../../src/shelves';
import { fetchUserPosts, fetchAllPosts } from '../../src/posts';
async function getPageData() {
const shelves = await fetchShelves();
async function getPageData(pageContext) {
const posts = pageContext.session.user
? await fetchUserPosts(pageContext.session.user)
: await fetchAllPosts();
return {
shelves,
posts,
};
}

View File

@@ -1,37 +1,20 @@
<template>
<div class="content">
<ul>
<li><a
href="/shelf/create"
class="link"
>Create new shelf</a></li>
<li v-if="!user"><a
href="/account/login"
class="link"
>Log in</a></li>
<li><a
href="/account/create"
class="link"
>Sign up</a></li>
</ul>
<ul>
<ul class="posts nolist">
<li
v-for="shelf in shelves"
:key="shelf.id"
><a
:href="`/s/${shelf.slug}`"
class="link"
>{{ shelf.slug }}</a></li>
v-for="post in posts"
:key="post.id"
>
<Post :post="post" />
</li>
</ul>
</div>
</template>
<script setup>
import { usePageContext } from '../../renderer/usePageContext';
import Post from '../../components/posts/post.vue';
const { user, pageData } = usePageContext();
const { shelves } = pageData;
const { pageData } = usePageContext();
const { posts } = pageData;
</script>

View File

@@ -1 +1 @@
export default '/s/@id/post/@postId';
export default '/s/@shelfId/post/@postId/@postSlug?';

View File

@@ -1,33 +1,20 @@
import { RenderErrorPage } from 'vite-plugin-ssr/RenderErrorPage';
import { fetchShelf } from '../../src/shelves';
import { fetchPost } from '../../src/posts';
import { fetchPostComments } from '../../src/comments';
async function getPageData(pageContext) {
const [shelf, post, comments] = await Promise.all([
fetchShelf(pageContext.routeParams.id),
fetchPost(pageContext.routeParams.postId),
fetchShelf(pageContext.routeParams.shelfId),
fetchPost(pageContext.routeParams.postId, pageContext.session.user),
fetchPostComments(pageContext.routeParams.postId),
]);
if (!shelf) {
throw RenderErrorPage({
pageContext: {
pageProps: {
errorInfo: 'This shelf does not exist',
},
},
});
throw new Error('This shelf does not exist');
}
if (!post) {
throw RenderErrorPage({
pageContext: {
pageProps: {
errorInfo: 'This post does not exist',
},
},
});
throw new Error('This post does not exist');
}
return {

View File

@@ -1,107 +1,86 @@
<template>
<div class="page">
<div class="body">
<Post :post="post" />
<Shelf :shelf="shelf">
<div class="content">
<Post
:post="post"
:shelf="shelf"
/>
<form
class="writer"
@submit.prevent="addComment"
<p
v-if="post.body"
class="body"
>{{ post.body }}</p>
<Writer
v-if="me"
:post="post"
/>
<div
v-else
class="body"
>
<textarea
v-model="newComment"
placeholder="Write a new comment"
class="input"
/>
<div class="actions">
<button class="button">Comment</button>
</div>
</form>
<a
href="/account/login"
class="link"
>Log in</a> or
<a
href="/account/create"
class="link"
>sign up</a> to comment
</div>
<ul class="comments nolist">
<li
v-for="comment in comments"
:key="comment.id"
><Comment :comment="comment" /></li>
>
<Comment
:comment="comment"
:post="post"
:shelf="shelf"
/>
</li>
</ul>
</div>
<div class="sidebar">
{{ shelf.name }}
</div>
</div>
</Shelf>
</template>
<script setup>
import { ref } from 'vue';
import Shelf from '../../templates/shelves/shelf.vue';
import Post from '../../components/posts/post.vue';
import Comment from '../../components/comments/comment.vue';
import * as api from '../../assets/js/api';
import { reload } from '../../assets/js/navigate';
import Writer from '../../components/comments/writer.vue';
import { usePageContext } from '../../renderer/usePageContext';
const { pageData } = usePageContext();
const { me, pageData } = usePageContext();
const {
shelf,
post,
comments,
} = pageData;
const newComment = ref('');
async function addComment() {
await api.post(`/posts/${post.id}/comments`, {
body: newComment.value,
parentId: null,
});
reload();
}
</script>
<style scoped>
.page {
display: flex;
padding: .5rem;
.content {
padding: 0;
}
.body {
box-sizing: border-box;
padding: 1rem;
border-radius: .5rem;
margin: 0 0 .5rem 0;
background: var(--background);
}
.title {
margin: 0 0 .5rem 0;
}
.body {
flex-grow: 1;
}
.post {
margin-bottom: .5rem;
}
.writer {
width: 40rem;
background: var(--background);
padding: .5rem;
border-radius: .5rem;
margin-bottom: .5rem;
.input {
width: 100%;
margin-bottom: .25rem;
}
.actions {
display: flex;
justify-content: flex-end;
}
}
.sidebar {
background: var(--background);
width: 20rem;
padding: .5rem;
border-radius: .5rem;
margin-left: .5rem;
}
</style>

View File

@@ -1,78 +0,0 @@
<template>
<div class="content">
<h3>{{ shelf.slug }}</h3>
<ul class="posts nolist">
<li
v-for="post in posts"
:key="post.id"
><Post :post="post" /></li>
</ul>
<form
class="form compose"
@submit.prevent="submitPost"
>
<div class="form-row">
<input
v-model="title"
placeholder="Title"
class="input"
>
</div>
<div class="form-row">
<input
v-model="link"
class="input"
placeholder="Link"
>
</div>
<div class="form-row">
<textarea
v-model="body"
placeholder="Body"
class="input body"
/>
</div>
<div class="form-actions">
<button class="button button-submit">Post</button>
</div>
</form>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Post from '../../../components/posts/post.vue';
import * as api from '../../../assets/js/api';
import { usePageContext } from '../../../renderer/usePageContext';
const { pageData, routeParams } = usePageContext();
const {
shelf,
posts,
} = pageData;
const title = ref();
const link = ref();
const body = ref();
async function submitPost() {
await api.post(`/api/shelves/${routeParams.id}/posts`, {
title: title.value,
link: link.value,
body: body.value,
});
}
</script>
<style scoped>
.posts {
margin-bottom: 1rem;
}
</style>

View File

@@ -0,0 +1 @@
export default '/shelf/create';

View File

@@ -126,6 +126,7 @@
import { ref } from 'vue';
import Checkbox from '../../components/form/checkbox.vue';
import { post } from '../../assets/js/api';
import { navigate } from '../../assets/js/navigate';
const slug = ref();
const title = ref();
@@ -137,7 +138,7 @@ const postAccess = ref('registered');
const isNsfw = ref(false);
async function create() {
await post('/shelves', {
const shelf = await post('/shelves', {
slug: slug.value,
title: title.value,
description: description.value,
@@ -147,6 +148,9 @@ async function create() {
isNsfw: isNsfw.value,
},
});
console.log(shelf);
navigate(`/s/${shelf.slug}`);
}
</script>

View File

@@ -0,0 +1 @@
export default '/s/@id';

View File

@@ -1,10 +1,10 @@
import { RenderErrorPage } from 'vite-plugin-ssr/RenderErrorPage';
import { fetchShelf } from '../../../src/shelves';
import { fetchShelfPosts } from '../../../src/posts';
import { fetchShelf } from '../../src/shelves';
import { fetchShelfPosts } from '../../src/posts';
async function getPageData(pageContext) {
const shelf = await fetchShelf(pageContext.routeParams.id);
const posts = await fetchShelfPosts(pageContext.routeParams.id, { limit: 50 });
const shelf = await fetchShelf(pageContext.routeParams.id, { user: pageContext.session.user });
const posts = await fetchShelfPosts(pageContext.routeParams.id, { user: pageContext.session.user, limit: 50 });
if (!shelf) {
throw RenderErrorPage({

View File

@@ -0,0 +1,43 @@
<template>
<Shelf :shelf="shelf">
<ul class="posts nolist">
<li
v-for="post in posts"
:key="post.id"
class="post-item"
>
<Post
:post="post"
:shelf="shelf"
/>
</li>
</ul>
</Shelf>
</template>
<script setup>
import Shelf from '../../templates/shelves/shelf.vue';
import Post from '../../components/posts/post.vue';
import { usePageContext } from '../../renderer/usePageContext';
const { pageData } = usePageContext();
const {
shelf,
posts,
} = pageData;
</script>
<style scoped>
.posts {
width: 100%;
display: flex;
flex-direction: column;
margin-bottom: 1rem;
}
.post-item {
width: 100%;
}
</style>

View File

@@ -1,11 +1,14 @@
// import { renderToString as renderToString_ } from '@vue/server-renderer';
import { renderToNodeStream } from '@vue/server-renderer';
import { escapeInject } from 'vite-plugin-ssr/server';
import { RenderErrorPage } from 'vite-plugin-ssr/RenderErrorPage';
import { createApp } from './app';
import { useUser } from '../stores/user';
import logoUrl from './logo.svg';
import { fetchAllShelves } from '../src/shelves';
async function render(pageContext) {
// See https://vite-plugin-ssr.com/head
const { documentProps } = pageContext.exports;
@@ -45,16 +48,32 @@ async function render(pageContext) {
}
async function onBeforeRender(pageContext) {
const pageData = await pageContext.exports.getPageData?.(pageContext, pageContext.session);
try {
const pageData = await pageContext.exports.getPageData?.(pageContext, pageContext.session);
const shelves = await fetchAllShelves({ user: pageContext.session.user });
return {
pageContext: {
// initialState: store.state.value,
pageData,
user: pageContext.session.user,
now: new Date(),
},
};
return {
pageContext: {
// initialState: store.state.value,
pageData: {
...pageData,
shelves,
},
me: pageContext.session.user,
now: new Date(),
},
};
} catch (error) {
console.error(error);
throw RenderErrorPage({
pageContext: {
pageProps: error,
me: pageContext.session.user,
now: new Date(),
},
});
}
}
export {
@@ -62,4 +81,4 @@ export {
onBeforeRender,
};
export const passToClient = ['urlPathname', 'initialState', 'pageData', 'pageProps', 'routeParams', 'user', 'now'];
export const passToClient = ['urlPathname', 'initialState', 'pageData', 'pageProps', 'routeParams', 'me', 'now'];

View File

@@ -1,16 +1,16 @@
<template>
<div class="content">
<div v-if="is404">
<h1>404 Page Not Found</h1>
<h1>{{ statusCode }}</h1>
<p v-if="errorInfo">{{ errorInfo }}</p>
<p v-if="statusMessage">{{ statusMessage }}</p>
<p v-else>This page could not be found.</p>
</div>
<div v-else>
<h1>500 Internal Error</h1>
<p v-if="errorInfo">{{ errorInfo }}</p>
<p v-if="statusMessage">{{ errorInfo }}</p>
<p v-else>Something went wrong.</p>
</div>
</div>
@@ -20,5 +20,5 @@
import { usePageContext } from './usePageContext';
const { pageProps } = usePageContext();
const { is404, errorInfo } = pageProps;
const { is404, statusCode, statusMessage } = pageProps;
</script>

View File

@@ -1,9 +1,12 @@
import { createSSRApp, h } from 'vue';
import { createPinia } from 'pinia';
import FloatingVue from 'floating-vue';
import Container from './container.vue';
import { setPageContext } from './usePageContext';
import '../assets/css/style.css';
import 'floating-vue/dist/style.css';
function createApp(pageContext) {
const PageWithLayout = {
@@ -20,6 +23,7 @@ function createApp(pageContext) {
const store = createPinia();
app.use(store);
app.use(FloatingVue);
// We make pageContext available from any Vue component
setPageContext(app, pageContext);

View File

@@ -18,11 +18,63 @@
>
</div>
<span
v-if="user"
class="userpanel"
@click="logout"
>{{ user.username }}</span>
<div class="actions">
<VDropdown>
<button class="button">Explore</button>
<template #popper>
<ul class="tooltip nolist">
<li class="tooltip-item">
<a
href="/shelf/create"
class="menu-item"
>
<button class="button button-submit">New shelf</button>
</a>
</li>
<li
v-for="shelf in shelves"
:key="shelf.id"
class="tooltip-item"
>
<a
:href="`/s/${shelf.slug}`"
class="link shelf"
>s/{{ shelf.slug }}</a>
</li>
</ul>
</template>
</VDropdown>
</div>
<VDropdown v-if="me">
<span class="userpanel">{{ me.username }}</span>
<template #popper>
<ul class="tooltip nolist">
<li>
<a
:href="`/user/${me.username}`"
class="link menu-item"
>Profile</a>
</li>
<li class="menu-item">
<button
class="button"
@click="logout"
>Log out</button>
</li>
</ul>
</template>
</VDropdown>
<a
v-else
href="/account/login"
class="link userpanel"
>Log in</a>
</header>
<div class="content-container">
@@ -35,23 +87,26 @@
<script setup>
import logo from '../assets/img/logo.svg?raw'; // eslint-disable-line import/no-unresolved
import { del } from '../assets/js/api';
import { navigate } from '../assets/js/navigate';
import { usePageContext } from './usePageContext';
const { user } = usePageContext();
const { pageData, me } = usePageContext();
const { shelves } = pageData;
const version = CLIENT_VERSION;
async function logout() {
await del('/api/session');
window.location.href = '/account/login';
await del('/session');
navigate('/account/login');
}
</script>
<style>
.content {
display: flex;
flex-grow: 1;
flex-direction: column;
padding: 1rem;
flex-grow: 1;
padding: 1rem;
}
.logo svg {
@@ -77,6 +132,7 @@ async function logout() {
.header {
display: flex;
align-items: center;
flex-shrink: 0;
background: var(--background);
box-shadow: 0 0 3px var(--shadow-weak-10);
@@ -105,11 +161,32 @@ async function logout() {
}
}
.actions {
display: flex;
align-items: center;
}
.userpanel {
display: flex;
align-items: center;
padding: 1rem;
font-weight: bold;
cursor: pointer;
}
.tooltip {
width: 10rem;
padding-bottom: .25rem;
.button {
width: 100%;
}
.shelf {
display: block;
box-sizing: border-box;
padding: .25rem .5rem;
}
}
.footer {

View File

@@ -1,7 +1,8 @@
// import config from 'config';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
const { argv } = yargs
const { argv } = yargs(hideBin(process.argv))
.command('npm start')
.option('log-level', {
alias: 'level',

View File

@@ -1,41 +1,80 @@
import knex from './knex';
import { fetchUsers } from './users';
import { verifyPrivilege } from './privileges';
import { HttpError } from './errors';
function curateDatabaseComment(comment, { users }) {
return {
id: comment.id,
body: comment.body,
parentId: comment.parent_id,
userId: comment.user_id,
user: users.find((user) => user.id === comment.user_id),
createdAt: comment.created_at,
};
}
function threadComments(thread, commentsByParentId) {
if (!thread) {
return [];
}
return thread.map((comment) => ({
...comment,
comments: threadComments(commentsByParentId[comment.id], commentsByParentId),
}));
}
function nestComments(comments) {
const commentsByParentId = comments.reduce((acc, comment) => {
if (!acc[comment.parentId]) {
acc[comment.parentId] = [];
}
acc[comment.parentId].push(comment);
return acc;
}, {});
return threadComments(commentsByParentId.null, commentsByParentId);
}
async function fetchPostComments(postId, { limit = 100 } = {}) {
const comments = await knex('comments')
.where('post_id', postId)
.orderBy('created_at', 'asc')
.orderBy('created_at', 'desc')
.limit(limit);
const users = await fetchUsers(comments.map((comment) => comment.user_id));
const curatedComments = comments.map((comment) => curateDatabaseComment(comment, { users }));
return comments.map((comment) => curateDatabaseComment(comment, { users }));
const nestedComments = nestComments(curatedComments);
return nestedComments;
}
async function addComment(comment, postId, user) {
await verifyPrivilege('addComment', user);
const commentEntry = await knex('comments')
if (!comment.body) {
throw new HttpError({
statusMessage: 'Comment cannot be empty',
statusCode: 400,
});
}
const [commentEntry] = await knex('comments')
.insert({
body: comment.body,
post_id: postId,
parent_id: comment.parentId,
user_id: user.id,
})
.returning('*');
console.log(comment, user);
return curateDatabaseComment(commentEntry);
const users = await fetchUsers([commentEntry.user_id]);
return curateDatabaseComment(commentEntry, { users });
}
export {

View File

@@ -3,45 +3,136 @@ import { verifyPrivilege } from './privileges';
import knex from './knex';
import { HttpError } from './errors';
import { fetchShelf } from './shelves';
import { fetchShelf, fetchShelves } from './shelves';
import { fetchUsers } from './users';
import { generateThumbnail } from './thumbnails';
import slugify from './utils/slugify';
function curatePost(post, { shelf, users }) {
import initLogger from './logger';
const logger = initLogger();
const emptyVote = {
tally: 0,
total: 0,
bump: false,
sink: false,
};
function curateDatabasePost(post, {
shelf, shelves, users, vote, votes,
}) {
const curatedPost = {
id: post.id,
title: post.title,
slug: slugify(post.title, { limit: 50 }),
body: post.body,
link: post.link,
shelfId: post.shelf_id,
createdAt: post.created_at,
shelf,
hasThumbnail: post.thumbnail,
shelf: shelf || shelves?.[post.shelf_id],
user: users.find((user) => user.id === post.user_id),
vote: vote || votes?.[post.id] || emptyVote,
commentCount: Number(post.comment_count),
};
return curatedPost;
}
async function fetchShelfPosts(shelfId, { limit = 100 } = {}) {
const shelf = await fetchShelf(shelfId);
function curatePostVote(vote) {
return {
tally: Number(vote.tally),
total: Number(vote.total),
bump: !!vote.bump,
sink: !!vote.sink,
};
}
async function fetchPostVotes(postIds, user) {
const votes = await knex('posts_votes')
.select(
'post_id',
knex.raw('sum(value) as tally'),
knex.raw('count(id) as total'),
...(user ? [
knex.raw('bool_or(user_id = :userId and value = 1) as bump', { userId: knex.raw(user.id) }),
knex.raw('bool_or(user_id = :userId and value = -1) as sink', { userId: knex.raw(user.id) })]
: []),
)
.whereIn('post_id', postIds)
.groupBy('post_id');
return Object.fromEntries(votes.map((vote) => [vote.post_id, curatePostVote(vote)]));
}
async function fetchShelfPosts(shelfIds, { user, limit = 100 } = {}) {
const shelves = await fetchShelves([].concat(shelfIds));
const posts = await knex('posts')
.select('posts.*', knex.raw('count(comments.id) as comment_count'))
.leftJoin('comments', 'comments.post_id', 'posts.id')
.where('shelf_id', shelf.id)
.whereIn('shelf_id', Object.keys(shelves))
.orderBy('created_at', 'desc')
.groupBy('posts.id')
.limit(limit);
const users = await fetchUsers(posts.map((post) => post.user_id));
const [users, votes] = await Promise.all([
fetchUsers(posts.map((post) => post.user_id)),
fetchPostVotes(posts.map((post) => post.id), user),
]);
return posts.map((post) => curatePost(post, { shelf, users }));
return posts.map((post) => curateDatabasePost(post, { shelves, users, votes }));
}
async function fetchPost(postId) {
async function fetchUserPosts(user, { limit = 20 } = {}) {
if (!user) {
throw new HttpError({
statusMessage: 'You are not logged in',
statusCode: 401,
});
}
const posts = await knex('shelves_subscriptions')
.select('posts.*', knex.raw('count(comments.id) as comment_count'))
.leftJoin('posts', 'posts.shelf_id', 'shelves_subscriptions.shelf_id')
.leftJoin('comments', 'comments.post_id', 'posts.id')
.where('shelves_subscriptions.user_id', user.id)
.groupBy('posts.id')
.orderBy('created_at', 'desc')
.limit(limit);
const [shelves, users, votes] = await Promise.all([
fetchShelves(posts.map((post) => post.shelf_id)),
fetchUsers(posts.map((post) => post.user_id)),
fetchPostVotes(posts.map((post) => post.id), user),
]);
return posts.map((post) => curateDatabasePost(post, { shelves, users, votes }));
}
async function fetchAllPosts({ user, limit = 20 } = {}) {
const posts = await knex('posts')
.select('posts.*', knex.raw('count(comments.id) as comment_count'))
.leftJoin('comments', 'comments.post_id', 'posts.id')
.orderBy('created_at', 'desc')
.groupBy('posts.id')
.limit(limit);
const [shelves, users, votes] = await Promise.all([
fetchShelves(posts.map((post) => post.shelf_id)),
fetchUsers(posts.map((post) => post.user_id)),
fetchPostVotes(posts.map((post) => post.id), user),
]);
return posts.map((post) => curateDatabasePost(post, { shelves, users, votes }));
}
async function fetchPost(postId, user) {
const post = await knex('posts')
.select('posts.*', knex.raw('count(comments.id) as comment_count'))
.leftJoin('comments', 'comments.post_id', 'posts.id')
.leftJoin('posts_votes', 'posts_votes.post_id', 'posts.id')
.where('posts.id', postId)
.groupBy('posts.id')
.first();
@@ -53,12 +144,39 @@ async function fetchPost(postId) {
});
}
const [shelf, users] = await Promise.all([
const [shelf, users, votes] = await Promise.all([
fetchShelf(post.shelf_id),
fetchUsers([post.user_id]),
fetchPostVotes([post.id], user),
]);
return curatePost(post, { shelf, users });
return curateDatabasePost(post, { shelf, users, votes });
}
async function votePost(postId, value, user) {
if (value === 0) {
await knex('posts_votes')
.where({
post_id: postId,
user_id: user.id,
})
.delete();
} else {
await knex('posts_votes')
.insert({
value,
post_id: postId,
user_id: user.id,
})
.onConflict(['post_id', 'user_id'])
.merge();
}
logger.silly(`User ${user.username} voted ${value} on post ${postId}`);
const votes = await fetchPostVotes([postId], user);
return votes[postId] || emptyVote;
}
async function createPost(post, shelfId, user) {
@@ -73,9 +191,7 @@ async function createPost(post, shelfId, user) {
});
}
console.log(post);
const postId = await knex('posts')
const [postEntry] = await knex('posts')
.insert({
title: post.title,
body: post.body,
@@ -83,13 +199,25 @@ async function createPost(post, shelfId, user) {
shelf_id: shelf.id,
user_id: user.id,
})
.returning('id');
.returning('*');
return postId;
const [users, vote] = await Promise.all([
fetchUsers([postEntry.user_id]),
votePost(postEntry.id, 1, user),
]);
logger.verbose(`User ${user.username} created post ${postEntry.id} on s/${shelf.slug}`);
generateThumbnail(postEntry.id);
return curateDatabasePost(postEntry, { shelf, users, vote });
}
export {
createPost,
fetchPost,
fetchShelfPosts,
fetchUserPosts,
fetchAllPosts,
votePost,
};

View File

@@ -1,4 +1,5 @@
import knex from './knex';
import { HttpError } from './errors';
function curateDatabaseShelf(shelf) {
if (!shelf) {
@@ -9,48 +10,132 @@ function curateDatabaseShelf(shelf) {
id: shelf.id,
slug: shelf.slug,
name: shelf.slug,
subscribed: !!shelf.subscribed,
};
}
async function fetchShelf(shelfId) {
function identityQuery(builder, shelfId) {
const id = Number(shelfId);
if (Number.isNaN(id)) {
builder.where('slug', shelfId);
return;
}
builder.where('id', shelfId);
}
function identitiesQuery(builder, shelfIds) {
const ids = Array.from(new Set(shelfIds.filter((shelfId) => !Number.isNaN(Number(shelfId)))));
const slugs = Array.from(new Set(shelfIds.filter((shelfId) => Number.isNaN(Number(shelfId)))));
builder
.whereIn('id', ids)
.orWhereIn('slug', slugs);
}
function isMemberQuery(builder, user) {
if (user) {
builder.select(knex.raw('shelves_subscriptions.id IS NOT NULL as subscribed'));
builder.leftJoin('shelves_subscriptions', (joinBuilder) => {
joinBuilder.on('shelf_id', 'shelves.id');
joinBuilder.andOnVal('user_id', user.id);
});
}
}
async function fetchShelf(shelfId, { user } = {}) {
const shelfEntry = await knex('shelves')
.where((builder) => {
const id = Number(shelfId);
if (Number.isNaN(id)) {
builder.where('slug', shelfId);
return;
}
builder.where('id', shelfId);
})
.select('shelves.*')
.modify((builder) => isMemberQuery(builder, user))
.where((builder) => identityQuery(builder, shelfId))
.first();
return curateDatabaseShelf(shelfEntry);
}
async function fetchShelves({ limit = 10 } = {}) {
const shelfEntries = await knex('shelves').limit(limit);
async function fetchAllShelves({ user, limit = 100 } = {}) {
const shelfEntries = await knex('shelves')
.select('shelves.*')
.modify((builder) => isMemberQuery(builder, user))
.orderBy('slug', 'asc')
.limit(limit);
return shelfEntries.map((shelfEntry) => curateDatabaseShelf(shelfEntry));
}
async function fetchShelves(shelfIds, { user } = {}) {
const shelfEntries = await knex('shelves')
.select('shelves.*')
.where((builder) => identitiesQuery(builder, shelfIds))
.modify((builder) => isMemberQuery(builder, user));
return Object.fromEntries(shelfEntries.map((shelfEntry) => [shelfEntry.id, curateDatabaseShelf(shelfEntry)]));
}
async function createShelf(shelf, user) {
const shelfEntry = await knex('shelves')
const [shelfEntry] = await knex('shelves')
.insert({
slug: shelf.slug,
founder_id: user.id,
})
.returning('*');
console.log('entry', shelfEntry);
return curateDatabaseShelf(shelfEntry);
}
async function subscribe(shelfId, user) {
const shelf = await fetchShelf(shelfId);
if (!shelf) {
throw new HttpError({
statusMessage: `Shelf ${shelfId} does not exist`,
statusCode: 404,
});
}
try {
await knex('shelves_subscriptions').insert({
shelf_id: shelf.id,
user_id: user.id,
});
} catch (error) {
if (error.code === '23505') {
throw new HttpError({
statusMessage: `You are already subscribed to s/${shelf.slug}`,
statusCode: 409,
});
}
throw error;
}
}
async function unsubscribe(shelfId, user) {
const shelf = await fetchShelf(shelfId);
if (!shelf) {
throw new HttpError({
statusMessage: `Shelf ${shelfId} does not exist`,
statusCode: 404,
});
}
await knex('shelves_subscriptions')
.where({
shelf_id: shelf.id,
user_id: user.id,
})
.delete();
}
export {
fetchShelf,
fetchShelves,
fetchAllShelves,
createShelf,
curateDatabaseShelf,
subscribe,
unsubscribe,
};

80
src/thumbnails.js Normal file
View File

@@ -0,0 +1,80 @@
import bhttp from 'bhttp';
import unprint from 'unprint';
import fs from 'fs';
import sharp from 'sharp';
import knex from './knex';
import initLogger from './logger';
const logger = initLogger();
async function createThumbnail(data, post) {
await fs.promises.mkdir('media/thumbnails', { recursive: true });
await sharp(data)
.resize(300, 300)
.jpeg({
quality: 80,
})
.toFile(`media/thumbnails/${post.id}.jpeg`);
await knex('posts')
.where('id', post.id)
.update('thumbnail', true);
logger.debug(`Saved thumbnail for ${post.id}`);
}
async function generateThumbnail(postId) {
const post = await knex('posts').where('id', postId).first();
if (!post) {
logger.warn(`Cannot generate thumbnail for non-existent post ${postId}`);
return;
}
if (!post.link) {
logger.debug(`Skipped thumbnail generation for text-only post ${postId}`);
return;
}
const res = await bhttp.get(post.link);
if (res.statusCode !== 200) {
logger.warn(`Failed thumbnail generation for ${post.link} from ${postId} (${res.statusCode})`);
return;
}
if (res.headers['content-type'].includes('image/')) {
await createThumbnail(res.body, post);
return;
}
const { query } = unprint.init(res.body.toString());
const ogHeader = query.attribute('meta[property="og:image"]', 'content');
if (ogHeader) {
const imgRes = await bhttp.get(ogHeader);
if (imgRes.statusCode === 200 && imgRes.headers['content-type'].includes('image/')) {
await createThumbnail(imgRes.body, post);
}
}
}
async function generateMissingThumbnails(force = false) {
const postsWithoutThumbnail = await knex('posts')
.select('id')
.modify((builder) => {
if (!force) {
builder.where('thumbnail', false);
}
});
await Promise.all(postsWithoutThumbnail.map(async (post) => generateThumbnail(post.id)));
}
export {
generateThumbnail,
generateMissingThumbnails,
};

View File

@@ -0,0 +1,9 @@
import { generateMissingThumbnails } from '../thumbnails';
import args from '../cli';
async function init() {
await generateMissingThumbnails(!!args.force);
process.exit();
}
init();

78
src/utils/slugify.js Executable file
View File

@@ -0,0 +1,78 @@
const substitutes = {
à: 'a',
á: 'a',
ä: 'a',
å: 'a',
ã: 'a',
æ: 'ae',
ç: 'c',
è: 'e',
é: 'e',
ë: 'e',
: 'e',
ì: 'i',
í: 'i',
ï: 'i',
ĩ: 'i',
ǹ: 'n',
ń: 'n',
ñ: 'n',
ò: 'o',
ó: 'o',
ö: 'o',
õ: 'o',
ø: 'o',
œ: 'oe',
ß: 'ss',
ù: 'u',
ú: 'u',
ü: 'u',
ũ: 'u',
: 'y',
ý: 'y',
ÿ: 'y',
: 'y',
};
function slugify(strings, {
delimiter = '-',
encode = false,
removeAccents = true,
removePunctuation = false,
limit = 1000,
} = {}) {
if (!strings || (typeof strings !== 'string' && !Array.isArray(strings))) {
return strings;
}
const slugComponents = []
.concat(strings)
.filter(Boolean)
.flatMap((string) => string
.trim()
.toLowerCase()
.replace(removePunctuation && /[.,:;'"_-]/g, '')
.match(/[A-Za-zÀ-ÖØ-öø-ÿ0-9]+/g));
if (!slugComponents) {
return '';
}
const slug = slugComponents.reduce((acc, component, index) => {
const accSlug = `${acc}${index > 0 ? delimiter : ''}${component}`;
if (accSlug.length < limit) {
if (removeAccents) {
return accSlug.replace(/[à-ÿ]/g, (match) => substitutes[match] || '');
}
return accSlug;
}
return acc;
}, '');
return encode ? encodeURI(slug) : slug;
}
export default slugify;

View File

@@ -1,4 +1,4 @@
import { createPost } from '../posts';
import { createPost, votePost } from '../posts';
async function createPostApi(req, res) {
const post = await createPost(req.body, req.params.shelfId, req.user);
@@ -6,6 +6,13 @@ async function createPostApi(req, res) {
res.send(post);
}
async function votePostApi(req, res) {
const votes = await votePost(req.params.postId, req.body.value, req.user);
res.send(votes);
}
export {
createPostApi as createPost,
votePostApi as votePost,
};

View File

@@ -23,9 +23,13 @@ import {
createUser,
} from './users';
import { createShelf } from './shelves';
import {
createShelf,
subscribe,
unsubscribe,
} from './shelves';
import { createPost } from './posts';
import { createPost, votePost } from './posts';
import { addComment } from './comments';
const logger = initLogger();
@@ -68,8 +72,13 @@ async function startServer() {
// SHELVES
router.post('/api/shelves', createShelf);
// MEMBERS
router.post('/api/shelves/:shelfId/members', subscribe);
router.delete('/api/shelves/:shelfId/members', unsubscribe);
// POSTS
router.post('/api/shelves/:shelfId/posts', createPost);
router.post('/api/posts/:postId/votes', votePost);
// COMMENTS
router.post('/api/posts/:postId/comments', addComment);

View File

@@ -1,11 +1,23 @@
import { createShelf } from '../shelves';
import { createShelf, subscribe, unsubscribe } from '../shelves';
async function createShelfApi(req) {
async function createShelfApi(req, res) {
const shelf = await createShelf(req.body, req.user);
return shelf;
res.send(shelf);
}
async function subscribeApi(req, res) {
await subscribe(req.params.shelfId, req.user);
res.status(204).send();
}
async function unsubscribeApi(req, res) {
await unsubscribe(req.params.shelfId, req.user);
res.status(204).send();
}
export {
createShelfApi as createShelf,
subscribeApi as subscribe,
unsubscribeApi as unsubscribe,
};

157
templates/shelves/shelf.vue Normal file
View File

@@ -0,0 +1,157 @@
<template>
<div class="page">
<header class="header">
<h2 class="title">
<a
:href="`/s/${shelf.slug}`"
class="nolink"
>s/{{ shelf.slug }}</a>
</h2>
</header>
<div class="body">
<slot />
<div class="sidebar">
<h4 class="sidebar-title">{{ shelf.slug }}</h4>
<button
v-if="subscribed"
class="button button-submit subscribe"
@click="unsubscribe"
>Unsubscribe</button>
<button
v-else
class="button button-submit subscribe"
@click="subscribe"
>Subscribe</button>
<form
class="form compose"
@submit.prevent="submitPost"
>
<div class="form-row">
<input
v-model="title"
placeholder="Title"
class="input"
>
</div>
<div class="form-row">
<input
v-model="link"
class="input"
placeholder="Link"
>
</div>
<div class="form-row">
<textarea
v-model="body"
placeholder="Body"
class="input body"
/>
</div>
<div class="form-actions">
<button
class="button button-submit"
:disabled="!body && !link"
>Post</button>
</div>
</form>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import * as api from '../../assets/js/api';
import { navigate } from '../../assets/js/navigate';
import { usePageContext } from '../../renderer/usePageContext';
const { routeParams } = usePageContext();
const props = defineProps({
shelf: {
type: Object,
default: null,
},
});
const title = ref();
const link = ref(null);
const body = ref(null);
const subscribed = ref(props.shelf.subscribed);
async function submitPost() {
const post = await api.post(`/shelves/${routeParams.id}/posts`, {
title: title.value,
link: link.value,
body: body.value,
});
navigate(`/s/${props.shelf.slug}/post/${post.id}/${post.slug}`);
}
async function subscribe() {
subscribed.value = true;
await api.post(`/shelves/${routeParams.id}/members`);
}
async function unsubscribe() {
subscribed.value = false;
await api.delete(`/shelves/${routeParams.id}/members`);
}
</script>
<style scoped>
.page {
display: flex;
flex-direction: column;
padding: 1rem
}
.body {
display: flex;
}
.content {
width: 100%;
display: flex;
flex-grow: 1;
}
.header {
padding: 1rem;
border-radius: .25rem;
margin-bottom: .5rem;
background: var(--background);
}
.title {
margin: 0;
font-size: 1.25rem;
}
.sidebar {
background: var(--background);
width: 20rem;
padding: .5rem;
border-radius: .25rem;
margin-left: .5rem;
}
.sidebar-title {
margin: 0 0 1rem 0;
font-size: 1.25rem;
}
.subscribe {
width: 100%;
margin-bottom: 1rem;
}
</style>