Skip to content

Commit 1564db5

Browse files
authored
Custom formatting names (#53)
1 parent 67fd7a0 commit 1564db5

File tree

4 files changed

+42
-19
lines changed

4 files changed

+42
-19
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ General usage
132132
~$ kobodl book get \
133133
134134
--output-dir /path/to/download_directory \
135+
--format-str '{Title}' \
135136
c1db3f5c-82da-4dda-9d81-fa718d5d1d16
136137

137138
# Download ALL books with default options when only 1 user exists
@@ -141,6 +142,7 @@ General usage
141142
~$ kobodl book get \
142143
143144
--output-dir /path/to/download_directory \
145+
--format-str '{Title}' \
144146
--get-all
145147
```
146148

kobodl/actions.py

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import os
3+
import platform
34
from typing import List, TextIO, Tuple, Union
45

56
import click
@@ -32,29 +33,34 @@ def __GetBookAuthor(book: dict) -> str:
3233
return ' & '.join(authors)
3334

3435

35-
def __SanitizeFileName(fileName: str) -> str:
36+
def __SanitizeString(string: str) -> str:
3637
result = ''
37-
for c in fileName:
38+
for c in string:
3839
if c.isalnum() or ' ,;.!(){}[]#$\'-+@_'.find(c) >= 0:
3940
result += c
4041

4142
result = result.strip(' .')
42-
result = result[
43-
:100
44-
] # Limit the length -- mostly because of Windows. It would be better to do it on the full path using MAX_PATH.
43+
if platform.system() == 'Windows':
44+
# Limit the length -- mostly because of Windows. It would be better to do it on the full path using MAX_PATH.
45+
result = result[:100]
4546
return result
4647

4748

48-
def __MakeFileNameForBook(bookMetadata: dict) -> str:
49+
def __MakeFileNameForBook(bookMetadata: dict, formatStr: str) -> str:
4950
'''filename without extension'''
5051
fileName = ''
51-
author = __GetBookAuthor(bookMetadata)
52-
if len(author) > 0:
53-
fileName = author + ' - '
54-
fileName += bookMetadata['Title']
55-
fileName = __SanitizeFileName(fileName)
56-
# Append a portion of revisionId to prevent name collisions.
57-
return f"{fileName} {bookMetadata['RevisionId'][:8]}"
52+
author = __SanitizeString(__GetBookAuthor(bookMetadata))
53+
title = __SanitizeString(bookMetadata['Title'])
54+
55+
return formatStr.format_map(
56+
{
57+
**bookMetadata,
58+
'Author': author,
59+
'Title': title,
60+
# Append a portion of revisionId to prevent name collisions.
61+
'ShortRevisionId': bookMetadata['RevisionId'][:8],
62+
}
63+
)
5864

5965

6066
def __GetBookMetadata(entitlement: dict) -> Tuple[dict, BookType]:
@@ -163,7 +169,12 @@ def Login(user: User, password: str, captcha: str) -> None:
163169
kobo.Login(user.Email, password, captcha)
164170

165171

166-
def GetBookOrBooks(user: User, outputPath: str, productId: str = '') -> Union[None, str]:
172+
def GetBookOrBooks(
173+
user: User,
174+
outputPath: str,
175+
formatStr: str = r'{Author} - {Title} {ShortRevisionId}',
176+
productId: str = '',
177+
) -> Union[None, str]:
167178
"""
168179
download 1 or all books to file
169180
returns output filepath if identifier is passed, otherwise returns None
@@ -192,7 +203,7 @@ def GetBookOrBooks(user: User, outputPath: str, productId: str = '') -> Union[No
192203
click.echo('Skipping subscribtion entity')
193204
continue
194205

195-
fileName = __MakeFileNameForBook(bookMetadata)
206+
fileName = __MakeFileNameForBook(bookMetadata, formatStr)
196207
if book_type == BookType.EBOOK:
197208
# Audiobooks go in sub-directories
198209
# but epub files go directly in outputPath

kobodl/commands/book.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import os
2+
from pathlib import Path
3+
from typing import List
24

35
import click
46
from tabulate import tabulate
@@ -33,11 +35,19 @@ def book():
3335
'--output-dir',
3436
type=click.Path(file_okay=False, dir_okay=True, writable=True),
3537
default='kobo_downloads',
38+
help='default: kobo_downloads',
3639
)
3740
@click.option('-a', '--get-all', is_flag=True)
41+
@click.option(
42+
'-f',
43+
'--format-str',
44+
type=click.STRING,
45+
default=r'{Author} - {Title} {ShortRevisionId}',
46+
help=r"default: '{Author} - {Title} {ShortRevisionId}'",
47+
)
3848
@click.argument('product-id', nargs=-1, type=click.STRING)
3949
@click.pass_obj
40-
def get(ctx, user, output_dir, get_all, product_id):
50+
def get(ctx, user, output_dir: Path, get_all: bool, format_str: str, product_id: List[str]):
4151
if len(Globals.Settings.UserList.users) == 0:
4252
click.echo('error: no users found. Did you `kobodl user add`?', err=True)
4353
exit(1)
@@ -67,10 +77,10 @@ def get(ctx, user, output_dir, get_all, product_id):
6777

6878
os.makedirs(output_dir, exist_ok=True)
6979
if get_all:
70-
actions.GetBookOrBooks(usercls, output_dir)
80+
actions.GetBookOrBooks(usercls, output_dir, formatStr=format_str)
7181
else:
7282
for pid in product_id:
73-
output = actions.GetBookOrBooks(usercls, output_dir, productId=pid)
83+
actions.GetBookOrBooks(usercls, output_dir, formatStr=format_str, productId=pid)
7484

7585

7686
@book.command(name='list', help='list books')

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
setup(
1010
name='kobodl',
1111
author='Brandon Davis',
12-
version='0.7.2',
12+
version='0.7.3',
1313
author_email='[email protected]',
1414
url="https://github.com/subdavis/kobo-book-downloader",
1515
long_description=long_description,

0 commit comments

Comments
 (0)