0
# Command Line Interface
1
2
Command-line interface for interactive downloads and batch operations with environment variable support and user-friendly interaction patterns.
3
4
## Types
5
6
```python { .api }
7
from typing import List, Dict, Any, Optional, Union
8
```
9
10
## Capabilities
11
12
### Main CLI Class
13
14
Interactive command-line interface for downloading content with user prompts and batch operations.
15
16
```python { .api }
17
class JmcomicUI:
18
"""
19
Command-line interface for interactive JMComic downloads.
20
21
Provides a user-friendly CLI with interactive prompts, batch operations,
22
and configuration management for downloading albums and photos.
23
24
Attributes:
25
- option: JmOption - Configuration options for downloads
26
- downloader: JmDownloader - Downloader instance
27
- interactive_mode: bool - Whether to use interactive prompts
28
29
Methods:
30
- run(): Start interactive CLI session
31
- download_single(jm_id): Download single album or photo
32
- download_batch(jm_ids): Download multiple items
33
- configure_options(): Interactive option configuration
34
- show_help(): Display help information
35
- show_status(): Display current status and statistics
36
"""
37
38
def __init__(self, option: 'JmOption' = None, interactive_mode: bool = True):
39
"""
40
Initialize CLI interface.
41
42
Parameters:
43
- option: JmOption, optional - Configuration options
44
- interactive_mode: bool - Enable interactive prompts
45
"""
46
self.option = option or JmOption.default()
47
self.interactive_mode = interactive_mode
48
self.downloader = None
49
50
def run(self):
51
"""
52
Start interactive CLI session.
53
54
Presents main menu and handles user input for various operations
55
including downloads, configuration, and status display.
56
"""
57
58
def download_single(self, jm_id: Union[str, int]) -> bool:
59
"""
60
Download single album or photo with progress display.
61
62
Parameters:
63
- jm_id: str or int - JM ID to download
64
65
Returns:
66
bool - True if download successful
67
"""
68
69
def download_batch(self, jm_ids: List[Union[str, int]]) -> Dict[str, bool]:
70
"""
71
Download multiple albums or photos with progress tracking.
72
73
Parameters:
74
- jm_ids: list - List of JM IDs to download
75
76
Returns:
77
dict - Mapping of JM ID to success status
78
"""
79
80
def configure_options(self):
81
"""
82
Interactive configuration of download options.
83
84
Presents prompts for setting download directories, client preferences,
85
plugin configurations, and other options.
86
"""
87
88
def show_help(self):
89
"""Display help information and usage examples."""
90
91
def show_status(self):
92
"""
93
Display current status and download statistics.
94
95
Shows information about current configuration, recent downloads,
96
and system status.
97
"""
98
```
99
100
Usage examples:
101
102
```python
103
# Start interactive CLI
104
ui = JmcomicUI()
105
ui.run()
106
107
# Non-interactive usage
108
option = JmOption.from_file("config.yml")
109
ui = JmcomicUI(option, interactive_mode=False)
110
success = ui.download_single("123456")
111
112
# Batch download
113
jm_ids = ["123456", "789012", "345678"]
114
results = ui.download_batch(jm_ids)
115
for jm_id, success in results.items():
116
print(f"{jm_id}: {'Success' if success else 'Failed'}")
117
```
118
119
### Main Entry Point
120
121
Main function that serves as the primary entry point for the CLI application.
122
123
```python { .api }
124
def main():
125
"""
126
Main entry point for the JMComic CLI application.
127
128
Handles command-line argument parsing, configuration loading,
129
and initialization of the CLI interface.
130
131
Command-line arguments:
132
- --config, -c: Path to configuration file
133
- --batch, -b: Batch mode with IDs from file or stdin
134
- --id: Single JM ID to download
135
- --help, -h: Show help information
136
- --version, -v: Show version information
137
- --interactive, -i: Force interactive mode
138
- --quiet, -q: Quiet mode with minimal output
139
"""
140
```
141
142
Command-line usage examples:
143
144
```bash
145
# Interactive mode (default)
146
python -m jmcomic
147
148
# Download single album
149
python -m jmcomic --id 123456
150
151
# Download with custom config
152
python -m jmcomic --config custom_config.yml --id 123456
153
154
# Batch download from file
155
python -m jmcomic --batch album_ids.txt
156
157
# Batch download from stdin
158
echo "123456 789012 345678" | python -m jmcomic --batch -
159
160
# Quiet mode
161
python -m jmcomic --quiet --id 123456
162
163
# Show help
164
python -m jmcomic --help
165
166
# Show version
167
python -m jmcomic --version
168
```
169
170
### Environment Variable Helper
171
172
Utility function for reading environment variables with default values.
173
174
```python { .api }
175
def get_env(name: str, default: Any = None) -> Any:
176
"""
177
Get environment variable value with default fallback.
178
179
Provides consistent environment variable access across the
180
application with support for type conversion and defaults.
181
182
Parameters:
183
- name: str - Environment variable name
184
- default: Any - Default value if variable not set
185
186
Returns:
187
Any - Environment variable value or default
188
"""
189
```
190
191
Usage examples:
192
193
```python
194
# Get environment variables with defaults
195
config_path = get_env('JM_CONFIG_PATH', 'default_config.yml')
196
max_threads = get_env('JM_MAX_THREADS', 4)
197
debug_mode = get_env('JM_DEBUG', False)
198
199
# Boolean environment variables
200
debug_enabled = get_env('JM_DEBUG', 'false').lower() in ('true', '1', 'yes')
201
```
202
203
## CLI Features
204
205
### Interactive Mode
206
207
When run in interactive mode, the CLI provides a menu-driven interface:
208
209
```
210
JMComic Downloader v2.6.6
211
=========================
212
213
1. Download single album/photo
214
2. Batch download
215
3. Configure options
216
4. View download history
217
5. Show status
218
6. Help
219
7. Exit
220
221
Select option (1-7):
222
```
223
224
### Configuration Management
225
226
The CLI supports various configuration sources in order of precedence:
227
228
1. Command-line arguments
229
2. Environment variables
230
3. Configuration files
231
4. Interactive prompts
232
5. Default values
233
234
### Batch Processing
235
236
Batch mode supports multiple input formats:
237
238
```bash
239
# From file (one ID per line)
240
python -m jmcomic --batch ids.txt
241
242
# From stdin
243
echo "123456" | python -m jmcomic --batch -
244
245
# Multiple IDs in single line
246
echo "123456 789012 345678" | python -m jmcomic --batch -
247
```
248
249
### Progress Display
250
251
The CLI provides visual progress indicators:
252
253
- Overall progress for batch operations
254
- Individual download progress
255
- Speed and ETA information
256
- Error summary and statistics
257
258
### Logging and Output
259
260
Output levels can be controlled:
261
262
- **Normal**: Standard progress and completion messages
263
- **Quiet** (`--quiet`): Minimal output, errors only
264
- **Verbose** (`--verbose`): Detailed operation logs
265
- **Debug**: Full debugging information
266
267
## Environment Variables
268
269
The CLI recognizes these environment variables:
270
271
```bash
272
# Configuration
273
export JM_CONFIG_PATH=/path/to/config.yml
274
export JM_OPTION_PATH=/path/to/options.yml
275
276
# Download settings
277
export JM_DOWNLOAD_DIR=/path/to/downloads
278
export JM_MAX_THREADS=8
279
280
# Client settings
281
export JM_RETRY_COUNT=3
282
export JM_TIMEOUT=30
283
export JM_USER_AGENT="Custom User Agent"
284
285
# Plugin settings
286
export JM_ENABLE_LOGIN=true
287
export JM_LOGIN_USERNAME=user@example.com
288
export JM_LOGIN_PASSWORD=password
289
290
# Output control
291
export JM_QUIET=false
292
export JM_DEBUG=false
293
export JM_LOG_FILE=/path/to/log.txt
294
```
295
296
## Integration Examples
297
298
### Shell Script Integration
299
300
```bash
301
#!/bin/bash
302
# Download script with error handling
303
304
export JM_CONFIG_PATH="./production_config.yml"
305
export JM_QUIET=true
306
307
if python -m jmcomic --id "$1"; then
308
echo "Download successful: $1"
309
exit 0
310
else
311
echo "Download failed: $1"
312
exit 1
313
fi
314
```
315
316
### Python Integration
317
318
```python
319
import sys
320
from jmcomic.cl import JmcomicUI, get_env
321
322
# Programmatic CLI usage
323
def automated_download(album_ids):
324
config_path = get_env('JM_CONFIG_PATH', 'config.yml')
325
option = JmOption.from_file(config_path)
326
327
ui = JmcomicUI(option, interactive_mode=False)
328
results = ui.download_batch(album_ids)
329
330
return all(results.values())
331
332
# Use in scripts
333
if __name__ == "__main__":
334
album_ids = sys.argv[1:]
335
success = automated_download(album_ids)
336
sys.exit(0 if success else 1)
337
```
338
339
### Configuration File Integration
340
341
```yaml
342
# cli_config.yml
343
download:
344
base_dir: "/downloads"
345
max_threads: 6
346
347
cli:
348
default_mode: "interactive"
349
show_progress: true
350
confirm_downloads: true
351
save_history: true
352
history_file: "download_history.json"
353
354
logging:
355
level: "INFO"
356
file: "jmcomic.log"
357
format: "[{timestamp}] {level}: {message}"
358
```
359
360
## Error Handling in CLI
361
362
The CLI provides user-friendly error messages and recovery options:
363
364
- Network errors: Suggest checking connection and retrying
365
- Authentication errors: Prompt for credential verification
366
- Configuration errors: Show specific validation failures
367
- Partial failures: Display success/failure summary with options to retry failed items
368
- Interrupt handling: Graceful shutdown on Ctrl+C with cleanup