Skip to content

Commit

Permalink
refactor: adapt biome code style, add git hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
thilobillerbeck committed Feb 5, 2025
1 parent 45a86b2 commit 91cfd81
Show file tree
Hide file tree
Showing 15 changed files with 185 additions and 135 deletions.
12 changes: 12 additions & 0 deletions devenv.nix
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,16 @@
};

pre-commit.hooks.commitizen.enable = true;
git-hooks.hooks.lint = {
enable = true;
name = "Lint code";
entry = "pnpm run lint";
pass_filenames = false;
};
git-hooks.hooks.format-check = {
enable = true;
name = "Check formatting";
entry = "pnpm run format:check";
pass_filenames = false;
};
}
2 changes: 1 addition & 1 deletion drizzle.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export default defineConfig({
out: "./drizzle",
schema: "./drizzle/schema.ts",
dbCredentials: {
url: process.env.POSTGRES_URL!,
url: process.env.POSTGRES_URL || "",
},
// Print all statements
verbose: true,
Expand Down
13 changes: 6 additions & 7 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import fastifyFormbody from "@fastify/formbody";
import fastifyJwt from "@fastify/jwt";
import { routesRoot } from "./routes/root";
import { routesUser } from "./routes/user";
import { join } from "path";
import { join } from "node:path";
import * as Sentry from "@sentry/node";
import { nodeProfilingIntegration } from "@sentry/profiling-node";
import { readFileSync } from "fs";
import { join as pathJoin } from "path";
import { existsSync, readFileSync } from "node:fs";
import { printInfo } from "./lib/utils";
import { client, db } from "./lib/db";
import { migrationHelper } from "./lib/migration";
Expand Down Expand Up @@ -47,8 +46,8 @@ migrationHelper()

let version = "development";

const gitRevPath = pathJoin(__dirname, ".git-rev");
if (require("fs").existsSync(gitRevPath)) {
const gitRevPath = join(__dirname, ".git-rev");
if (existsSync(gitRevPath)) {
version = readFileSync(gitRevPath, "utf-8").trim();
}

Expand Down Expand Up @@ -88,8 +87,8 @@ migrationHelper()
app.register(routesUser);

app.listen(
{ host: ADDRESS, port: parseInt(PORT, 10) },
function (err, address) {
{ host: ADDRESS, port: Number.parseInt(PORT, 10) },
(err, address) => {
if (err) {
app.log.error(err);
}
Expand Down
47 changes: 26 additions & 21 deletions lib/bluesky.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,36 @@ import {
AtpAgent,
AppBskyFeedPost,
RichText,
BlobRef,
AtpSessionData,
AtpSessionEvent,
type BlobRef,
type AtpSessionData,
type AtpSessionEvent,
} from "@atproto/api";
import { Entity } from "megalodon";
import type { Entity } from "megalodon";
import {
fetchImageToBytes,
logSchedulerEvent,
mastodonHtmlToText,
splitTextBluesky,
} from "./utils";
import sharp from "sharp";
import { Attachment } from "megalodon/lib/src/entities/attachment";
import type { Attachment } from "megalodon/lib/src/entities/attachment";
import {
clearBlueskyCreds,
clearBluskySession,
db,
persistBlueskySession,
} from "./db";
import { ResponseType, XRPCError } from "@atproto/xrpc";
import { ResponseType, type XRPCError } from "@atproto/xrpc";
import type { InferSelectModel } from "drizzle-orm";
import type { mastodonInstance, user as User } from "../drizzle/schema";

export async function intiBlueskyAgent(
url: string,
handle: string,
password: string,
user: any,
user: InferSelectModel<typeof User> & {
mastodonInstance: InferSelectModel<typeof mastodonInstance>;
},
): Promise<AtpAgent | undefined> {
let session: AtpSessionData | undefined = undefined;
session = user.blueskySession as unknown as AtpSessionData;
Expand Down Expand Up @@ -72,14 +76,14 @@ export async function intiBlueskyAgent(
"resuming session",
);
return agent;
} else {
logSchedulerEvent(
user.name,
user.mastodonInstance.url,
"AGENT",
"could not resume session",
);
}

logSchedulerEvent(
user.name,
user.mastodonInstance.url,
"AGENT",
"could not resume session",
);
} else {
logSchedulerEvent(
user.name,
Expand All @@ -93,7 +97,7 @@ export async function intiBlueskyAgent(
await agent.login({ identifier: handle, password: password });
return agent;
} catch (err) {
if ((err as XRPCError).status == ResponseType.AuthRequired) {
if ((err as XRPCError).status === ResponseType.AuthRequired) {
// invalidate creds to prevent further login attempts resulting in rate limiting
logSchedulerEvent(
user.name,
Expand All @@ -102,7 +106,7 @@ export async function intiBlueskyAgent(
"invalid creds",
);
clearBlueskyCreds(user);
} else if ((err as XRPCError).status == ResponseType.RateLimitExceeded) {
} else if ((err as XRPCError).status === ResponseType.RateLimitExceeded) {
logSchedulerEvent(
user.name,
user.mastodonInstance.url,
Expand All @@ -126,13 +130,13 @@ export async function generateBlueskyPostsFromMastodon(
status: Entity.Status,
client: AtpAgent,
): Promise<Array<AppBskyFeedPost.Record>> {
let posts: Array<AppBskyFeedPost.Record> = [];
const posts: Array<AppBskyFeedPost.Record> = [];
const spoiler = status.sensitive ? `CW: ${status.spoiler_text}\n\n` : "";
const conv = mastodonHtmlToText(status.content);
const split = splitTextBluesky(conv, spoiler);

for (const [idx, text] of split.entries()) {
let post = await generateBlueskyPostFromMastodon(
const post = await generateBlueskyPostFromMastodon(
text,
client,
idx === 0 ? status.media_attachments : undefined,
Expand Down Expand Up @@ -192,8 +196,10 @@ export async function generateBlueskyPostFromMastodon(
arr = new Uint8Array(result.buffer);
}

if (!mimeType) continue;

const res = await client.uploadBlob(arr, {
encoding: mimeType!,
encoding: mimeType,
});

let width = 1200;
Expand Down Expand Up @@ -232,9 +238,8 @@ export async function generateBlueskyPostFromMastodon(
const res = AppBskyFeedPost.validateRecord(post);
if (res.success) {
return post;
} else {
console.log(res);
}
console.log(res);
}
return undefined;
}
Expand Down
75 changes: 50 additions & 25 deletions lib/db.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { ReplyRef } from "@atproto/api/dist/client/types/app/bsky/feed/post";
import type { ReplyRef } from "@atproto/api/dist/client/types/app/bsky/feed/post";
import { logSchedulerEvent } from "./utils";
import { drizzle } from "drizzle-orm/node-postgres";
import { Client } from "pg";
import * as schema from "./../drizzle/schema";
import * as relations from "./../drizzle/relations";
import { count, eq } from "drizzle-orm";
import { AtpSessionData } from "@atproto/api";
import {
count,
eq,
type InferInsertModel,
type InferSelectModel,
} from "drizzle-orm";
import type { AtpSessionData } from "@atproto/api";
import type { OAuth } from "megalodon";
import type Response from "megalodon/lib/src/response";
import type { Account } from "megalodon/lib/src/entities/account";

export const client = new Client({
connectionString: process.env.POSTGRES_URL,
Expand Down Expand Up @@ -88,7 +96,9 @@ export async function findParentToot(
}

export async function persistBlueskySession(
user: any,
user: InferSelectModel<typeof schema.user> & {
mastodonInstance: InferSelectModel<typeof schema.mastodonInstance>;
},
evt: string,
sess?: AtpSessionData,
) {
Expand Down Expand Up @@ -119,7 +129,11 @@ export async function persistBlueskySession(
});
}

export async function clearBluskySession(user: any) {
export async function clearBluskySession(
user: InferSelectModel<typeof schema.user> & {
mastodonInstance: InferSelectModel<typeof schema.mastodonInstance>;
},
) {
return await db
.update(schema.user)
.set({
Expand Down Expand Up @@ -147,7 +161,11 @@ export async function clearBluskySession(user: any) {
});
}

export async function clearBlueskyCreds(user: any) {
export async function clearBlueskyCreds(
user: InferSelectModel<typeof schema.user> & {
mastodonInstance: InferSelectModel<typeof schema.mastodonInstance>;
},
) {
return await db
.update(schema.user)
.set({
Expand Down Expand Up @@ -186,8 +204,8 @@ export async function findUsers() {
}

export async function findUserById(
userid: any,
withMastodonInstance: boolean = false,
userid: string,
withMastodonInstance = false,
) {
return await db.query.user.findFirst({
where: (user, { eq }) => eq(user.id, userid),
Expand All @@ -213,16 +231,16 @@ export async function getAllUserInformation(userId: string) {
});
}

export async function deleteUser(user: any) {
export async function deleteUser(userId: string, userName: string) {
return await db
.delete(schema.user)
.where(eq(schema.user.id, user.id))
.where(eq(schema.user.id, userId))
.then(() => {
logSchedulerEvent(user.name, "---", "CREDENTIAL_CHECK", "User deleted");
logSchedulerEvent(userName, "---", "CREDENTIAL_CHECK", "User deleted");
})
.catch((err) => {
logSchedulerEvent(
user.name,
userName,
"---",
"CREDENTIAL_CHECK",
"Could not delete user",
Expand All @@ -246,22 +264,25 @@ export async function getMastodonInstanceUsers() {
.groupBy(schema.mastodonInstance.id);
}

export async function deleteMastodonInstance(instance: any) {
export async function deleteMastodonInstance(
instanceId: string,
instanceUrl: string,
) {
return await db
.delete(schema.mastodonInstance)
.where(eq(schema.mastodonInstance.id, instance.id))
.where(eq(schema.mastodonInstance.id, instanceId))
.then(() => {
logSchedulerEvent(
"SYSTEM",
instance.url,
instanceUrl,
"INSTANCE_USERS",
"Instance deleted",
);
})
.catch((err) => {
logSchedulerEvent(
"SYSTEM",
instance.url,
instanceUrl,
"INSTANCE_USERS",
"Could not delete instance",
);
Expand All @@ -270,7 +291,7 @@ export async function deleteMastodonInstance(instance: any) {
}

export async function persistBlueskyCreds(
userId: any,
userId: string,
handle: string,
token: string,
pds: string,
Expand All @@ -288,10 +309,10 @@ export async function persistBlueskyCreds(
}

export async function updateRelaySettings(
userId: any,
relayCriteria: any,
userId: string,
relayCriteria: InferInsertModel<typeof schema.user>["relayCriteria"],
relayMarker: string,
relayVisibility: any,
relayVisibility: InferInsertModel<typeof schema.user>["relayVisibility"],
) {
return await db
.update(schema.user)
Expand All @@ -307,7 +328,7 @@ export async function updateRelaySettings(

export async function createMastodonInstance(
instanceDomain: string,
appData: any,
appData: OAuth.AppData,
) {
return await db
.insert(schema.mastodonInstance)
Expand All @@ -322,9 +343,9 @@ export async function createMastodonInstance(
}

export async function createUser(
instanceId: any,
verifiedCredentials: any,
token: any,
instanceId: string,
verifiedCredentials: Response<Account>,
token: OAuth.TokenData,
) {
return await db
.insert(schema.user)
Expand All @@ -339,7 +360,11 @@ export async function createUser(
.returning();
}

export async function updateUser(userId: any, token: any, name: string) {
export async function updateUser(
userId: string,
token: OAuth.TokenData,
name: string,
) {
return await db
.update(schema.user)
.set({
Expand Down
Loading

0 comments on commit 91cfd81

Please sign in to comment.