Skip to content

Commit

Permalink
add snowflake.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Eric committed May 25, 2023
1 parent 28117fd commit e615d04
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 243 deletions.
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@
"typescript": "^5.0.4"
},
"dependencies": {
"discord-api-types": "^0.37.42",
"discord.js": "^14.11.0",
"p-queue": "^6.6.2",
"throat": "^6.0.2",
"tslib": "^2.5.0",
Expand Down
19 changes: 8 additions & 11 deletions src/midjourney.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Snowflake, SnowflakeUtil } from "discord.js";
import {
DefaultMidjourneyConfig,
LoadingHandler,
Expand All @@ -7,7 +6,7 @@ import {
} from "./interfaces";
import { MidjourneyMessage } from "./midjourney.message";
import { CreateQueue } from "./queue";
import { random, sleep } from "./utls";
import { nextNonce, random, sleep } from "./utls";
import { WsMessage } from "./ws.message";
export class Midjourney extends MidjourneyMessage {
private ApiQueue = CreateQueue(1);
Expand Down Expand Up @@ -39,7 +38,8 @@ export class Midjourney extends MidjourneyMessage {
const speed = random(1000, 9999);
prompt = `${prompt} --seed ${speed}`;
}
const nonce = SnowflakeUtil.generate().toString();

const nonce = nextNonce();
this.log(`Imagine`, prompt, "nonce", nonce);
const httpStatus = await this.ImagineApi(prompt, nonce);
if (httpStatus !== 204) {
Expand Down Expand Up @@ -94,10 +94,7 @@ export class Midjourney extends MidjourneyMessage {
}
}

async ImagineApi(
prompt: string,
nonce: Snowflake = SnowflakeUtil.generate().toString()
) {
async ImagineApi(prompt: string, nonce: string = nextNonce()) {
const payload = {
type: 2,
application_id: "936929561302675456",
Expand Down Expand Up @@ -154,7 +151,7 @@ export class Midjourney extends MidjourneyMessage {
if (index < 1 || index > 4) {
throw new Error(`Variation index must be between 1 and 4, got ${index}`);
}
const nonce = SnowflakeUtil.generate().toString();
const nonce = nextNonce();
const httpStatus = await this.VariationApi(index, msgId, msgHash, nonce);
if (httpStatus !== 204) {
throw new Error(`VariationApi failed with status ${httpStatus}`);
Expand All @@ -169,7 +166,7 @@ export class Midjourney extends MidjourneyMessage {
index: number,
messageId: string,
messageHash: string,
nonce?: Snowflake
nonce?: string
) {
const payload = {
type: 3,
Expand Down Expand Up @@ -199,7 +196,7 @@ export class Midjourney extends MidjourneyMessage {
if (index < 1 || index > 4) {
throw new Error(`Variation index must be between 1 and 4, got ${index}`);
}
const nonce = SnowflakeUtil.generate().toString();
const nonce = nextNonce();
const httpStatus = await this.UpscaleApi(index, msgId, msgHash, nonce);
if (httpStatus !== 204) {
throw new Error(`VariationApi failed with status ${httpStatus}`);
Expand All @@ -215,7 +212,7 @@ export class Midjourney extends MidjourneyMessage {
index: number,
messageId: string,
messageHash: string,
nonce?: Snowflake
nonce?: string
) {
const payload = {
type: 3,
Expand Down
7 changes: 7 additions & 0 deletions src/utls/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { Snowflake } from "./snowflake";

export * from "./snowflake";

export const sleep = async (ms: number): Promise<void> =>
await new Promise((resolve) => setTimeout(resolve, ms));

export const random = (min: number, max: number): number =>
Math.floor(Math.random() * (max - min) + min);

const snowflake = new Snowflake(random(0, 1023));
export const nextNonce = (): string => snowflake.nextId().toString();
46 changes: 46 additions & 0 deletions src/utls/snowflake.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export class Snowflake {
private static readonly EPOCH = 1609459200000;
private static readonly SEQUENCE_BITS = 12;
private static readonly WORKER_ID_BITS = 10;
private static readonly MAX_SEQUENCE = (1 << Snowflake.SEQUENCE_BITS) - 1;
private static readonly MAX_WORKER_ID = (1 << Snowflake.WORKER_ID_BITS) - 1;

private sequence: number;
private lastTimestamp: number;

constructor(private readonly workerId: number) {
if (workerId > Snowflake.MAX_WORKER_ID || workerId < 0) {
throw new Error(
`worker id must be between 0 and ${Snowflake.MAX_WORKER_ID}`
);
}
this.sequence = 0;
this.lastTimestamp = -1;
}

public nextId(): number {
let timestamp = Date.now();
if (timestamp < this.lastTimestamp) {
throw new Error("Invalid System Clock");
}
if (this.lastTimestamp == timestamp) {
this.sequence++;
if (this.sequence > Snowflake.MAX_SEQUENCE) {
while (Date.now() <= timestamp) {
// Wait for next millisecond
}
timestamp = Date.now();
this.sequence = 0;
}
} else {
this.sequence = 0;
}
this.lastTimestamp = timestamp;
const id =
((timestamp - Snowflake.EPOCH) <<
(Snowflake.SEQUENCE_BITS + Snowflake.WORKER_ID_BITS)) |
(this.workerId << Snowflake.SEQUENCE_BITS) |
this.sequence;
return id;
}
}
7 changes: 1 addition & 6 deletions src/ws.message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
WsEventMsg,
ImageEventType,
} from "./interfaces";
import { error } from "console";

export class WsMessage {
DISCORD_GATEWAY =
Expand Down Expand Up @@ -145,11 +144,7 @@ export class WsMessage {
if (nonce && msg.t === "MESSAGE_CREATE") {
this.log("waiting start image or info or error");
this.updateMjEventIdByNonce(id, nonce);
if (
embeds &&
embeds.length > 0 &&
embeds[0].title === "Invalid parameter"
) {
if (embeds && embeds.length > 0 && embeds[0].title.includes("Invalid")) {
//error
const error = new Error(embeds[0].description);
this.EventError(id, error);
Expand Down
Loading

0 comments on commit e615d04

Please sign in to comment.