Skip to content

Commit

Permalink
Merge pull request #33 from N3aar/feat/backup-pull
Browse files Browse the repository at this point in the history
feat: pull db from discord
  • Loading branch information
Psykka authored Jun 22, 2024
2 parents 4c71517 + c974cc5 commit 96acd76
Show file tree
Hide file tree
Showing 4 changed files with 170 additions and 3 deletions.
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ DEPLOY_WEBHOOK_TOKEN=your_token_here
DEPLOY_WEBHOOK_ID=your_id_here

# discord backup webhook url
DISCORD_BACKUP_WEBHOOK=your_webhook_here
DISCORD_BACKUP_WEBHOOK=your_webhook_here

# discord backup channel id
BACKUP_CHANNEL_ID=your_channel_id_here
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"lint": "biome check src",
"lint:fix": "biome check --apply src",
"generate": "prisma generate",
"prepare": "husky || true"
"prepare": "husky || true",
"backup:pull": "node --env-file=.env scripts/pull_db"
},
"devDependencies": {
"@biomejs/biome": "1.7.3",
Expand All @@ -26,6 +27,7 @@
"husky": "^9.0.11",
"nodemon": "^3.1.1",
"rimraf": "^5.0.7",
"tar": "^7.4.0",
"tsc-alias": "^1.8.10",
"typescript": "^5.4.5"
},
Expand All @@ -39,4 +41,4 @@
"discord.js": "14.x",
"prisma": "^5.14.0"
}
}
}
52 changes: 52 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

110 changes: 110 additions & 0 deletions scripts/pull_db
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/env node

import * as tar from 'tar';
import { createWriteStream, mkdir, unlink, existsSync } from 'node:fs';
import { pipeline } from 'stream';
import { promisify } from 'node:util';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { tmpdir } from 'node:os';

const streamPipeline = promisify(pipeline);
const tempPath = tmpdir();
const __dirname = dirname(fileURLToPath(import.meta.url));

const BACKUP_CHANNEL_ID = process.env.BACKUP_CHANNEL_ID;
const pathToExtract = `${process.cwd()}/prisma`;
const fileName = 'db.sqlite'

const throwError = (message) => {
console.error(message);
process.exit(1);
}

console.log('Pulling backup from Discord...');

const fileUrl = await fetch(`https://discord.com/api/v10/channels/${BACKUP_CHANNEL_ID}/messages`, {
headers: {
Authorization: `Bot ${process.env.TOKEN}`,
},
})
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to fetch backup URL: ${res.statusText}`);
}

return res.json();
})
.then((data) => {
const message = data.find((message) => message.attachments.length > 0);
if (!message) {
throw new Error('No backup URL found');
}

const attachment = message.attachments[0]
if (!attachment) {
throw new Error('No backup URL found');
}

return attachment.url;
})
.catch((err) => {
throwError(`Failed to fetch backup URL: ${err}`);
});

if (!fileUrl) {
throwError('No backup URL found');
}

const tarballPath = resolve(tempPath, 'backup.tar.gz');
const extractPath = resolve(__dirname, pathToExtract);
const jornalPath = resolve(extractPath, `${fileName}-jornal`);

console.log(`Downloading backup from:\n${fileUrl.split('?')[0]}\n`);

await fetch(fileUrl)
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to download backup: ${res.statusText}`);
}

return res.body
})
.then((body) => {
const writeStream = createWriteStream(tarballPath);
return streamPipeline(body, writeStream);
})
.catch((err) => {
throwError(`Failed to download backup: ${err}`);
});

console.log(`Extracting backup to:\n${extractPath}\n`);

await mkdir(extractPath, { recursive: true }, (err) => {
if (err) {
throwError(`Failed to create backup directory: ${err}`);
}
});

await tar.extract({
file: tarballPath,
cwd: extractPath,
strip: 1,
filter: (path) => path.endsWith(fileName),
})

await unlink(tarballPath, (err) => {
if (err) {
throwError(`Failed to delete tarball: ${err}`);
}
});

if (existsSync(jornalPath)) {
await unlink(jornalPath, (err) => {
if (err) {
throwError(`Failed to delete jornal file: ${err}`);
}
});
}

console.log('Backup extracted successfully!\n');

0 comments on commit 96acd76

Please sign in to comment.