Merge branch 'develop' of https://github.com/misskey-dev/misskey into develop
This commit is contained in:
commit
c4429ca65e
9 changed files with 156 additions and 126 deletions
|
@ -3,3 +3,4 @@ coverage:
|
||||||
project:
|
project:
|
||||||
default:
|
default:
|
||||||
only_pulls: true
|
only_pulls: true
|
||||||
|
if_ci_failed: success
|
||||||
|
|
|
@ -1490,6 +1490,7 @@ _ago:
|
||||||
weeksAgo: "{n}週間前"
|
weeksAgo: "{n}週間前"
|
||||||
monthsAgo: "{n}ヶ月前"
|
monthsAgo: "{n}ヶ月前"
|
||||||
yearsAgo: "{n}年前"
|
yearsAgo: "{n}年前"
|
||||||
|
invalid: "ありません"
|
||||||
|
|
||||||
_time:
|
_time:
|
||||||
second: "秒"
|
second: "秒"
|
||||||
|
|
|
@ -15,8 +15,8 @@
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"eslint": "eslint --quiet \"src/**/*.ts\"",
|
"eslint": "eslint --quiet \"src/**/*.ts\"",
|
||||||
"lint": "pnpm typecheck && pnpm eslint",
|
"lint": "pnpm typecheck && pnpm eslint",
|
||||||
"jest": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --forceExit --runInBand",
|
"jest": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --forceExit --runInBand --detectOpenHandles",
|
||||||
"jest-and-coverage": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --coverage --forceExit --runInBand",
|
"jest-and-coverage": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --coverage --forceExit --runInBand --detectOpenHandles",
|
||||||
"jest-clear": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --clearCache",
|
"jest-clear": "cross-env NODE_ENV=test node --experimental-vm-modules --experimental-import-meta-resolve node_modules/jest/bin/jest.js --clearCache",
|
||||||
"test": "pnpm jest",
|
"test": "pnpm jest",
|
||||||
"test-and-coverage": "pnpm jest-and-coverage"
|
"test-and-coverage": "pnpm jest-and-coverage"
|
||||||
|
|
|
@ -28,6 +28,101 @@ type PrivateKey = {
|
||||||
keyId: string;
|
keyId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export class ApRequestCreator {
|
||||||
|
static createSignedPost(args: { key: PrivateKey, url: string, body: string, additionalHeaders: Record<string, string> }): Signed {
|
||||||
|
const u = new URL(args.url);
|
||||||
|
const digestHeader = `SHA-256=${crypto.createHash('sha256').update(args.body).digest('base64')}`;
|
||||||
|
|
||||||
|
const request: Request = {
|
||||||
|
url: u.href,
|
||||||
|
method: 'POST',
|
||||||
|
headers: this.#objectAssignWithLcKey({
|
||||||
|
'Date': new Date().toUTCString(),
|
||||||
|
'Host': u.host,
|
||||||
|
'Content-Type': 'application/activity+json',
|
||||||
|
'Digest': digestHeader,
|
||||||
|
}, args.additionalHeaders),
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = this.#signToRequest(request, args.key, ['(request-target)', 'date', 'host', 'digest']);
|
||||||
|
|
||||||
|
return {
|
||||||
|
request,
|
||||||
|
signingString: result.signingString,
|
||||||
|
signature: result.signature,
|
||||||
|
signatureHeader: result.signatureHeader,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static createSignedGet(args: { key: PrivateKey, url: string, additionalHeaders: Record<string, string> }): Signed {
|
||||||
|
const u = new URL(args.url);
|
||||||
|
|
||||||
|
const request: Request = {
|
||||||
|
url: u.href,
|
||||||
|
method: 'GET',
|
||||||
|
headers: this.#objectAssignWithLcKey({
|
||||||
|
'Accept': 'application/activity+json, application/ld+json',
|
||||||
|
'Date': new Date().toUTCString(),
|
||||||
|
'Host': new URL(args.url).host,
|
||||||
|
}, args.additionalHeaders),
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = this.#signToRequest(request, args.key, ['(request-target)', 'date', 'host', 'accept']);
|
||||||
|
|
||||||
|
return {
|
||||||
|
request,
|
||||||
|
signingString: result.signingString,
|
||||||
|
signature: result.signature,
|
||||||
|
signatureHeader: result.signatureHeader,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static #signToRequest(request: Request, key: PrivateKey, includeHeaders: string[]): Signed {
|
||||||
|
const signingString = this.#genSigningString(request, includeHeaders);
|
||||||
|
const signature = crypto.sign('sha256', Buffer.from(signingString), key.privateKeyPem).toString('base64');
|
||||||
|
const signatureHeader = `keyId="${key.keyId}",algorithm="rsa-sha256",headers="${includeHeaders.join(' ')}",signature="${signature}"`;
|
||||||
|
|
||||||
|
request.headers = this.#objectAssignWithLcKey(request.headers, {
|
||||||
|
Signature: signatureHeader,
|
||||||
|
});
|
||||||
|
// node-fetch will generate this for us. if we keep 'Host', it won't change with redirects!
|
||||||
|
delete request.headers['host'];
|
||||||
|
|
||||||
|
return {
|
||||||
|
request,
|
||||||
|
signingString,
|
||||||
|
signature,
|
||||||
|
signatureHeader,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static #genSigningString(request: Request, includeHeaders: string[]): string {
|
||||||
|
request.headers = this.#lcObjectKey(request.headers);
|
||||||
|
|
||||||
|
const results: string[] = [];
|
||||||
|
|
||||||
|
for (const key of includeHeaders.map(x => x.toLowerCase())) {
|
||||||
|
if (key === '(request-target)') {
|
||||||
|
results.push(`(request-target): ${request.method.toLowerCase()} ${new URL(request.url).pathname}`);
|
||||||
|
} else {
|
||||||
|
results.push(`${key}: ${request.headers[key]}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
static #lcObjectKey(src: Record<string, string>): Record<string, string> {
|
||||||
|
const dst: Record<string, string> = {};
|
||||||
|
for (const key of Object.keys(src).filter(x => x !== '__proto__' && typeof src[x] === 'string')) dst[key.toLowerCase()] = src[key];
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
static #objectAssignWithLcKey(a: Record<string, string>, b: Record<string, string>): Record<string, string> {
|
||||||
|
return Object.assign(this.#lcObjectKey(a), this.#lcObjectKey(b));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ApRequestService {
|
export class ApRequestService {
|
||||||
private logger: Logger;
|
private logger: Logger;
|
||||||
|
@ -44,112 +139,13 @@ export class ApRequestService {
|
||||||
this.logger = this.loggerService?.getLogger('ap-request'); // なぜか TypeError: Cannot read properties of undefined (reading 'getLogger') と言われる
|
this.logger = this.loggerService?.getLogger('ap-request'); // なぜか TypeError: Cannot read properties of undefined (reading 'getLogger') と言われる
|
||||||
}
|
}
|
||||||
|
|
||||||
@bindThis
|
|
||||||
private createSignedPost(args: { key: PrivateKey, url: string, body: string, additionalHeaders: Record<string, string> }): Signed {
|
|
||||||
const u = new URL(args.url);
|
|
||||||
const digestHeader = `SHA-256=${crypto.createHash('sha256').update(args.body).digest('base64')}`;
|
|
||||||
|
|
||||||
const request: Request = {
|
|
||||||
url: u.href,
|
|
||||||
method: 'POST',
|
|
||||||
headers: this.objectAssignWithLcKey({
|
|
||||||
'Date': new Date().toUTCString(),
|
|
||||||
'Host': u.host,
|
|
||||||
'Content-Type': 'application/activity+json',
|
|
||||||
'Digest': digestHeader,
|
|
||||||
}, args.additionalHeaders),
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = this.signToRequest(request, args.key, ['(request-target)', 'date', 'host', 'digest']);
|
|
||||||
|
|
||||||
return {
|
|
||||||
request,
|
|
||||||
signingString: result.signingString,
|
|
||||||
signature: result.signature,
|
|
||||||
signatureHeader: result.signatureHeader,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@bindThis
|
|
||||||
private createSignedGet(args: { key: PrivateKey, url: string, additionalHeaders: Record<string, string> }): Signed {
|
|
||||||
const u = new URL(args.url);
|
|
||||||
|
|
||||||
const request: Request = {
|
|
||||||
url: u.href,
|
|
||||||
method: 'GET',
|
|
||||||
headers: this.objectAssignWithLcKey({
|
|
||||||
'Accept': 'application/activity+json, application/ld+json',
|
|
||||||
'Date': new Date().toUTCString(),
|
|
||||||
'Host': new URL(args.url).host,
|
|
||||||
}, args.additionalHeaders),
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = this.signToRequest(request, args.key, ['(request-target)', 'date', 'host', 'accept']);
|
|
||||||
|
|
||||||
return {
|
|
||||||
request,
|
|
||||||
signingString: result.signingString,
|
|
||||||
signature: result.signature,
|
|
||||||
signatureHeader: result.signatureHeader,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@bindThis
|
|
||||||
private signToRequest(request: Request, key: PrivateKey, includeHeaders: string[]): Signed {
|
|
||||||
const signingString = this.genSigningString(request, includeHeaders);
|
|
||||||
const signature = crypto.sign('sha256', Buffer.from(signingString), key.privateKeyPem).toString('base64');
|
|
||||||
const signatureHeader = `keyId="${key.keyId}",algorithm="rsa-sha256",headers="${includeHeaders.join(' ')}",signature="${signature}"`;
|
|
||||||
|
|
||||||
request.headers = this.objectAssignWithLcKey(request.headers, {
|
|
||||||
Signature: signatureHeader,
|
|
||||||
});
|
|
||||||
// node-fetch will generate this for us. if we keep 'Host', it won't change with redirects!
|
|
||||||
delete request.headers['host'];
|
|
||||||
|
|
||||||
return {
|
|
||||||
request,
|
|
||||||
signingString,
|
|
||||||
signature,
|
|
||||||
signatureHeader,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@bindThis
|
|
||||||
private genSigningString(request: Request, includeHeaders: string[]): string {
|
|
||||||
request.headers = this.lcObjectKey(request.headers);
|
|
||||||
|
|
||||||
const results: string[] = [];
|
|
||||||
|
|
||||||
for (const key of includeHeaders.map(x => x.toLowerCase())) {
|
|
||||||
if (key === '(request-target)') {
|
|
||||||
results.push(`(request-target): ${request.method.toLowerCase()} ${new URL(request.url).pathname}`);
|
|
||||||
} else {
|
|
||||||
results.push(`${key}: ${request.headers[key]}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return results.join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
@bindThis
|
|
||||||
private lcObjectKey(src: Record<string, string>): Record<string, string> {
|
|
||||||
const dst: Record<string, string> = {};
|
|
||||||
for (const key of Object.keys(src).filter(x => x !== '__proto__' && typeof src[x] === 'string')) dst[key.toLowerCase()] = src[key];
|
|
||||||
return dst;
|
|
||||||
}
|
|
||||||
|
|
||||||
@bindThis
|
|
||||||
private objectAssignWithLcKey(a: Record<string, string>, b: Record<string, string>): Record<string, string> {
|
|
||||||
return Object.assign(this.lcObjectKey(a), this.lcObjectKey(b));
|
|
||||||
}
|
|
||||||
|
|
||||||
@bindThis
|
@bindThis
|
||||||
public async signedPost(user: { id: User['id'] }, url: string, object: any) {
|
public async signedPost(user: { id: User['id'] }, url: string, object: any) {
|
||||||
const body = JSON.stringify(object);
|
const body = JSON.stringify(object);
|
||||||
|
|
||||||
const keypair = await this.userKeypairStoreService.getUserKeypair(user.id);
|
const keypair = await this.userKeypairStoreService.getUserKeypair(user.id);
|
||||||
|
|
||||||
const req = this.createSignedPost({
|
const req = ApRequestCreator.createSignedPost({
|
||||||
key: {
|
key: {
|
||||||
privateKeyPem: keypair.privateKey,
|
privateKeyPem: keypair.privateKey,
|
||||||
keyId: `${this.config.url}/users/${user.id}#main-key`,
|
keyId: `${this.config.url}/users/${user.id}#main-key`,
|
||||||
|
@ -176,7 +172,7 @@ export class ApRequestService {
|
||||||
public async signedGet(url: string, user: { id: User['id'] }) {
|
public async signedGet(url: string, user: { id: User['id'] }) {
|
||||||
const keypair = await this.userKeypairStoreService.getUserKeypair(user.id);
|
const keypair = await this.userKeypairStoreService.getUserKeypair(user.id);
|
||||||
|
|
||||||
const req = this.createSignedGet({
|
const req = ApRequestCreator.createSignedGet({
|
||||||
key: {
|
key: {
|
||||||
privateKeyPem: keypair.privateKey,
|
privateKeyPem: keypair.privateKey,
|
||||||
keyId: `${this.config.url}/users/${user.id}#main-key`,
|
keyId: `${this.config.url}/users/${user.id}#main-key`,
|
||||||
|
|
|
@ -79,6 +79,12 @@ export const meta = {
|
||||||
code: 'YOU_HAVE_BEEN_BLOCKED',
|
code: 'YOU_HAVE_BEEN_BLOCKED',
|
||||||
id: 'b390d7e1-8a5e-46ed-b625-06271cafd3d3',
|
id: 'b390d7e1-8a5e-46ed-b625-06271cafd3d3',
|
||||||
},
|
},
|
||||||
|
|
||||||
|
noSuchFile: {
|
||||||
|
message: 'Some files are not found.',
|
||||||
|
code: 'NO_SUCH_FILE',
|
||||||
|
id: 'b6992544-63e7-67f0-fa7f-32444b1b5306',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
@ -207,6 +213,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
|
||||||
.orderBy('array_position(ARRAY[:...fileIds], "id"::text)')
|
.orderBy('array_position(ARRAY[:...fileIds], "id"::text)')
|
||||||
.setParameters({ fileIds })
|
.setParameters({ fileIds })
|
||||||
.getMany();
|
.getMany();
|
||||||
|
|
||||||
|
if (files.length !== fileIds.length) {
|
||||||
|
throw new ApiError(meta.errors.noSuchFile);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let renote: Note | null = null;
|
let renote: Note | null = null;
|
||||||
|
|
|
@ -37,6 +37,7 @@
|
||||||
},
|
},
|
||||||
"compileOnSave": false,
|
"compileOnSave": false,
|
||||||
"include": [
|
"include": [
|
||||||
"./**/*.ts"
|
"./**/*.ts",
|
||||||
|
"../src/@types/**/*.ts",
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
import * as assert from 'assert';
|
import * as assert from 'assert';
|
||||||
import httpSignature from '@peertube/http-signature';
|
import httpSignature from '@peertube/http-signature';
|
||||||
import { genRsaKeyPair } from '../../src/misc/gen-key-pair.js';
|
|
||||||
import { createSignedPost, createSignedGet } from '../../src/activitypub/ap-request.js';
|
import { genRsaKeyPair } from '@/misc/gen-key-pair.js';
|
||||||
|
import { ApRequestCreator } from '@/core/activitypub/ApRequestService.js';
|
||||||
|
|
||||||
export const buildParsedSignature = (signingString: string, signature: string, algorithm: string) => {
|
export const buildParsedSignature = (signingString: string, signature: string, algorithm: string) => {
|
||||||
return {
|
return {
|
||||||
|
@ -9,7 +10,7 @@ export const buildParsedSignature = (signingString: string, signature: string, a
|
||||||
params: {
|
params: {
|
||||||
keyId: 'KeyID', // dummy, not used for verify
|
keyId: 'KeyID', // dummy, not used for verify
|
||||||
algorithm: algorithm,
|
algorithm: algorithm,
|
||||||
headers: [ '(request-target)', 'date', 'host', 'digest' ], // dummy, not used for verify
|
headers: ['(request-target)', 'date', 'host', 'digest'], // dummy, not used for verify
|
||||||
signature: signature,
|
signature: signature,
|
||||||
},
|
},
|
||||||
signingString: signingString,
|
signingString: signingString,
|
||||||
|
@ -29,7 +30,7 @@ describe('ap-request', () => {
|
||||||
'User-Agent': 'UA',
|
'User-Agent': 'UA',
|
||||||
};
|
};
|
||||||
|
|
||||||
const req = createSignedPost({ key, url, body, additionalHeaders: headers });
|
const req = ApRequestCreator.createSignedPost({ key, url, body, additionalHeaders: headers });
|
||||||
|
|
||||||
const parsed = buildParsedSignature(req.signingString, req.signature, 'rsa-sha256');
|
const parsed = buildParsedSignature(req.signingString, req.signature, 'rsa-sha256');
|
||||||
|
|
||||||
|
@ -45,7 +46,7 @@ describe('ap-request', () => {
|
||||||
'User-Agent': 'UA',
|
'User-Agent': 'UA',
|
||||||
};
|
};
|
||||||
|
|
||||||
const req = createSignedGet({ key, url, additionalHeaders: headers });
|
const req = ApRequestCreator.createSignedGet({ key, url, additionalHeaders: headers });
|
||||||
|
|
||||||
const parsed = buildParsedSignature(req.signingString, req.signature, 'rsa-sha256');
|
const parsed = buildParsedSignature(req.signingString, req.signature, 'rsa-sha256');
|
||||||
|
|
|
@ -1,12 +1,25 @@
|
||||||
<template>
|
<template>
|
||||||
<div v-if="playerEnabled" :class="$style.player" :style="`padding: ${(player.height || 0) / (player.width || 1) * 100}% 0 0`">
|
<template v-if="playerEnabled">
|
||||||
<button :class="$style.disablePlayer" :title="i18n.ts.disablePlayer" @click="playerEnabled = false"><i class="ti ti-x"></i></button>
|
<div :class="$style.player" :style="`padding: ${(player.height || 0) / (player.width || 1) * 100}% 0 0`">
|
||||||
<iframe v-if="player.url.startsWith('http://') || player.url.startsWith('https://')" :class="$style.playerIframe" :src="player.url + (player.url.match(/\?/) ? '&autoplay=1&auto_play=1' : '?autoplay=1&auto_play=1')" :width="player.width || '100%'" :heigth="player.height || 250" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen/>
|
<iframe v-if="player.url.startsWith('http://') || player.url.startsWith('https://')" :class="$style.playerIframe" :src="player.url + (player.url.match(/\?/) ? '&autoplay=1&auto_play=1' : '?autoplay=1&auto_play=1')" :width="player.width || '100%'" :heigth="player.height || 250" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen/>
|
||||||
<span v-else>invalid url</span>
|
<span v-else>invalid url</span>
|
||||||
</div>
|
</div>
|
||||||
<div v-else-if="tweetId && tweetExpanded" ref="twitter" :class="$style.twitter">
|
<div :class="$style.action">
|
||||||
|
<MkButton :small="true" inline @click="playerEnabled = false">
|
||||||
|
<i class="ti ti-x"></i> {{ i18n.ts.disablePlayer }}
|
||||||
|
</MkButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="tweetId && tweetExpanded">
|
||||||
|
<div ref="twitter" :class="$style.twitter">
|
||||||
<iframe ref="tweet" scrolling="no" frameborder="no" :style="{ position: 'relative', width: '100%', height: `${tweetHeight}px` }" :src="`https://platform.twitter.com/embed/index.html?embedId=${embedId}&hideCard=false&hideThread=false&lang=en&theme=${$store.state.darkMode ? 'dark' : 'light'}&id=${tweetId}`"></iframe>
|
<iframe ref="tweet" scrolling="no" frameborder="no" :style="{ position: 'relative', width: '100%', height: `${tweetHeight}px` }" :src="`https://platform.twitter.com/embed/index.html?embedId=${embedId}&hideCard=false&hideThread=false&lang=en&theme=${$store.state.darkMode ? 'dark' : 'light'}&id=${tweetId}`"></iframe>
|
||||||
</div>
|
</div>
|
||||||
|
<div :class="$style.action">
|
||||||
|
<MkButton :small="true" inline @click="tweetExpanded = false">
|
||||||
|
<i class="ti ti-x"></i> {{ i18n.ts.close }}
|
||||||
|
</MkButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
<div v-else :class="$style.urlPreview">
|
<div v-else :class="$style.urlPreview">
|
||||||
<component :is="self ? 'MkA' : 'a'" :class="[$style.link, { [$style.compact]: compact }]" :[attr]="self ? url.substr(local.length) : url" rel="nofollow noopener" :target="target" :title="url">
|
<component :is="self ? 'MkA' : 'a'" :class="[$style.link, { [$style.compact]: compact }]" :[attr]="self ? url.substr(local.length) : url" rel="nofollow noopener" :target="target" :title="url">
|
||||||
<div v-if="thumbnail" :class="$style.thumbnail" :style="`background-image: url('${thumbnail}')`">
|
<div v-if="thumbnail" :class="$style.thumbnail" :style="`background-image: url('${thumbnail}')`">
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
<template>
|
<template>
|
||||||
<time :title="absolute">
|
<time :title="absolute">
|
||||||
<template v-if="mode === 'relative'">{{ relative }}</template>
|
<template v-if="invalid">{{ i18n.ts._ago.invalid }}</template>
|
||||||
|
<template v-else-if="mode === 'relative'">{{ relative }}</template>
|
||||||
<template v-else-if="mode === 'absolute'">{{ absolute }}</template>
|
<template v-else-if="mode === 'absolute'">{{ absolute }}</template>
|
||||||
<template v-else-if="mode === 'detail'">{{ absolute }} ({{ relative }})</template>
|
<template v-else-if="mode === 'detail'">{{ absolute }} ({{ relative }})</template>
|
||||||
</time>
|
</time>
|
||||||
|
@ -12,18 +13,24 @@ import { i18n } from '@/i18n';
|
||||||
import { dateTimeFormat } from '@/scripts/intl-const';
|
import { dateTimeFormat } from '@/scripts/intl-const';
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{
|
const props = withDefaults(defineProps<{
|
||||||
time: Date | string;
|
time: Date | string | number | null;
|
||||||
mode?: 'relative' | 'absolute' | 'detail';
|
mode?: 'relative' | 'absolute' | 'detail';
|
||||||
}>(), {
|
}>(), {
|
||||||
mode: 'relative',
|
mode: 'relative',
|
||||||
});
|
});
|
||||||
|
|
||||||
const _time = typeof props.time === 'string' ? new Date(props.time) : props.time;
|
const _time = props.time == null ? NaN :
|
||||||
const absolute = dateTimeFormat.format(_time);
|
typeof props.time === 'number' ? props.time :
|
||||||
|
(props.time instanceof Date ? props.time : new Date(props.time)).getTime();
|
||||||
|
const invalid = Number.isNaN(_time);
|
||||||
|
const absolute = !invalid ? dateTimeFormat.format(_time) : i18n.ts._ago.invalid;
|
||||||
|
|
||||||
let now = $shallowRef(new Date());
|
let now = $ref((new Date()).getTime());
|
||||||
const relative = $computed(() => {
|
const relative = $computed<string>(() => {
|
||||||
const ago = (now.getTime() - _time.getTime()) / 1000/*ms*/;
|
if (props.mode === 'absolute') return ''; // absoluteではrelativeを使わないので計算しない
|
||||||
|
if (invalid) return i18n.ts._ago.invalid;
|
||||||
|
|
||||||
|
const ago = (now - _time) / 1000/*ms*/;
|
||||||
return (
|
return (
|
||||||
ago >= 31536000 ? i18n.t('_ago.yearsAgo', { n: Math.round(ago / 31536000).toString() }) :
|
ago >= 31536000 ? i18n.t('_ago.yearsAgo', { n: Math.round(ago / 31536000).toString() }) :
|
||||||
ago >= 2592000 ? i18n.t('_ago.monthsAgo', { n: Math.round(ago / 2592000).toString() }) :
|
ago >= 2592000 ? i18n.t('_ago.monthsAgo', { n: Math.round(ago / 2592000).toString() }) :
|
||||||
|
@ -39,8 +46,8 @@ const relative = $computed(() => {
|
||||||
let tickId: number;
|
let tickId: number;
|
||||||
|
|
||||||
function tick() {
|
function tick() {
|
||||||
now = new Date();
|
now = (new Date()).getTime();
|
||||||
const ago = (now.getTime() - _time.getTime()) / 1000/*ms*/;
|
const ago = (now - _time) / 1000/*ms*/;
|
||||||
const next = ago < 60 ? 10000 : ago < 3600 ? 60000 : 180000;
|
const next = ago < 60 ? 10000 : ago < 3600 ? 60000 : 180000;
|
||||||
|
|
||||||
tickId = window.setTimeout(tick, next);
|
tickId = window.setTimeout(tick, next);
|
||||||
|
|
Loading…
Reference in a new issue