pixiv-bookmarks-to-pleroma/matrix.js

68 lines
2.2 KiB
JavaScript

import ky from 'https://esm.sh/ky';
import { credentials } from "./common.js";
var ke = ky.create({
hooks: {
beforeRequest: [request => console.log(`${request.method} ${request.url}`)],
afterResponse: [(_request, _options, response) => console.log(response.status)]
},
retry: {
limit: 100,
delay: attemptCount => (2 ** (attemptCount - 1)) * 1000
},
timeout: false
});
var matrix = {
ky: ke.extend({headers: {"Authorization": `Bearer ${credentials.matrix_token}`}}),
rooms: {
default: "!mxhaBcBiEmnGxrffll:matrix.org",
pixiv_sfw: "!zStOGJAGxEaQgwxGYI:matrix.org",
pixiv_nsfw: "!HtXDHeAhEKBFGfAJTi:matrix.org"
},
async sendMessage({room = this.rooms.default, type = "m.text", body, filename, info, url}) {
return await this.ky.put(`https://matrix-client.matrix.org/_matrix/client/v3/rooms/${encodeURIComponent(room)}/send/m.room.message/${Math.random().toString()}`, {
json: {msgtype: type, body, filename, info, url}
}).json();
},
async uploadFile(filename, data) {
var {content_uri} = await this.ky.post(`https://matrix-client.matrix.org/_matrix/media/v3/upload?filename=${encodeURIComponent(filename)}`, {body: data}).json();
return content_uri;
},
async sendImage({room = this.rooms.default, body, filename, data, info}) {
var content_uri = await this.uploadFile(filename, data);
return await this.sendMessage({room, type: "m.image", body: body || filename, filename, url: content_uri, info});
}
};
export async function postPixivIllustToMatrix(illust, images, msg) {
try {
var room = illust.xRestrict ? matrix.rooms.pixiv_nsfw : matrix.rooms.pixiv_sfw;
await matrix.sendMessage({room, body: msg || `https://www.pixiv.net/en/artworks/${illust.id}`});
for (var image of images) {
try {
await matrix.sendImage({
room,
filename: image.name,
data: image.data,
info: {
mimetype: image.data.type,
size: image.data.size,
w: image.width,
h: image.height
}
});
} catch (error) {
onError(error);
}
}
} catch (error) {
onError(error);
}
function onError(error) {
console.error(error.stack);
matrix.sendMessage({room: room || matrix.rooms.pixiv_sfw, body: error.stack}).catch(error => {
console.error(error.stack);
});
}
}