Skip to content

Commit

Permalink
feat: metadata file with book files
Browse files Browse the repository at this point in the history
  • Loading branch information
jedwards1230 committed Apr 21, 2024
1 parent da25bc4 commit 7f2cf2e
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 23 deletions.
4 changes: 2 additions & 2 deletions cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ const Command = yargs(hideBin(process.argv))

const downloadHelper = async (book: Audiobook) => {
logger.info(`Downloading: ${book.title}`);
const [path, zippedPaths] = await client.downloadBook(
const filepath = await client.downloadBook(
book,
argv.overwrite,
argv.keepZip
);
if (path) {
if (filepath) {
logger.info(`Downloaded ${book.title}`);
count++;
} else {
Expand Down
8 changes: 3 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
services:
libro-client:
libro:
build:
context: .
dockerfile: Dockerfile
container_name: libro
develop:
watch:
- action: sync
Expand All @@ -13,10 +14,7 @@ services:
- action: rebuild
path: package.json
volumes:
- data:/app/data/
- ./data:/app/data/
- ${PWD}/downloads:/app/downloads/
env_file:
- .env

volumes:
data:
Binary file added libro
Binary file not shown.
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
{
"name": "libro-client",
"version": "0.0.5",
"version": "0.0.6",
"module": "cli.ts",
"type": "module",
"description": "Library for downloading Libro.fm audiobooks",
"author": "[email protected]",
"repository": "github:jedwards1230/libro-client",
"repository": {
"url": "git+https://github.com/jedwards1230/libro-client.git"
},
"license": "MIT",
"bin": {
"libro": "cli.ts"
Expand All @@ -16,8 +18,10 @@
},
"scripts": {
"start": "bun run cli.ts",
"service": "bun run service.ts",
"build:cli": "bun build ./cli.ts --compile --minify --sourcemap --outfile libro",
"build:docker": "docker build . -t jedwards1230/libro:latest",
"push:cli": "npm publish",
"push:docker": "docker push jedwards1230/libro:latest"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ const downloadBooks = async (newBooks: Audiobook[]) => {
if (book) {
console.log(`Downloading: ${book.title}`);
try {
const [path, zippedPaths] = await client.downloadBook(
const filepath = await client.downloadBook(
book,
overwrite,
keepZip
);
if (path) {
if (filepath) {
console.log(`Downloaded ${book.title}`);
return book;
} else {
Expand Down
17 changes: 12 additions & 5 deletions src/LibroFmClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export default class LibroFmClient {
book: Audiobook,
overwrite: boolean = false,
keepZip: boolean = false
): Promise<[string, string[] | false]> {
): Promise<string> {
if (!this.config.authToken) throw new Error("Not logged in");
const authToken = this.config.authToken;

Expand All @@ -97,27 +97,34 @@ export default class LibroFmClient {
logger.verbose("Skipping download", {
fn: "LibroFmClient.downloadBook",
});
return ["", false];
return "";
}
}

try {
const bookPath = `${book.authors}`;
if (!book.authors) throw new Error("No authors found");
const filename =
typeof book.authors === "string"
? book.authors
: book.authors.join(", ");

const [path, zipped_files] = await DownloadCLient.downloadFiles(
bookPath,
filename,
urls,
authToken,
keepZip
);

await DownloadCLient.saveMetadata(book, path);

this.state.addBook({
book,
path,
meta: metadata,
...(zipped_files && { zippedPaths: zipped_files }),
});

return [`./${bookPath}`, zipped_files];
return filename;
} catch (error) {
logger.error({ error, fn: "LibroFmClient.downloadBook" });
throw new Error("Failed to download books");
Expand Down
20 changes: 16 additions & 4 deletions src/lib/DownloadClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default class DownloadCLient {
* */
@LogMethod({ scope, message: "Downloading files..." })
static async downloadFiles(
filenamePrefix: string,
filename: string,
urls: string[],
authToken: string,
keepZip = false
Expand All @@ -29,22 +29,34 @@ export default class DownloadCLient {
keepZip &&
(await Promise.all(
buffers.map((buffer, idx) =>
DownloadCLient.save(buffer, `/${filenamePrefix}-${idx}.zip`)
DownloadCLient.save(buffer, `/${filename}-${idx}.zip`)
)
));

const paths = await Promise.all(
buffers.map((buffer, idx) =>
DownloadCLient.unzip(buffer, `/${filenamePrefix}-${idx}`)
DownloadCLient.unzip(buffer, `/${filename}-${idx}`)
)
);

const finalPath = path.join(DOWNLOAD_DIR, filenamePrefix);
const finalPath = path.join(DOWNLOAD_DIR, filename);
await DownloadCLient.mergeDirectories(paths, finalPath);

return [finalPath, zipped_files];
}

/**
* Save Audiobook object as JSON file alongside the downloaded files.
*/
@LogMethod({ scope, message: "Saving metadata..." })
static async saveMetadata(
book: Audiobook,
filepath: string
): Promise<void> {
const metadataPath = path.join(filepath, "metadata.json");
fs.writeFileSync(metadataPath, JSON.stringify(book, null, 2));
}

/** Downloads a file from a URL and returns the data as a Uint8Array */
@LogMethod({ scope, message: "Downloading file..." })
private static async download(
Expand Down
15 changes: 13 additions & 2 deletions src/lib/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ if (fs.existsSync(LOGS_DIR)) {
});
}

const logFile = path.join(LOGS_DIR, "silly.log");
const sillyLogFile = path.join(LOGS_DIR, "silly.log");
const debugLogFile = path.join(LOGS_DIR, "debug.log");

const DEBUG_MODE = process.env.DEBUG === "true";

Expand Down Expand Up @@ -69,9 +70,19 @@ const logger = createLogger({
format.timestamp(),
getFormat(true)
),
filename: logFile,
filename: sillyLogFile,
level: "silly",
}),
new transports.File({
format: format.combine(
format.errors({ stack: true }),
format.splat(),
format.timestamp(),
getFormat(true)
),
filename: debugLogFile,
level: "debug",
}),
],
});

Expand Down
2 changes: 1 addition & 1 deletion src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type StateDataMap = {
interface Audiobook {
isbn: string;
title: string;
authors?: string[];
authors?: string | string[];
cover_url?: string;
catalog_info?: {
bookseller_pick?: boolean;
Expand Down

0 comments on commit 7f2cf2e

Please sign in to comment.