chore: lint and update package name

This commit is contained in:
Mar0xy 2023-09-24 17:36:13 +02:00
parent 410e6515d3
commit db6dc1b52e
No known key found for this signature in database
GPG key ID: 56569BBE47D2C828
12 changed files with 1636 additions and 1683 deletions

View file

@ -1,10 +1,10 @@
{ {
"name": "misskey", "name": "sharkey",
"version": "2023.9.0-beta.10", "version": "2023.9.0-beta.10",
"codename": "nasubi", "codename": "nasubi",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/misskey-dev/misskey.git" "url": "https://github.com/transfem-org/sharkey.git"
}, },
"packageManager": "pnpm@8.7.6", "packageManager": "pnpm@8.7.6",
"workspaces": [ "workspaces": [

View file

@ -1,6 +1,6 @@
import { Entity } from 'megalodon'; import { Entity } from 'megalodon';
const CHAR_COLLECTION: string = '0123456789abcdefghijklmnopqrstuvwxyz'; const CHAR_COLLECTION = '0123456789abcdefghijklmnopqrstuvwxyz';
export enum IdConvertType { export enum IdConvertType {
MastodonId, MastodonId,
@ -8,48 +8,50 @@ export enum IdConvertType {
} }
export function convertId(in_id: string, id_convert_type: IdConvertType): string { export function convertId(in_id: string, id_convert_type: IdConvertType): string {
switch (id_convert_type) { switch (id_convert_type) {
case IdConvertType.MastodonId: case IdConvertType.MastodonId: {
let out: bigint = BigInt(0); let out = BigInt(0);
const lowerCaseId = in_id.toLowerCase(); const lowerCaseId = in_id.toLowerCase();
for (let i = 0; i < lowerCaseId.length; i++) { for (let i = 0; i < lowerCaseId.length; i++) {
const charValue = numFromChar(lowerCaseId.charAt(i)); const charValue = numFromChar(lowerCaseId.charAt(i));
out += BigInt(charValue) * BigInt(36) ** BigInt(i); out += BigInt(charValue) * BigInt(36) ** BigInt(i);
} }
return out.toString(); return out.toString();
}
case IdConvertType.SharkeyId: case IdConvertType.SharkeyId: {
let input: bigint = BigInt(in_id); let input = BigInt(in_id);
let outStr = ''; let outStr = '';
while (input > BigInt(0)) { while (input > BigInt(0)) {
const remainder = Number(input % BigInt(36)); const remainder = Number(input % BigInt(36));
outStr = charFromNum(remainder) + outStr; outStr = charFromNum(remainder) + outStr;
input /= BigInt(36); input /= BigInt(36);
} }
let ReversedoutStr = outStr.split('').reduce((acc, char) => char + acc, ''); const ReversedoutStr = outStr.split('').reduce((acc, char) => char + acc, '');
return ReversedoutStr; return ReversedoutStr;
}
default: default:
throw new Error('Invalid ID conversion type'); throw new Error('Invalid ID conversion type');
} }
} }
function numFromChar(character: string): number { function numFromChar(character: string): number {
for (let i = 0; i < CHAR_COLLECTION.length; i++) { for (let i = 0; i < CHAR_COLLECTION.length; i++) {
if (CHAR_COLLECTION.charAt(i) === character) { if (CHAR_COLLECTION.charAt(i) === character) {
return i; return i;
} }
} }
throw new Error('Invalid character in parsed base36 id'); throw new Error('Invalid character in parsed base36 id');
} }
function charFromNum(number: number): string { function charFromNum(number: number): string {
if (number >= 0 && number < CHAR_COLLECTION.length) { if (number >= 0 && number < CHAR_COLLECTION.length) {
return CHAR_COLLECTION.charAt(number); return CHAR_COLLECTION.charAt(number);
} else { } else {
throw new Error('Invalid number for base-36 encoding'); throw new Error('Invalid number for base-36 encoding');
} }
} }
function simpleConvert(data: any) { function simpleConvert(data: any) {
@ -81,8 +83,7 @@ export function convertFeaturedTag(tag: Entity.FeaturedTag) {
export function convertNotification(notification: Entity.Notification) { export function convertNotification(notification: Entity.Notification) {
notification.account = convertAccount(notification.account); notification.account = convertAccount(notification.account);
notification.id = convertId(notification.id, IdConvertType.MastodonId); notification.id = convertId(notification.id, IdConvertType.MastodonId);
if (notification.status) if (notification.status) notification.status = convertStatus(notification.status);
notification.status = convertStatus(notification.status);
return notification; return notification;
} }
@ -102,13 +103,11 @@ export function convertRelationship(relationship: Entity.Relationship) {
export function convertStatus(status: Entity.Status) { export function convertStatus(status: Entity.Status) {
status.account = convertAccount(status.account); status.account = convertAccount(status.account);
status.id = convertId(status.id, IdConvertType.MastodonId); status.id = convertId(status.id, IdConvertType.MastodonId);
if (status.in_reply_to_account_id) if (status.in_reply_to_account_id) status.in_reply_to_account_id = convertId(
status.in_reply_to_account_id = convertId( status.in_reply_to_account_id,
status.in_reply_to_account_id, IdConvertType.MastodonId,
IdConvertType.MastodonId, );
); if (status.in_reply_to_id) status.in_reply_to_id = convertId(status.in_reply_to_id, IdConvertType.MastodonId);
if (status.in_reply_to_id)
status.in_reply_to_id = convertId(status.in_reply_to_id, IdConvertType.MastodonId);
status.media_attachments = status.media_attachments.map((attachment) => status.media_attachments = status.media_attachments.map((attachment) =>
convertAttachment(attachment), convertAttachment(attachment),
); );

View file

@ -1,17 +1,17 @@
import { apiAuthMastodon } from './endpoints/auth.js'; import { ApiAuthMastodon } from './endpoints/auth.js';
import { apiAccountMastodon } from './endpoints/account.js'; import { ApiAccountMastodon } from './endpoints/account.js';
import { apiSearchMastodon } from './endpoints/search.js'; import { ApiSearchMastodon } from './endpoints/search.js';
import { apiNotifyMastodon } from './endpoints/notifications.js'; import { ApiNotifyMastodon } from './endpoints/notifications.js';
import { apiFilterMastodon } from './endpoints/filter.js'; import { ApiFilterMastodon } from './endpoints/filter.js';
import { apiTimelineMastodon } from './endpoints/timeline.js'; import { ApiTimelineMastodon } from './endpoints/timeline.js';
import { apiStatusMastodon } from './endpoints/status.js'; import { ApiStatusMastodon } from './endpoints/status.js';
export { export {
apiAccountMastodon, ApiAccountMastodon,
apiAuthMastodon, ApiAuthMastodon,
apiSearchMastodon, ApiSearchMastodon,
apiNotifyMastodon, ApiNotifyMastodon,
apiFilterMastodon, ApiFilterMastodon,
apiTimelineMastodon, ApiTimelineMastodon,
apiStatusMastodon ApiStatusMastodon,
} };

View file

@ -1,7 +1,7 @@
import { convertId, IdConvertType as IdType, convertAccount, convertRelationship, convertStatus } from '../converters.js';
import { argsToBools, convertTimelinesArgsId, limitToInt } from './timeline.js';
import type { MegalodonInterface } from 'megalodon'; import type { MegalodonInterface } from 'megalodon';
import type { FastifyRequest } from 'fastify'; import type { FastifyRequest } from 'fastify';
import { argsToBools, convertTimelinesArgsId, limitToInt } from './timeline.js';
import { convertId, IdConvertType as IdType, convertAccount, convertRelationship, convertStatus } from '../converters.js';
const relationshipModel = { const relationshipModel = {
id: '', id: '',
@ -20,21 +20,21 @@ const relationshipModel = {
note: '', note: '',
}; };
export class apiAccountMastodon { export class ApiAccountMastodon {
private request: FastifyRequest; private request: FastifyRequest;
private client: MegalodonInterface; private client: MegalodonInterface;
private BASE_URL: string; private BASE_URL: string;
constructor(request: FastifyRequest, client: MegalodonInterface, BASE_URL: string) { constructor(request: FastifyRequest, client: MegalodonInterface, BASE_URL: string) {
this.request = request; this.request = request;
this.client = client; this.client = client;
this.BASE_URL = BASE_URL; this.BASE_URL = BASE_URL;
} }
public async verifyCredentials() { public async verifyCredentials() {
try { try {
const data = await this.client.verifyAccountCredentials(); const data = await this.client.verifyAccountCredentials();
let acct = data.data; const acct = data.data;
acct.id = convertId(acct.id, IdType.MastodonId); acct.id = convertId(acct.id, IdType.MastodonId);
acct.display_name = acct.display_name || acct.username; acct.display_name = acct.display_name || acct.username;
acct.url = `${this.BASE_URL}/@${acct.url}`; acct.url = `${this.BASE_URL}/@${acct.url}`;
@ -56,230 +56,230 @@ export class apiAccountMastodon {
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async updateCredentials() { public async updateCredentials() {
try { try {
const data = await this.client.updateCredentials(this.request.body as any); const data = await this.client.updateCredentials(this.request.body as any);
return convertAccount(data.data); return convertAccount(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async lookup() { public async lookup() {
try { try {
const data = await this.client.search((this.request.query as any).acct, { type: 'accounts' }); const data = await this.client.search((this.request.query as any).acct, { type: 'accounts' });
return convertAccount(data.data.accounts[0]); return convertAccount(data.data.accounts[0]);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getRelationships(users: [string]) { public async getRelationships(users: [string]) {
try { try {
relationshipModel.id = users?.toString() || '1'; relationshipModel.id = users.toString() || '1';
if (!users) { if (!(users.length > 0)) {
return [relationshipModel]; return [relationshipModel];
} }
let reqIds = []; const reqIds = [];
for (let i = 0; i < users.length; i++) { for (let i = 0; i < users.length; i++) {
reqIds.push(convertId(users[i], IdType.SharkeyId)); reqIds.push(convertId(users[i], IdType.SharkeyId));
} }
const data = await this.client.getRelationships(reqIds); const data = await this.client.getRelationships(reqIds);
return data.data.map((relationship) => convertRelationship(relationship)); return data.data.map((relationship) => convertRelationship(relationship));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getStatuses() { public async getStatuses() {
try { try {
const data = await this.client.getAccountStatuses( const data = await this.client.getAccountStatuses(
convertId((this.request.params as any).id, IdType.SharkeyId), convertId((this.request.params as any).id, IdType.SharkeyId),
convertTimelinesArgsId(argsToBools(limitToInt(this.request.query as any))) convertTimelinesArgsId(argsToBools(limitToInt(this.request.query as any))),
); );
return data.data.map((status) => convertStatus(status)); return data.data.map((status) => convertStatus(status));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getFollowers() { public async getFollowers() {
try { try {
const data = await this.client.getAccountFollowers( const data = await this.client.getAccountFollowers(
convertId((this.request.params as any).id, IdType.SharkeyId), convertId((this.request.params as any).id, IdType.SharkeyId),
convertTimelinesArgsId(limitToInt(this.request.query as any)) convertTimelinesArgsId(limitToInt(this.request.query as any)),
); );
return data.data.map((account) => convertAccount(account)); return data.data.map((account) => convertAccount(account));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getFollowing() { public async getFollowing() {
try { try {
const data = await this.client.getAccountFollowing( const data = await this.client.getAccountFollowing(
convertId((this.request.params as any).id, IdType.SharkeyId), convertId((this.request.params as any).id, IdType.SharkeyId),
convertTimelinesArgsId(limitToInt(this.request.query as any)) convertTimelinesArgsId(limitToInt(this.request.query as any)),
); );
return data.data.map((account) => convertAccount(account)); return data.data.map((account) => convertAccount(account));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async addFollow() { public async addFollow() {
try { try {
const data = await this.client.followAccount( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.followAccount( convertId((this.request.params as any).id, IdType.SharkeyId) );
let acct = convertRelationship(data.data); const acct = convertRelationship(data.data);
acct.following = true; acct.following = true;
return acct; return acct;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async rmFollow() { public async rmFollow() {
try { try {
const data = await this.client.unfollowAccount( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.unfollowAccount( convertId((this.request.params as any).id, IdType.SharkeyId) );
let acct = convertRelationship(data.data); const acct = convertRelationship(data.data);
acct.following = false; acct.following = false;
return acct; return acct;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async addBlock() { public async addBlock() {
try { try {
const data = await this.client.blockAccount( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.blockAccount( convertId((this.request.params as any).id, IdType.SharkeyId) );
return convertRelationship(data.data); return convertRelationship(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async rmBlock() { public async rmBlock() {
try { try {
const data = await this.client.unblockAccount( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.unblockAccount( convertId((this.request.params as any).id, IdType.SharkeyId) );
return convertRelationship(data.data); return convertRelationship(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async addMute() { public async addMute() {
try { try {
const data = await this.client.muteAccount( const data = await this.client.muteAccount(
convertId((this.request.params as any).id, IdType.SharkeyId), convertId((this.request.params as any).id, IdType.SharkeyId),
this.request.body as any this.request.body as any,
); );
return convertRelationship(data.data); return convertRelationship(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async rmMute() { public async rmMute() {
try { try {
const data = await this.client.unmuteAccount( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.unmuteAccount( convertId((this.request.params as any).id, IdType.SharkeyId) );
return convertRelationship(data.data); return convertRelationship(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getBookmarks() { public async getBookmarks() {
try { try {
const data = await this.client.getBookmarks( convertTimelinesArgsId(limitToInt(this.request.query as any)) ); const data = await this.client.getBookmarks( convertTimelinesArgsId(limitToInt(this.request.query as any)) );
return data.data.map((status) => convertStatus(status)); return data.data.map((status) => convertStatus(status));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getFavourites() { public async getFavourites() {
try { try {
const data = await this.client.getFavourites( convertTimelinesArgsId(limitToInt(this.request.query as any)) ); const data = await this.client.getFavourites( convertTimelinesArgsId(limitToInt(this.request.query as any)) );
return data.data.map((status) => convertStatus(status)); return data.data.map((status) => convertStatus(status));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getMutes() { public async getMutes() {
try { try {
const data = await this.client.getMutes( convertTimelinesArgsId(limitToInt(this.request.query as any)) ); const data = await this.client.getMutes( convertTimelinesArgsId(limitToInt(this.request.query as any)) );
return data.data.map((account) => convertAccount(account)); return data.data.map((account) => convertAccount(account));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async getBlocks() { public async getBlocks() {
try { try {
const data = await this.client.getBlocks( convertTimelinesArgsId(limitToInt(this.request.query as any)) ); const data = await this.client.getBlocks( convertTimelinesArgsId(limitToInt(this.request.query as any)) );
return data.data.map((account) => convertAccount(account)); return data.data.map((account) => convertAccount(account));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async acceptFollow() { public async acceptFollow() {
try { try {
const data = await this.client.acceptFollowRequest( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.acceptFollowRequest( convertId((this.request.params as any).id, IdType.SharkeyId) );
return convertRelationship(data.data); return convertRelationship(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
public async rejectFollow() { public async rejectFollow() {
try { try {
const data = await this.client.rejectFollowRequest( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.rejectFollowRequest( convertId((this.request.params as any).id, IdType.SharkeyId) );
return convertRelationship(data.data); return convertRelationship(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
return e.response.data; return e.response.data;
} }
} }
} }

View file

@ -39,36 +39,36 @@ const writeScope = [
'write:gallery-likes', 'write:gallery-likes',
]; ];
export async function apiAuthMastodon(request: FastifyRequest, client: MegalodonInterface) { export async function ApiAuthMastodon(request: FastifyRequest, client: MegalodonInterface) {
const body: any = request.body || request.query; const body: any = request.body || request.query;
try { try {
let scope = body.scopes; let scope = body.scopes;
if (typeof scope === 'string') scope = scope.split(' '); if (typeof scope === 'string') scope = scope.split(' ');
const pushScope = new Set<string>(); const pushScope = new Set<string>();
for (const s of scope) { for (const s of scope) {
if (s.match(/^read/)) for (const r of readScope) pushScope.add(r); if (s.match(/^read/)) for (const r of readScope) pushScope.add(r);
if (s.match(/^write/)) for (const r of writeScope) pushScope.add(r); if (s.match(/^write/)) for (const r of writeScope) pushScope.add(r);
}
const scopeArr = Array.from(pushScope);
const red = body.redirect_uris;
const appData = await client.registerApp(body.client_name, {
scopes: scopeArr,
redirect_uris: red,
website: body.website,
});
const returns = {
id: Math.floor(Math.random() * 100).toString(),
name: appData.name,
website: body.website,
redirect_uri: red,
client_id: Buffer.from(appData.url || '').toString('base64'),
client_secret: appData.clientSecret,
};
return returns;
} catch (e: any) {
console.error(e);
return e.response.data;
} }
const scopeArr = Array.from(pushScope);
const red = body.redirect_uris;
const appData = await client.registerApp(body.client_name, {
scopes: scopeArr,
redirect_uris: red,
website: body.website,
});
const returns = {
id: Math.floor(Math.random() * 100).toString(),
name: appData.name,
website: body.website,
redirect_uri: red,
client_id: Buffer.from(appData.url || '').toString('base64'),
client_secret: appData.clientSecret,
};
return returns;
} catch (e: any) {
console.error(e);
return e.response.data;
}
} }

View file

@ -1,65 +1,65 @@
import { IdConvertType as IdType, convertId, convertFilter } from '../converters.js';
import type { MegalodonInterface } from 'megalodon'; import type { MegalodonInterface } from 'megalodon';
import type { FastifyRequest } from 'fastify'; import type { FastifyRequest } from 'fastify';
import { IdConvertType as IdType, convertId, convertFilter } from '../converters.js';
export class apiFilterMastodon { export class ApiFilterMastodon {
private request: FastifyRequest; private request: FastifyRequest;
private client: MegalodonInterface; private client: MegalodonInterface;
constructor(request: FastifyRequest, client: MegalodonInterface) { constructor(request: FastifyRequest, client: MegalodonInterface) {
this.request = request; this.request = request;
this.client = client; this.client = client;
} }
public async getFilters() { public async getFilters() {
try { try {
const data = await this.client.getFilters(); const data = await this.client.getFilters();
return data.data.map((filter) => convertFilter(filter)); return data.data.map((filter) => convertFilter(filter));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async getFilter() { public async getFilter() {
try { try {
const data = await this.client.getFilter( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.getFilter( convertId((this.request.params as any).id, IdType.SharkeyId) );
return convertFilter(data.data); return convertFilter(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async createFilter() { public async createFilter() {
try { try {
const body: any = this.request.body; const body: any = this.request.body;
const data = await this.client.createFilter(body.pharse, body.context, body); const data = await this.client.createFilter(body.pharse, body.context, body);
return convertFilter(data.data); return convertFilter(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async updateFilter() { public async updateFilter() {
try { try {
const body: any = this.request.body; const body: any = this.request.body;
const data = await this.client.updateFilter(convertId((this.request.params as any).id, IdType.SharkeyId), body.pharse, body.context); const data = await this.client.updateFilter(convertId((this.request.params as any).id, IdType.SharkeyId), body.pharse, body.context);
return convertFilter(data.data); return convertFilter(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async rmFilter() { public async rmFilter() {
try { try {
const data = await this.client.deleteFilter( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.deleteFilter( convertId((this.request.params as any).id, IdType.SharkeyId) );
return data.data; return data.data;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
} }

View file

@ -6,8 +6,8 @@ import type { MiMeta } from '@/models/Meta.js';
export async function getInstance( export async function getInstance(
response: Entity.Instance, response: Entity.Instance,
contact: Entity.Account, contact: Entity.Account,
config: Config, config: Config,
meta: MiMeta, meta: MiMeta,
) { ) {
return { return {
uri: config.url, uri: config.url,
@ -16,7 +16,7 @@ export async function getInstance(
meta.description?.substring(0, 50) || 'See real server website', meta.description?.substring(0, 50) || 'See real server website',
description: description:
meta.description || meta.description ||
"This is a vanilla Sharkey Instance. It doesn't seem to have a description.", 'This is a vanilla Sharkey Instance. It doesn\'t seem to have a description.',
email: response.email || '', email: response.email || '',
version: `3.0.0 (compatible; Sharkey ${config.version})`, version: `3.0.0 (compatible; Sharkey ${config.version})`,
urls: response.urls, urls: response.urls,
@ -60,4 +60,4 @@ export async function getInstance(
contact_account: contact, contact_account: contact,
rules: [], rules: [],
}; };
} }

View file

@ -1,71 +1,71 @@
import type { MegalodonInterface } from 'megalodon';
import type { FastifyRequest } from 'fastify';
import { convertTimelinesArgsId } from './timeline.js';
import { IdConvertType as IdType, convertId, convertNotification } from '../converters.js'; import { IdConvertType as IdType, convertId, convertNotification } from '../converters.js';
import { convertTimelinesArgsId } from './timeline.js';
import type { MegalodonInterface, Entity } from 'megalodon';
import type { FastifyRequest } from 'fastify';
function toLimitToInt(q: any) { function toLimitToInt(q: any) {
if (q.limit) if (typeof q.limit === 'string') q.limit = parseInt(q.limit, 10); if (q.limit) if (typeof q.limit === 'string') q.limit = parseInt(q.limit, 10);
return q; return q;
} }
export class apiNotifyMastodon { export class ApiNotifyMastodon {
private request: FastifyRequest; private request: FastifyRequest;
private client: MegalodonInterface; private client: MegalodonInterface;
constructor(request: FastifyRequest, client: MegalodonInterface) { constructor(request: FastifyRequest, client: MegalodonInterface) {
this.request = request; this.request = request;
this.client = client; this.client = client;
} }
public async getNotifications() { public async getNotifications() {
try { try {
const data = await this.client.getNotifications( convertTimelinesArgsId(toLimitToInt(this.request.query)) ); const data = await this.client.getNotifications( convertTimelinesArgsId(toLimitToInt(this.request.query)) );
const notifs = data.data; const notifs = data.data;
const processed = notifs.map((n) => { const processed = notifs.map((n: Entity.Notification) => {
n = convertNotification(n); let convertedn = convertNotification(n);
if (n.type !== 'follow' && n.type !== 'follow_request') { if (convertedn.type !== 'follow' && convertedn.type !== 'follow_request') {
if (n.type === 'reaction') n.type = 'favourite'; if (convertedn.type === 'reaction') convertedn.type = 'favourite';
return n; return convertedn;
} else { } else {
return n; return convertedn;
} }
}); });
return processed; return processed;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async getNotification() { public async getNotification() {
try { try {
const data = await this.client.getNotification( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.getNotification( convertId((this.request.params as any).id, IdType.SharkeyId) );
const notif = convertNotification(data.data); const notif = convertNotification(data.data);
if (notif.type !== 'follow' && notif.type !== 'follow_request' && notif.type === 'reaction') notif.type = 'favourite'; if (notif.type !== 'follow' && notif.type !== 'follow_request' && notif.type === 'reaction') notif.type = 'favourite';
return notif; return notif;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async rmNotification() { public async rmNotification() {
try { try {
const data = await this.client.dismissNotification( convertId((this.request.params as any).id, IdType.SharkeyId) ); const data = await this.client.dismissNotification( convertId((this.request.params as any).id, IdType.SharkeyId) );
return data.data; return data.data;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async rmNotifications() { public async rmNotifications() {
try { try {
const data = await this.client.dismissNotifications(); const data = await this.client.dismissNotifications();
return data.data; return data.data;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
} }

View file

@ -1,30 +1,29 @@
import type { MegalodonInterface } from 'megalodon'; import { Converter } from 'megalodon';
import { Converter } from 'megalodon';
import type { FastifyRequest } from 'fastify';
import { convertTimelinesArgsId, limitToInt } from './timeline.js';
import { convertAccount, convertStatus } from '../converters.js'; import { convertAccount, convertStatus } from '../converters.js';
import { convertTimelinesArgsId, limitToInt } from './timeline.js';
import type { MegalodonInterface } from 'megalodon';
import type { FastifyRequest } from 'fastify';
async function getHighlight( async function getHighlight(
BASE_URL: string, BASE_URL: string,
domain: string, domain: string,
accessTokens: string | undefined, accessTokens: string | undefined,
) { ) {
const accessTokenArr = accessTokens?.split(" ") ?? [null]; const accessTokenArr = accessTokens?.split(' ') ?? [null];
const accessToken = accessTokenArr[accessTokenArr.length - 1]; const accessToken = accessTokenArr[accessTokenArr.length - 1];
try { try {
const apicall = await fetch(`${BASE_URL}/api/notes/featured`, const apicall = await fetch(`${BASE_URL}/api/notes/featured`,
{ {
method: 'POST', method: 'POST',
headers: { headers: {
'Accept': 'application/json, text/plain, */*', 'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json' 'Content-Type': 'application/json',
}, },
body: JSON.stringify({i: accessToken}) body: JSON.stringify({ i: accessToken }),
}); });
const api = await apicall.json(); const api = await apicall.json();
const data: MisskeyEntity.Note[] = api; const data: MisskeyEntity.Note[] = api;
return data.map((note) => Converter.note(note, domain)); return data.map((note) => Converter.note(note, domain));
} catch (e: any) { } catch (e: any) {
console.log(e); console.log(e);
console.log(e.response.data); console.log(e.response.data);
@ -33,76 +32,76 @@ async function getHighlight(
} }
async function getFeaturedUser( BASE_URL: string, host: string, accessTokens: string | undefined, limit: number ) { async function getFeaturedUser( BASE_URL: string, host: string, accessTokens: string | undefined, limit: number ) {
const accessTokenArr = accessTokens?.split(" ") ?? [null]; const accessTokenArr = accessTokens?.split(' ') ?? [null];
const accessToken = accessTokenArr[accessTokenArr.length - 1]; const accessToken = accessTokenArr[accessTokenArr.length - 1];
try { try {
const apicall = await fetch(`${BASE_URL}/api/users`, const apicall = await fetch(`${BASE_URL}/api/users`,
{ {
method: 'POST', method: 'POST',
headers: { headers: {
'Accept': 'application/json, text/plain, */*', 'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json' 'Content-Type': 'application/json',
}, },
body: JSON.stringify({i: accessToken, limit, origin: "local", sort: "+follower", state: "alive"}) body: JSON.stringify({ i: accessToken, limit, origin: 'local', sort: '+follower', state: 'alive' }),
}); });
const api = await apicall.json(); const api = await apicall.json();
const data: MisskeyEntity.UserDetail[] = api; const data: MisskeyEntity.UserDetail[] = api;
return data.map((u) => { return data.map((u) => {
return { return {
source: "past_interactions", source: 'past_interactions',
account: Converter.userDetail(u, host), account: Converter.userDetail(u, host),
}; };
}); });
} catch (e: any) { } catch (e: any) {
console.log(e); console.log(e);
console.log(e.response.data); console.log(e.response.data);
return []; return [];
} }
} }
export class apiSearchMastodon { export class ApiSearchMastodon {
private request: FastifyRequest; private request: FastifyRequest;
private client: MegalodonInterface; private client: MegalodonInterface;
private BASE_URL: string; private BASE_URL: string;
constructor(request: FastifyRequest, client: MegalodonInterface, BASE_URL: string) { constructor(request: FastifyRequest, client: MegalodonInterface, BASE_URL: string) {
this.request = request; this.request = request;
this.client = client; this.client = client;
this.BASE_URL = BASE_URL; this.BASE_URL = BASE_URL;
} }
public async SearchV1() { public async SearchV1() {
try { try {
const query: any = convertTimelinesArgsId(limitToInt(this.request.query as any)); const query: any = convertTimelinesArgsId(limitToInt(this.request.query as any));
const type = query.type || ""; const type = query.type || '';
const data = await this.client.search(query.q, { type: type, ...query }); const data = await this.client.search(query.q, { type: type, ...query });
return data.data; return data.data;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async SearchV2() { public async SearchV2() {
try { try {
const query: any = convertTimelinesArgsId(limitToInt(this.request.query as any)); const query: any = convertTimelinesArgsId(limitToInt(this.request.query as any));
const type = query.type; const type = query.type;
const acct = !type || type === "accounts" ? await this.client.search(query.q, { type: "accounts", ...query }) : null; const acct = !type || type === 'accounts' ? await this.client.search(query.q, { type: 'accounts', ...query }) : null;
const stat = !type || type === "statuses" ? await this.client.search(query.q, { type: "statuses", ...query }) : null; const stat = !type || type === 'statuses' ? await this.client.search(query.q, { type: 'statuses', ...query }) : null;
const tags = !type || type === "hashtags" ? await this.client.search(query.q, { type: "hashtags", ...query }) : null; const tags = !type || type === 'hashtags' ? await this.client.search(query.q, { type: 'hashtags', ...query }) : null;
const data = { const data = {
accounts: acct?.data.accounts.map((account) => convertAccount(account)) ?? [], accounts: acct?.data.accounts.map((account) => convertAccount(account)) ?? [],
statuses: stat?.data.statuses.map((status) => convertStatus(status)) ?? [], statuses: stat?.data.statuses.map((status) => convertStatus(status)) ?? [],
hashtags: tags?.data.hashtags ?? [] hashtags: tags?.data.hashtags ?? [],
}; };
return data; return data;
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async getStatusTrends() { public async getStatusTrends() {
try { try {
const data = await getHighlight( const data = await getHighlight(
this.BASE_URL, this.BASE_URL,
this.request.hostname, this.request.hostname,
@ -113,14 +112,14 @@ export class apiSearchMastodon {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
public async getSuggestions() { public async getSuggestions() {
try { try {
const data = await getFeaturedUser( const data = await getFeaturedUser(
this.BASE_URL, this.BASE_URL,
this.request.hostname, this.request.hostname,
this.request.headers.authorization, this.request.headers.authorization,
(this.request.query as any).limit || 20, (this.request.query as any).limit || 20,
); );
return data.map((suggestion) => { suggestion.account = convertAccount(suggestion.account); return suggestion; }); return data.map((suggestion) => { suggestion.account = convertAccount(suggestion.account); return suggestion; });
@ -128,5 +127,5 @@ export class apiSearchMastodon {
console.error(e); console.error(e);
return e.response.data; return e.response.data;
} }
} }
} }

View file

@ -1,407 +1,400 @@
import { convertId, IdConvertType as IdType, convertAccount, convertAttachment, convertPoll, convertStatus } from '../converters.js';
import querystring from 'querystring'; import querystring from 'querystring';
import type { Entity, MegalodonInterface } from 'megalodon'; import { emojiRegexAtStartToEnd } from '@/misc/emoji-regex.js';
import type { FastifyInstance } from 'fastify'; import { convertId, IdConvertType as IdType, convertAccount, convertAttachment, convertPoll, convertStatus } from '../converters.js';
import { getClient } from '../MastodonApiServerService.js'; import { getClient } from '../MastodonApiServerService.js';
import { convertTimelinesArgsId, limitToInt } from './timeline.js'; import { convertTimelinesArgsId, limitToInt } from './timeline.js';
import { emojiRegexAtStartToEnd } from "@/misc/emoji-regex.js"; import type { Entity } from 'megalodon';
import { MetaService } from '@/core/MetaService.js'; import type { FastifyInstance } from 'fastify';
function normalizeQuery(data: any) { function normalizeQuery(data: any) {
const str = querystring.stringify(data); const str = querystring.stringify(data);
return querystring.parse(str); return querystring.parse(str);
} }
export class apiStatusMastodon { export class ApiStatusMastodon {
private fastify: FastifyInstance; private fastify: FastifyInstance;
private metaService: MetaService;
constructor(fastify: FastifyInstance) { constructor(fastify: FastifyInstance) {
this.fastify = fastify; this.fastify = fastify;
} }
public async getStatus() { public async getStatus() {
this.fastify.get<{ Params: { id: string } }>("/v1/statuses/:id", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/statuses/:id', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const data = await client.getStatus(convertId(_request.params.id, IdType.SharkeyId)); const data = await client.getStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data)); reply.send(convertStatus(data.data));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
reply.code(_request.is404 ? 404 : 401).send(e.response.data); reply.code(_request.is404 ? 404 : 401).send(e.response.data);
} }
}); });
} }
public async getContext() { public async getContext() {
this.fastify.get<{ Params: { id: string } }>("/v1/statuses/:id/context", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/statuses/:id/context', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const query: any = _request.query; const query: any = _request.query;
try { try {
const data = await client.getStatusContext( const data = await client.getStatusContext(
convertId(_request.params.id, IdType.SharkeyId),
convertTimelinesArgsId(limitToInt(query))
);
data.data.ancestors = data.data.ancestors.map((status: Entity.Status) => convertStatus(status));
data.data.descendants = data.data.descendants.map((status: Entity.Status) => convertStatus(status));
reply.send(data.data);
} catch (e: any) {
console.error(e);
reply.code(_request.is404 ? 404 : 401).send(e.response.data);
}
});
}
public async getHistory() {
this.fastify.get<{ Params: { id: string } }>("/v1/statuses/:id/history", async (_request, reply) => {
try {
reply.code(401).send({ message: 'Not Implemented' });
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async getReblogged() {
this.fastify.get<{ Params: { id: string } }>("/v1/statuses/:id/reblogged_by", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.getStatusRebloggedBy(convertId(_request.params.id, IdType.SharkeyId));
reply.send(data.data.map((account: Entity.Account) => convertAccount(account)));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async getFavourites() {
this.fastify.get<{ Params: { id: string } }>("/v1/statuses/:id/favourited_by", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.getStatusFavouritedBy(convertId(_request.params.id, IdType.SharkeyId));
reply.send(data.data.map((account: Entity.Account) => convertAccount(account)));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async getMedia() {
this.fastify.get<{ Params: { id: string } }>("/v1/media/:id", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.getMedia(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertAttachment(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async getPoll() {
this.fastify.get<{ Params: { id: string } }>("/v1/polls/:id", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.getPoll(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertPoll(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async votePoll() {
this.fastify.post<{ Params: { id: string } }>("/v1/polls/:id/votes", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
const body: any = _request.body;
try {
const data = await client.votePoll(convertId(_request.params.id, IdType.SharkeyId), body.choices);
reply.send(convertPoll(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async postStatus() {
this.fastify.post("/v1/statuses", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
let body: any = _request.body;
try {
if (body.in_reply_to_id)
body.in_reply_to_id = convertId(body.in_reply_to_id, IdType.SharkeyId);
if (body.quote_id)
body.quote_id = convertId(body.quote_id, IdType.SharkeyId);
if (
(!body.poll && body["poll[options][]"]) ||
(!body.media_ids && body["media_ids[]"])
) {
body = normalizeQuery(body);
}
const text = body.status;
const removed = text.replace(/@\S+/g, "").replace(/\s|/g, "");
const isDefaultEmoji = emojiRegexAtStartToEnd.test(removed);
const isCustomEmoji = /^:[a-zA-Z0-9@_]+:$/.test(removed);
if ((body.in_reply_to_id && isDefaultEmoji) || isCustomEmoji) {
const a = await client.createEmojiReaction(
body.in_reply_to_id,
removed,
);
reply.send(a.data);
}
if (body.in_reply_to_id && removed === "/unreact") {
try {
const id = body.in_reply_to_id;
const post = await client.getStatus(id);
const react = post.data.emoji_reactions.filter((e: any) => e.me)[0].name;
const data = await client.deleteEmojiReaction(id, react);
reply.send(data.data);
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
}
if (!body.media_ids) body.media_ids = undefined;
if (body.media_ids && !body.media_ids.length) body.media_ids = undefined;
if (body.media_ids) {
body.media_ids = (body.media_ids as string[]).map((p) =>convertId(p, IdType.SharkeyId));
}
const { sensitive } = body;
body.sensitive = typeof sensitive === "string" ? sensitive === "true" : sensitive;
if (body.poll) {
if (
body.poll.expires_in != null &&
typeof body.poll.expires_in === "string"
)
body.poll.expires_in = parseInt(body.poll.expires_in);
if (
body.poll.multiple != null &&
typeof body.poll.multiple === "string"
)
body.poll.multiple = body.poll.multiple == "true";
if (
body.poll.hide_totals != null &&
typeof body.poll.hide_totals === "string"
)
body.poll.hide_totals = body.poll.hide_totals == "true";
}
const data = await client.postStatus(text, body);
reply.send(convertStatus(data.data as Entity.Status));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async addFavourite() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/favourite", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = (await client.createEmojiReaction(
convertId(_request.params.id, IdType.SharkeyId), convertId(_request.params.id, IdType.SharkeyId),
'⭐' convertTimelinesArgsId(limitToInt(query)),
)) as any;
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async rmFavourite() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/unfavourite", async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.deleteEmojiReaction(
convertId(_request.params.id, IdType.SharkeyId),
'⭐'
); );
reply.send(convertStatus(data.data)); data.data.ancestors = data.data.ancestors.map((status: Entity.Status) => convertStatus(status));
} catch (e: any) { data.data.descendants = data.data.descendants.map((status: Entity.Status) => convertStatus(status));
console.error(e); reply.send(data.data);
reply.code(401).send(e.response.data); } catch (e: any) {
} console.error(e);
}); reply.code(_request.is404 ? 404 : 401).send(e.response.data);
} }
});
}
public async reblogStatus() { public async getHistory() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/reblog", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/statuses/:id/history', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; try {
const accessTokens = _request.headers.authorization; reply.code(401).send({ message: 'Not Implemented' });
const client = getClient(BASE_URL, accessTokens); } catch (e: any) {
try { console.error(e);
const data = await client.reblogStatus(convertId(_request.params.id, IdType.SharkeyId)); reply.code(401).send(e.response.data);
reply.send(convertStatus(data.data)); }
} catch (e: any) { });
console.error(e); }
reply.code(401).send(e.response.data);
}
});
}
public async unreblogStatus() { public async getReblogged() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/unreblog", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/statuses/:id/reblogged_by', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const data = await client.unreblogStatus(convertId(_request.params.id, IdType.SharkeyId)); const data = await client.getStatusRebloggedBy(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data)); reply.send(data.data.map((account: Entity.Account) => convertAccount(account)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async bookmarkStatus() { public async getFavourites() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/bookmark", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/statuses/:id/favourited_by', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const data = await client.bookmarkStatus(convertId(_request.params.id, IdType.SharkeyId)); const data = await client.getStatusFavouritedBy(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data)); reply.send(data.data.map((account: Entity.Account) => convertAccount(account)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async unbookmarkStatus() { public async getMedia() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/unbookmark", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/media/:id', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const data = await client.unbookmarkStatus(convertId(_request.params.id, IdType.SharkeyId)); const data = await client.getMedia(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data)); reply.send(convertAttachment(data.data));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async pinStatus() { public async getPoll() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/pin", async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/polls/:id', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const data = await client.pinStatus(convertId(_request.params.id, IdType.SharkeyId)); const data = await client.getPoll(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data)); reply.send(convertPoll(data.data));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async unpinStatus() { public async votePoll() {
this.fastify.post<{ Params: { id: string } }>("/v1/statuses/:id/unpin", async (_request, reply) => { this.fastify.post<{ Params: { id: string } }>('/v1/polls/:id/votes', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { const body: any = _request.body;
const data = await client.unpinStatus(convertId(_request.params.id, IdType.SharkeyId)); try {
reply.send(convertStatus(data.data)); const data = await client.votePoll(convertId(_request.params.id, IdType.SharkeyId), body.choices);
} catch (e: any) { reply.send(convertPoll(data.data));
console.error(e); } catch (e: any) {
reply.code(401).send(e.response.data); console.error(e);
} reply.code(401).send(e.response.data);
}); }
} });
}
public async reactStatus() { public async postStatus() {
this.fastify.post<{ Params: { id: string, name: string } }>("/v1/statuses/:id/react/:name", async (_request, reply) => { this.fastify.post('/v1/statuses', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { let body: any = _request.body;
const data = await client.createEmojiReaction(convertId(_request.params.id, IdType.SharkeyId), _request.params.name); try {
reply.send(convertStatus(data.data)); if (body.in_reply_to_id) body.in_reply_to_id = convertId(body.in_reply_to_id, IdType.SharkeyId);
} catch (e: any) { if (body.quote_id) body.quote_id = convertId(body.quote_id, IdType.SharkeyId);
console.error(e); if (
reply.code(401).send(e.response.data); (!body.poll && body['poll[options][]']) ||
} (!body.media_ids && body['media_ids[]'])
}); ) {
} body = normalizeQuery(body);
}
const text = body.status;
const removed = text.replace(/@\S+/g, '').replace(/\s|/g, '');
const isDefaultEmoji = emojiRegexAtStartToEnd.test(removed);
const isCustomEmoji = /^:[a-zA-Z0-9@_]+:$/.test(removed);
if ((body.in_reply_to_id && isDefaultEmoji) || isCustomEmoji) {
const a = await client.createEmojiReaction(
body.in_reply_to_id,
removed,
);
reply.send(a.data);
}
if (body.in_reply_to_id && removed === '/unreact') {
try {
const id = body.in_reply_to_id;
const post = await client.getStatus(id);
const react = post.data.emoji_reactions.filter((e: any) => e.me)[0].name;
const data = await client.deleteEmojiReaction(id, react);
reply.send(data.data);
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
}
if (!body.media_ids) body.media_ids = undefined;
if (body.media_ids && !body.media_ids.length) body.media_ids = undefined;
if (body.media_ids) {
body.media_ids = (body.media_ids as string[]).map((p) => convertId(p, IdType.SharkeyId));
}
public async unreactStatus() { const { sensitive } = body;
this.fastify.post<{ Params: { id: string, name: string } }>("/v1/statuses/:id/unreact/:name", async (_request, reply) => { body.sensitive = typeof sensitive === 'string' ? sensitive === 'true' : sensitive;
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.deleteEmojiReaction(convertId(_request.params.id, IdType.SharkeyId), _request.params.name);
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async updateMedia() { if (body.poll) {
this.fastify.put<{ Params: { id: string } }>("/v1/media/:id", async (_request, reply) => { if (
const BASE_URL = `${_request.protocol}://${_request.hostname}`; body.poll.expires_in != null &&
const accessTokens = _request.headers.authorization; typeof body.poll.expires_in === 'string'
const client = getClient(BASE_URL, accessTokens); ) body.poll.expires_in = parseInt(body.poll.expires_in);
try { if (
const data = await client.updateMedia(convertId(_request.params.id, IdType.SharkeyId), _request.body as any); body.poll.multiple != null &&
reply.send(convertAttachment(data.data)); typeof body.poll.multiple === 'string'
} catch (e: any) { ) body.poll.multiple = body.poll.multiple === 'true';
console.error(e); if (
reply.code(401).send(e.response.data); body.poll.hide_totals != null &&
} typeof body.poll.hide_totals === 'string'
}); ) body.poll.hide_totals = body.poll.hide_totals === 'true';
} }
public async deleteStatus() { const data = await client.postStatus(text, body);
this.fastify.delete<{ Params: { id: string } }>("/v1/statuses/:id", async (_request, reply) => { reply.send(convertStatus(data.data as Entity.Status));
const BASE_URL = `${_request.protocol}://${_request.hostname}`; } catch (e: any) {
const accessTokens = _request.headers.authorization; console.error(e);
const client = getClient(BASE_URL, accessTokens); reply.code(401).send(e.response.data);
try { }
const data = await client.deleteStatus(convertId(_request.params.id, IdType.SharkeyId)); });
reply.send(data.data); }
} catch (e: any) {
console.error(e); public async addFavourite() {
reply.code(401).send(e.response.data); this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/favourite', async (_request, reply) => {
} const BASE_URL = `${_request.protocol}://${_request.hostname}`;
}); const accessTokens = _request.headers.authorization;
} const client = getClient(BASE_URL, accessTokens);
} try {
const data = (await client.createEmojiReaction(
convertId(_request.params.id, IdType.SharkeyId),
'⭐',
)) as any;
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async rmFavourite() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/unfavourite', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.deleteEmojiReaction(
convertId(_request.params.id, IdType.SharkeyId),
'⭐',
);
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async reblogStatus() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/reblog', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.reblogStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async unreblogStatus() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/unreblog', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.unreblogStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async bookmarkStatus() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/bookmark', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.bookmarkStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async unbookmarkStatus() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/unbookmark', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.unbookmarkStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async pinStatus() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/pin', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.pinStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async unpinStatus() {
this.fastify.post<{ Params: { id: string } }>('/v1/statuses/:id/unpin', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.unpinStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async reactStatus() {
this.fastify.post<{ Params: { id: string, name: string } }>('/v1/statuses/:id/react/:name', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.createEmojiReaction(convertId(_request.params.id, IdType.SharkeyId), _request.params.name);
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async unreactStatus() {
this.fastify.post<{ Params: { id: string, name: string } }>('/v1/statuses/:id/unreact/:name', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.deleteEmojiReaction(convertId(_request.params.id, IdType.SharkeyId), _request.params.name);
reply.send(convertStatus(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async updateMedia() {
this.fastify.put<{ Params: { id: string } }>('/v1/media/:id', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.updateMedia(convertId(_request.params.id, IdType.SharkeyId), _request.body as any);
reply.send(convertAttachment(data.data));
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
public async deleteStatus() {
this.fastify.delete<{ Params: { id: string } }>('/v1/statuses/:id', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens);
try {
const data = await client.deleteStatus(convertId(_request.params.id, IdType.SharkeyId));
reply.send(data.data);
} catch (e: any) {
console.error(e);
reply.code(401).send(e.response.data);
}
});
}
}

View file

@ -1,15 +1,13 @@
import { convertId, IdConvertType as IdType, convertAccount, convertConversation, convertList, convertStatus } from '../converters.js';
import { ParsedUrlQuery } from 'querystring'; import { ParsedUrlQuery } from 'querystring';
import type { Entity, MegalodonInterface } from 'megalodon'; import { convertId, IdConvertType as IdType, convertAccount, convertConversation, convertList, convertStatus } from '../converters.js';
import type { FastifyInstance } from 'fastify';
import { getClient } from '../MastodonApiServerService.js'; import { getClient } from '../MastodonApiServerService.js';
import type { Entity } from 'megalodon';
import type { FastifyInstance } from 'fastify';
export function limitToInt(q: ParsedUrlQuery) { export function limitToInt(q: ParsedUrlQuery) {
let object: any = q; const object: any = q;
if (q.limit) if (q.limit) if (typeof q.limit === 'string') object.limit = parseInt(q.limit, 10);
if (typeof q.limit === 'string') object.limit = parseInt(q.limit, 10); if (q.offset) if (typeof q.offset === 'string') object.offset = parseInt(q.offset, 10);
if (q.offset)
if (typeof q.offset === 'string') object.offset = parseInt(q.offset, 10);
return object; return object;
} }
@ -22,165 +20,133 @@ export function argsToBools(q: ParsedUrlQuery) {
// - https://docs.joinmastodon.org/methods/accounts/#statuses // - https://docs.joinmastodon.org/methods/accounts/#statuses
// - https://docs.joinmastodon.org/methods/timelines/#public // - https://docs.joinmastodon.org/methods/timelines/#public
// - https://docs.joinmastodon.org/methods/timelines/#tag // - https://docs.joinmastodon.org/methods/timelines/#tag
let object: any = q; const object: any = q;
if (q.only_media) if (q.only_media) if (typeof q.only_media === 'string') object.only_media = toBoolean(q.only_media);
if (typeof q.only_media === 'string') if (q.exclude_replies) if (typeof q.exclude_replies === 'string') object.exclude_replies = toBoolean(q.exclude_replies);
object.only_media = toBoolean(q.only_media); if (q.exclude_reblogs) if (typeof q.exclude_reblogs === 'string') object.exclude_reblogs = toBoolean(q.exclude_reblogs);
if (q.exclude_replies) if (q.pinned) if (typeof q.pinned === 'string') object.pinned = toBoolean(q.pinned);
if (typeof q.exclude_replies === 'string') if (q.local) if (typeof q.local === 'string') object.local = toBoolean(q.local);
object.exclude_replies = toBoolean(q.exclude_replies);
if (q.exclude_reblogs)
if (typeof q.exclude_reblogs === 'string')
object.exclude_reblogs = toBoolean(q.exclude_reblogs);
if (q.pinned)
if (typeof q.pinned === 'string') object.pinned = toBoolean(q.pinned);
if (q.local)
if (typeof q.local === 'string') object.local = toBoolean(q.local);
return q; return q;
} }
export function convertTimelinesArgsId(q: ParsedUrlQuery) { export function convertTimelinesArgsId(q: ParsedUrlQuery) {
if (typeof q.min_id === 'string') if (typeof q.min_id === 'string') q.min_id = convertId(q.min_id, IdType.SharkeyId);
q.min_id = convertId(q.min_id, IdType.SharkeyId); if (typeof q.max_id === 'string') q.max_id = convertId(q.max_id, IdType.SharkeyId);
if (typeof q.max_id === 'string') if (typeof q.since_id === 'string') q.since_id = convertId(q.since_id, IdType.SharkeyId);
q.max_id = convertId(q.max_id, IdType.SharkeyId);
if (typeof q.since_id === 'string')
q.since_id = convertId(q.since_id, IdType.SharkeyId);
return q; return q;
} }
function escapeHTML(str: string) { export class ApiTimelineMastodon {
if (!str) {
return '';
}
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/'/g, '&quot;')
.replace(/'/g, '&#039;');
}
function nl2br(str: string) {
if (!str) {
return '';
}
str = str.replace(/\r\n/g, '<br />');
str = str.replace(/(\n|\r)/g, '<br />');
return str;
}
export class apiTimelineMastodon {
private fastify: FastifyInstance; private fastify: FastifyInstance;
constructor(fastify: FastifyInstance) { constructor(fastify: FastifyInstance) {
this.fastify = fastify; this.fastify = fastify;
} }
public async getTL() { public async getTL() {
this.fastify.get('/v1/timelines/public', async (_request, reply) => { this.fastify.get('/v1/timelines/public', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const query: any = _request.query; const query: any = _request.query;
const data = query.local === 'true' const data = query.local === 'true'
? await client.getLocalTimeline(convertTimelinesArgsId(argsToBools(limitToInt(query)))) ? await client.getLocalTimeline(convertTimelinesArgsId(argsToBools(limitToInt(query))))
: await client.getPublicTimeline(convertTimelinesArgsId(argsToBools(limitToInt(query)))); : await client.getPublicTimeline(convertTimelinesArgsId(argsToBools(limitToInt(query))));
reply.send(data.data.map((status: Entity.Status) => convertStatus(status))); reply.send(data.data.map((status: Entity.Status) => convertStatus(status)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async getHomeTl() { public async getHomeTl() {
this.fastify.get('/v1/timelines/home', async (_request, reply) => { this.fastify.get('/v1/timelines/home', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const query: any = _request.query; const query: any = _request.query;
const data = await client.getHomeTimeline(convertTimelinesArgsId(limitToInt(query))); const data = await client.getHomeTimeline(convertTimelinesArgsId(limitToInt(query)));
reply.send(data.data.map((status: Entity.Status) => convertStatus(status))); reply.send(data.data.map((status: Entity.Status) => convertStatus(status)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async getTagTl() { public async getTagTl() {
this.fastify.get<{ Params: { hashtag: string } }>('/v1/timelines/tag/:hashtag', async (_request, reply) => { this.fastify.get<{ Params: { hashtag: string } }>('/v1/timelines/tag/:hashtag', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const query: any = _request.query; const query: any = _request.query;
const params: any = _request.params; const params: any = _request.params;
const data = await client.getTagTimeline(params.hashtag, convertTimelinesArgsId(limitToInt(query))); const data = await client.getTagTimeline(params.hashtag, convertTimelinesArgsId(limitToInt(query)));
reply.send(data.data.map((status: Entity.Status) => convertStatus(status))); reply.send(data.data.map((status: Entity.Status) => convertStatus(status)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async getListTL() { public async getListTL() {
this.fastify.get<{ Params: { id: string } }>('/v1/timelines/list/:id', async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/timelines/list/:id', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const query: any = _request.query; const query: any = _request.query;
const params: any = _request.params; const params: any = _request.params;
const data = await client.getListTimeline(convertId(params.id, IdType.SharkeyId), convertTimelinesArgsId(limitToInt(query))); const data = await client.getListTimeline(convertId(params.id, IdType.SharkeyId), convertTimelinesArgsId(limitToInt(query)));
reply.send(data.data.map((status: Entity.Status) => convertStatus(status))); reply.send(data.data.map((status: Entity.Status) => convertStatus(status)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async getConversations() { public async getConversations() {
this.fastify.get('/v1/conversations', async (_request, reply) => { this.fastify.get('/v1/conversations', async (_request, reply) => {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
try { try {
const query: any = _request.query; const query: any = _request.query;
const data = await client.getConversationTimeline(convertTimelinesArgsId(limitToInt(query))); const data = await client.getConversationTimeline(convertTimelinesArgsId(limitToInt(query)));
reply.send(data.data.map((conversation: Entity.Conversation) => convertConversation(conversation))); reply.send(data.data.map((conversation: Entity.Conversation) => convertConversation(conversation)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async getList(){ public async getList() {
this.fastify.get<{ Params: { id: string } }>('/v1/lists/:id', async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/lists/:id', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const params: any = _request.params; const params: any = _request.params;
const data = await client.getList(convertId(params.id, IdType.SharkeyId)); const data = await client.getList(convertId(params.id, IdType.SharkeyId));
reply.send(convertList(data.data)); reply.send(convertList(data.data));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async getLists() { public async getLists() {
@ -197,121 +163,120 @@ export class apiTimelineMastodon {
return e.response.data; return e.response.data;
} }
}); });
} }
public async getListAccounts(){ public async getListAccounts() {
this.fastify.get<{ Params: { id: string } }>('/v1/lists/:id/accounts', async (_request, reply) => { this.fastify.get<{ Params: { id: string } }>('/v1/lists/:id/accounts', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const params: any = _request.params; const params: any = _request.params;
const query: any = _request.query; const query: any = _request.query;
const data = await client.getAccountsInList( const data = await client.getAccountsInList(
convertId(params.id, IdType.SharkeyId), convertId(params.id, IdType.SharkeyId),
convertTimelinesArgsId(query) convertTimelinesArgsId(query),
); );
reply.send(data.data.map((account: Entity.Account) => convertAccount(account))); reply.send(data.data.map((account: Entity.Account) => convertAccount(account)));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async addListAccount() { public async addListAccount() {
this.fastify.post<{ Params: { id: string } }>('/v1/lists/:id/accounts', async (_request, reply) => { this.fastify.post<{ Params: { id: string } }>('/v1/lists/:id/accounts', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const params: any = _request.params; const params: any = _request.params;
const query: any = _request.query; const query: any = _request.query;
const data = await client.addAccountsToList( const data = await client.addAccountsToList(
convertId(params.id, IdType.SharkeyId), convertId(params.id, IdType.SharkeyId),
(query.accounts_id as string[]).map((id) => convertId(id, IdType.SharkeyId)) (query.accounts_id as string[]).map((id) => convertId(id, IdType.SharkeyId)),
); );
reply.send(data.data); reply.send(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async rmListAccount() { public async rmListAccount() {
this.fastify.delete<{ Params: { id: string } }>('/v1/lists/:id/accounts', async (_request, reply) => { this.fastify.delete<{ Params: { id: string } }>('/v1/lists/:id/accounts', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const params: any = _request.params; const params: any = _request.params;
const query: any = _request.query; const query: any = _request.query;
const data = await client.deleteAccountsFromList( const data = await client.deleteAccountsFromList(
convertId(params.id, IdType.SharkeyId), convertId(params.id, IdType.SharkeyId),
(query.accounts_id as string[]).map((id) => convertId(id, IdType.SharkeyId)) (query.accounts_id as string[]).map((id) => convertId(id, IdType.SharkeyId)),
); );
reply.send(data.data); reply.send(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async createList() { public async createList() {
this.fastify.post('/v1/lists', async (_request, reply) => { this.fastify.post('/v1/lists', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const body: any = _request.body; const body: any = _request.body;
const data = await client.createList(body.title); const data = await client.createList(body.title);
reply.send(convertList(data.data)); reply.send(convertList(data.data));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async updateList() { public async updateList() {
this.fastify.put<{ Params: { id: string } }>('/v1/lists/:id', async (_request, reply) => { this.fastify.put<{ Params: { id: string } }>('/v1/lists/:id', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const body: any = _request.body; const body: any = _request.body;
const params: any = _request.params; const params: any = _request.params;
const data = await client.updateList(convertId(params.id, IdType.SharkeyId), body.title); const data = await client.updateList(convertId(params.id, IdType.SharkeyId), body.title);
reply.send(convertList(data.data)); reply.send(convertList(data.data));
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
public async deleteList() { public async deleteList() {
this.fastify.delete<{ Params: { id: string } }>('/v1/lists/:id', async (_request, reply) => { this.fastify.delete<{ Params: { id: string } }>('/v1/lists/:id', async (_request, reply) => {
try { try {
const BASE_URL = `${_request.protocol}://${_request.hostname}`; const BASE_URL = `${_request.protocol}://${_request.hostname}`;
const accessTokens = _request.headers.authorization; const accessTokens = _request.headers.authorization;
const client = getClient(BASE_URL, accessTokens); const client = getClient(BASE_URL, accessTokens);
const params: any = _request.params; const params: any = _request.params;
const data = await client.deleteList(convertId(params.id, IdType.SharkeyId)); const data = await client.deleteList(convertId(params.id, IdType.SharkeyId));
reply.send(data.data); reply.send(data.data);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error(e);
console.error(e.response.data); console.error(e.response.data);
reply.code(401).send(e.response.data); reply.code(401).send(e.response.data);
} }
}); });
} }
}
}