fix ogp rendering and refactor

This commit is contained in:
syuilo 2022-04-17 21:18:18 +09:00
parent 33c22b5f3e
commit 6d33b366f8
10 changed files with 51 additions and 37 deletions

View file

@ -1,6 +1,6 @@
import { Entity, Column, Index, OneToOne, JoinColumn, PrimaryColumn } from 'typeorm'; import { Entity, Column, Index, OneToOne, JoinColumn, PrimaryColumn } from 'typeorm';
import { DriveFile } from './drive-file.js';
import { id } from '../id.js'; import { id } from '../id.js';
import { DriveFile } from './drive-file.js';
@Entity() @Entity()
@Index(['usernameLower', 'host'], { unique: true }) @Index(['usernameLower', 'host'], { unique: true })
@ -207,7 +207,7 @@ export class User {
@Column('boolean', { @Column('boolean', {
default: false, default: false,
comment: 'Whether to show users replying to other users in the timeline' comment: 'Whether to show users replying to other users in the timeline',
}) })
public showTimelineReplies: boolean; public showTimelineReplies: boolean;

View file

@ -1,7 +1,6 @@
import { EntityRepository, Repository, In, Not } from 'typeorm'; import { EntityRepository, Repository, In, Not } from 'typeorm';
import Ajv from 'ajv'; import Ajv from 'ajv';
import { User, ILocalUser, IRemoteUser } from '@/models/entities/user.js'; import { User, ILocalUser, IRemoteUser } from '@/models/entities/user.js';
import { Notes, NoteUnreads, FollowRequests, Notifications, MessagingMessages, UserNotePinings, Followings, Blockings, Mutings, UserProfiles, UserSecurityKeys, UserGroupJoinings, Pages, Announcements, AnnouncementReads, Antennas, AntennaNotes, ChannelFollowings, Instances, DriveFiles } from '../index.js';
import config from '@/config/index.js'; import config from '@/config/index.js';
import { Packed } from '@/misc/schema.js'; import { Packed } from '@/misc/schema.js';
import { awaitAll, Promiseable } from '@/prelude/await-all.js'; import { awaitAll, Promiseable } from '@/prelude/await-all.js';
@ -9,8 +8,9 @@ import { populateEmojis } from '@/misc/populate-emojis.js';
import { getAntennas } from '@/misc/antenna-cache.js'; import { getAntennas } from '@/misc/antenna-cache.js';
import { USER_ACTIVE_THRESHOLD, USER_ONLINE_THRESHOLD } from '@/const.js'; import { USER_ACTIVE_THRESHOLD, USER_ONLINE_THRESHOLD } from '@/const.js';
import { Cache } from '@/misc/cache.js'; import { Cache } from '@/misc/cache.js';
import { Instance } from '../entities/instance.js';
import { db } from '@/db/postgre.js'; import { db } from '@/db/postgre.js';
import { Instance } from '../entities/instance.js';
import { Notes, NoteUnreads, FollowRequests, Notifications, MessagingMessages, UserNotePinings, Followings, Blockings, Mutings, UserProfiles, UserSecurityKeys, UserGroupJoinings, Pages, Announcements, AnnouncementReads, Antennas, AntennaNotes, ChannelFollowings, Instances, DriveFiles } from '../index.js';
const userInstanceCache = new Cache<Instance | null>(1000 * 60 * 60 * 3); const userInstanceCache = new Cache<Instance | null>(1000 * 60 * 60 * 3);
@ -112,7 +112,7 @@ export const UserRepository = db.getRepository(User).extend({
const joinings = await UserGroupJoinings.findBy({ userId: userId }); const joinings = await UserGroupJoinings.findBy({ userId: userId });
const groupQs = Promise.all(joinings.map(j => MessagingMessages.createQueryBuilder('message') const groupQs = Promise.all(joinings.map(j => MessagingMessages.createQueryBuilder('message')
.where(`message.groupId = :groupId`, { groupId: j.userGroupId }) .where('message.groupId = :groupId', { groupId: j.userGroupId })
.andWhere('message.userId != :userId', { userId: userId }) .andWhere('message.userId != :userId', { userId: userId })
.andWhere('NOT (:userId = ANY(message.reads))', { userId: userId }) .andWhere('NOT (:userId = ANY(message.reads))', { userId: userId })
.andWhere('message.createdAt > :joinedAt', { joinedAt: j.createdAt }) // 自分が加入する前の会話については、未読扱いしない .andWhere('message.createdAt > :joinedAt', { joinedAt: j.createdAt }) // 自分が加入する前の会話については、未読扱いしない
@ -204,8 +204,18 @@ export const UserRepository = db.getRepository(User).extend({
); );
}, },
getAvatarUrl(user: User): string { async getAvatarUrl(user: User): Promise<string> {
// TODO: avatarIdがあるがavatarがない(JOINされてない)場合のハンドリング if (user.avatar) {
return DriveFiles.getPublicUrl(user.avatar, true) || this.getIdenticonUrl(user.id);
} else if (user.avatarId) {
const avatar = await DriveFiles.findOneByOrFail({ id: user.avatarId });
return DriveFiles.getPublicUrl(avatar, true) || this.getIdenticonUrl(user.id);
} else {
return this.getIdenticonUrl(user.id);
}
},
getAvatarUrlSync(user: User): string {
if (user.avatar) { if (user.avatar) {
return DriveFiles.getPublicUrl(user.avatar, true) || this.getIdenticonUrl(user.id); return DriveFiles.getPublicUrl(user.avatar, true) || this.getIdenticonUrl(user.id);
} else { } else {
@ -223,7 +233,7 @@ export const UserRepository = db.getRepository(User).extend({
options?: { options?: {
detail?: D, detail?: D,
includeSecrets?: boolean, includeSecrets?: boolean,
} },
): Promise<IsMeAndIsUserDetailed<ExpectsMe, D>> { ): Promise<IsMeAndIsUserDetailed<ExpectsMe, D>> {
const opts = Object.assign({ const opts = Object.assign({
detail: false, detail: false,
@ -274,7 +284,7 @@ export const UserRepository = db.getRepository(User).extend({
name: user.name, name: user.name,
username: user.username, username: user.username,
host: user.host, host: user.host,
avatarUrl: this.getAvatarUrl(user), avatarUrl: this.getAvatarUrlSync(user),
avatarBlurhash: user.avatar?.blurhash || null, avatarBlurhash: user.avatar?.blurhash || null,
avatarColor: null, // 後方互換性のため avatarColor: null, // 後方互換性のため
isAdmin: user.isAdmin || falsy, isAdmin: user.isAdmin || falsy,
@ -283,7 +293,7 @@ export const UserRepository = db.getRepository(User).extend({
isCat: user.isCat || falsy, isCat: user.isCat || falsy,
instance: user.host ? userInstanceCache.fetch(user.host, instance: user.host ? userInstanceCache.fetch(user.host,
() => Instances.findOneBy({ host: user.host! }), () => Instances.findOneBy({ host: user.host! }),
v => v != null v => v != null,
).then(instance => instance ? { ).then(instance => instance ? {
name: instance.name, name: instance.name,
softwareName: instance.softwareName, softwareName: instance.softwareName,
@ -403,7 +413,7 @@ export const UserRepository = db.getRepository(User).extend({
options?: { options?: {
detail?: D, detail?: D,
includeSecrets?: boolean, includeSecrets?: boolean,
} },
): Promise<IsUserDetailed<D>[]> { ): Promise<IsUserDetailed<D>[]> {
return Promise.all(users.map(u => this.pack(u, me, options))); return Promise.all(users.map(u => this.pack(u, me, options)));
}, },

View file

@ -9,7 +9,7 @@ import { publishMainStream } from '@/services/stream.js';
export default function(ctx: Koa.Context, user: ILocalUser, redirect = false) { export default function(ctx: Koa.Context, user: ILocalUser, redirect = false) {
if (redirect) { if (redirect) {
//#region Cookie //#region Cookie
ctx.cookies.set('igi', user.token, { ctx.cookies.set('igi', user.token!, {
path: '/', path: '/',
// SEE: https://github.com/koajs/koa/issues/974 // SEE: https://github.com/koajs/koa/issues/974
// When using a SSL proxy it should be configured to add the "X-Forwarded-Proto: https" header // When using a SSL proxy it should be configured to add the "X-Forwarded-Proto: https" header

View file

@ -10,23 +10,23 @@ import mount from 'koa-mount';
import koaLogger from 'koa-logger'; import koaLogger from 'koa-logger';
import * as slow from 'koa-slow'; import * as slow from 'koa-slow';
import activityPub from './activitypub.js'; import { IsNull } from 'typeorm';
import nodeinfo from './nodeinfo.js';
import wellKnown from './well-known.js';
import config from '@/config/index.js'; import config from '@/config/index.js';
import apiServer from './api/index.js';
import fileServer from './file/index.js';
import proxyServer from './proxy/index.js';
import webServer from './web/index.js';
import Logger from '@/services/logger.js'; import Logger from '@/services/logger.js';
import { envOption } from '../env.js';
import { UserProfiles, Users } from '@/models/index.js'; import { UserProfiles, Users } from '@/models/index.js';
import { genIdenticon } from '@/misc/gen-identicon.js'; import { genIdenticon } from '@/misc/gen-identicon.js';
import { createTemp } from '@/misc/create-temp.js'; import { createTemp } from '@/misc/create-temp.js';
import { publishMainStream } from '@/services/stream.js'; import { publishMainStream } from '@/services/stream.js';
import * as Acct from '@/misc/acct.js'; import * as Acct from '@/misc/acct.js';
import { envOption } from '../env.js';
import activityPub from './activitypub.js';
import nodeinfo from './nodeinfo.js';
import wellKnown from './well-known.js';
import apiServer from './api/index.js';
import fileServer from './file/index.js';
import proxyServer from './proxy/index.js';
import webServer from './web/index.js';
import { initializeStreamingServer } from './api/streaming.js'; import { initializeStreamingServer } from './api/streaming.js';
import { IsNull } from 'typeorm';
export const serverLogger = new Logger('server', 'gray', false); export const serverLogger = new Logger('server', 'gray', false);
@ -81,7 +81,7 @@ router.get('/avatar/@:acct', async ctx => {
}); });
if (user) { if (user) {
ctx.redirect(Users.getAvatarUrl(user)); ctx.redirect(Users.getAvatarUrlSync(user));
} else { } else {
ctx.redirect('/static-assets/user-unknown.png'); ctx.redirect('/static-assets/user-unknown.png');
} }

View file

@ -1,8 +1,8 @@
import { Feed } from 'feed'; import { Feed } from 'feed';
import { In, IsNull } from 'typeorm';
import config from '@/config/index.js'; import config from '@/config/index.js';
import { User } from '@/models/entities/user.js'; import { User } from '@/models/entities/user.js';
import { Notes, DriveFiles, UserProfiles } from '@/models/index.js'; import { Notes, DriveFiles, UserProfiles, Users } from '@/models/index.js';
import { In, IsNull } from 'typeorm';
export default async function(user: User) { export default async function(user: User) {
const author = { const author = {
@ -29,7 +29,7 @@ export default async function(user: User) {
generator: 'Misskey', generator: 'Misskey',
description: `${user.notesCount} Notes, ${profile.ffVisibility === 'public' ? user.followingCount : '?'} Following, ${profile.ffVisibility === 'public' ? user.followersCount : '?'} Followers${profile.description ? ` · ${profile.description}` : ''}`, description: `${user.notesCount} Notes, ${profile.ffVisibility === 'public' ? user.followingCount : '?'} Following, ${profile.ffVisibility === 'public' ? user.followersCount : '?'} Followers${profile.description ? ` · ${profile.description}` : ''}`,
link: author.link, link: author.link,
image: user.avatarUrl ? user.avatarUrl : undefined, image: await Users.getAvatarUrl(user),
feedLinks: { feedLinks: {
json: `${author.link}.json`, json: `${author.link}.json`,
atom: `${author.link}.atom`, atom: `${author.link}.atom`,

View file

@ -14,17 +14,17 @@ import { createBullBoard } from '@bull-board/api';
import { BullAdapter } from '@bull-board/api/bullAdapter.js'; import { BullAdapter } from '@bull-board/api/bullAdapter.js';
import { KoaAdapter } from '@bull-board/koa'; import { KoaAdapter } from '@bull-board/koa';
import packFeed from './feed.js'; import { IsNull } from 'typeorm';
import { fetchMeta } from '@/misc/fetch-meta.js'; import { fetchMeta } from '@/misc/fetch-meta.js';
import { genOpenapiSpec } from '../api/openapi/gen-spec.js';
import config from '@/config/index.js'; import config from '@/config/index.js';
import { Users, Notes, UserProfiles, Pages, Channels, Clips, GalleryPosts } from '@/models/index.js'; import { Users, Notes, UserProfiles, Pages, Channels, Clips, GalleryPosts } from '@/models/index.js';
import * as Acct from '@/misc/acct.js'; import * as Acct from '@/misc/acct.js';
import { getNoteSummary } from '@/misc/get-note-summary.js'; import { getNoteSummary } from '@/misc/get-note-summary.js';
import { queues } from '@/queue/queues.js';
import { genOpenapiSpec } from '../api/openapi/gen-spec.js';
import { urlPreviewHandler } from './url-preview.js'; import { urlPreviewHandler } from './url-preview.js';
import { manifestHandler } from './manifest.js'; import { manifestHandler } from './manifest.js';
import { queues } from '@/queue/queues.js'; import packFeed from './feed.js';
import { IsNull } from 'typeorm';
const _filename = fileURLToPath(import.meta.url); const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename); const _dirname = dirname(_filename);
@ -127,7 +127,7 @@ router.get('/twemoji/(.*)', async ctx => {
return; return;
} }
ctx.set('Content-Security-Policy', `default-src 'none'; style-src 'unsafe-inline'`); ctx.set('Content-Security-Policy', 'default-src \'none\'; style-src \'unsafe-inline\'');
await send(ctx as any, path, { await send(ctx as any, path, {
root: `${_dirname}/../../../node_modules/@discordapp/twemoji/dist/svg/`, root: `${_dirname}/../../../node_modules/@discordapp/twemoji/dist/svg/`,
@ -235,6 +235,7 @@ router.get(['/@:user', '/@:user/:sub'], async (ctx, next) => {
await ctx.render('user', { await ctx.render('user', {
user, profile, me, user, profile, me,
avatarUrl: await Users.getAvatarUrl(user),
sub: ctx.params.sub, sub: ctx.params.sub,
instanceName: meta.name || 'Misskey', instanceName: meta.name || 'Misskey',
icon: meta.iconUrl, icon: meta.iconUrl,
@ -274,6 +275,7 @@ router.get('/notes/:note', async (ctx, next) => {
await ctx.render('note', { await ctx.render('note', {
note: _note, note: _note,
profile, profile,
avatarUrl: await Users.getAvatarUrl(await Users.findOneByOrFail({ id: note.userId })),
// TODO: Let locale changeable by instance setting // TODO: Let locale changeable by instance setting
summary: getNoteSummary(_note), summary: getNoteSummary(_note),
instanceName: meta.name || 'Misskey', instanceName: meta.name || 'Misskey',
@ -315,6 +317,7 @@ router.get('/@:user/pages/:page', async (ctx, next) => {
await ctx.render('page', { await ctx.render('page', {
page: _page, page: _page,
profile, profile,
avatarUrl: await Users.getAvatarUrl(await Users.findOneByOrFail({ id: page.userId })),
instanceName: meta.name || 'Misskey', instanceName: meta.name || 'Misskey',
icon: meta.iconUrl, icon: meta.iconUrl,
themeColor: meta.themeColor, themeColor: meta.themeColor,
@ -346,6 +349,7 @@ router.get('/clips/:clip', async (ctx, next) => {
await ctx.render('clip', { await ctx.render('clip', {
clip: _clip, clip: _clip,
profile, profile,
avatarUrl: await Users.getAvatarUrl(await Users.findOneByOrFail({ id: clip.userId })),
instanceName: meta.name || 'Misskey', instanceName: meta.name || 'Misskey',
icon: meta.iconUrl, icon: meta.iconUrl,
themeColor: meta.themeColor, themeColor: meta.themeColor,
@ -370,6 +374,7 @@ router.get('/gallery/:post', async (ctx, next) => {
await ctx.render('gallery-post', { await ctx.render('gallery-post', {
post: _post, post: _post,
profile, profile,
avatarUrl: await Users.getAvatarUrl(await Users.findOneByOrFail({ id: post.userId })),
instanceName: meta.name || 'Misskey', instanceName: meta.name || 'Misskey',
icon: meta.iconUrl, icon: meta.iconUrl,
themeColor: meta.themeColor, themeColor: meta.themeColor,
@ -434,7 +439,7 @@ router.get('/cli', async ctx => {
}); });
}); });
const override = (source: string, target: string, depth: number = 0) => const override = (source: string, target: string, depth = 0) =>
[, ...target.split('/').filter(x => x), ...source.split('/').filter(x => x).splice(depth)].join('/'); [, ...target.split('/').filter(x => x), ...source.split('/').filter(x => x).splice(depth)].join('/');
router.get('/flush', async ctx => { router.get('/flush', async ctx => {

View file

@ -16,7 +16,7 @@ block og
meta(property='og:title' content= title) meta(property='og:title' content= title)
meta(property='og:description' content= clip.description) meta(property='og:description' content= clip.description)
meta(property='og:url' content= url) meta(property='og:url' content= url)
meta(property='og:image' content= user.avatarUrl) meta(property='og:image' content= avatarUrl)
block meta block meta
if profile.noCrawle if profile.noCrawle

View file

@ -17,7 +17,7 @@ block og
meta(property='og:title' content= title) meta(property='og:title' content= title)
meta(property='og:description' content= summary) meta(property='og:description' content= summary)
meta(property='og:url' content= url) meta(property='og:url' content= url)
meta(property='og:image' content= user.avatarUrl) meta(property='og:image' content= avatarUrl)
block meta block meta
if user.host || isRenote || profile.noCrawle if user.host || isRenote || profile.noCrawle

View file

@ -16,7 +16,7 @@ block og
meta(property='og:title' content= title) meta(property='og:title' content= title)
meta(property='og:description' content= page.summary) meta(property='og:description' content= page.summary)
meta(property='og:url' content= url) meta(property='og:url' content= url)
meta(property='og:image' content= page.eyeCatchingImage ? page.eyeCatchingImage.thumbnailUrl : user.avatarUrl) meta(property='og:image' content= page.eyeCatchingImage ? page.eyeCatchingImage.thumbnailUrl : avatarUrl)
block meta block meta
if profile.noCrawle if profile.noCrawle

View file

@ -3,7 +3,6 @@ extends ./base
block vars block vars
- const title = user.name ? `${user.name} (@${user.username})` : `@${user.username}`; - const title = user.name ? `${user.name} (@${user.username})` : `@${user.username}`;
- const url = `${config.url}/@${(user.host ? `${user.username}@${user.host}` : user.username)}`; - const url = `${config.url}/@${(user.host ? `${user.username}@${user.host}` : user.username)}`;
- const img = user.avatarUrl || null;
block title block title
= `${title} | ${instanceName}` = `${title} | ${instanceName}`
@ -16,7 +15,7 @@ block og
meta(property='og:title' content= title) meta(property='og:title' content= title)
meta(property='og:description' content= profile.description) meta(property='og:description' content= profile.description)
meta(property='og:url' content= url) meta(property='og:url' content= url)
meta(property='og:image' content= img) meta(property='og:image' content= avatarUrl)
block meta block meta
if user.host || profile.noCrawle if user.host || profile.noCrawle