Add file format

This changed a lot of things, I did not think this would happen :P
master
Vishnunarayan K I 2018-06-10 23:33:56 +05:30
parent 8624bee9eb
commit 04e1bb1e78
7 changed files with 76 additions and 25 deletions

View File

@ -1 +1 @@
__version__ = '2.3.3'
__version__ = '2.3.4dev'

View File

@ -55,12 +55,12 @@ def cli():
type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR']),
help='Sets the level of logger')
@click.option(
'--name-fmt', '-nf',
'--file-format', '-ff', default='{anime_title}/{anime_title}_{ep_no}',
help='Format for how the files to be downloaded be named.'
)
@click.pass_context
def dl(ctx, anime_url, episode_range, url, player, skip_download, quality,
force_download, log_level, download_dir, name_fmt):
force_download, log_level, download_dir, file_format):
""" Download the anime using the url or search for it.
"""
@ -99,9 +99,10 @@ def dl(ctx, anime_url, episode_range, url, player, skip_download, quality,
util.play_episode(episode)
if not skip_download:
util.download_episode(episode, force_download=force_download,
download_dir=download_dir)
episode.download(force=force_download,
path=download_dir,
format=file_format)
print()
@cli.command()
@ -203,7 +204,7 @@ def list_animes(watcher, quality):
meta += '{}: {}\n'.format(k, click.style(v, bold=True))
click.echo(meta)
click.echo('Available Commands: set, remove, update, watch\n')
click.echo('Available Commands: set, remove, update, watch, download\n')
inp = click.prompt('Press q to exit', default='q').strip()
@ -229,8 +230,9 @@ def list_animes(watcher, quality):
inp = inp+str(len(anime)) if inp.endswith(':') else inp
anime = util.split_anime(anime, inp)
for episode in anime:
util.download_episode(episode, force_download=False,
download_dir=Config['dl']['download_dir'])
episode.download(force=False,
path=Config['dl']['download_dir'],
format=Config['dl']['file_format'])
elif inp.startswith('set '):
inp = inp.split('set ')[-1]
key, val = [v.strip() for v in inp.split('=')]

View File

@ -14,6 +14,7 @@ DEFAULT_CONFIG = {
'quality': '720p',
'force_download': False,
'log_level': 'INFO',
'file_format': '{anime_title}/{anime_title}_{ep_no}'
},
'watch': {
'quality': '720p',
@ -38,6 +39,15 @@ class _Config:
else:
self._CONFIG = self._read_config()
def update(gkey):
for key, val in DEFAULT_CONFIG[gkey].items():
if key not in self._CONFIG[gkey].keys():
self._CONFIG[gkey][key] = val
for key in ['dl', 'watch']:
update(key)
self.write()
@property
def CONTEXT_SETTINGS(self):
return dict(
@ -47,6 +57,9 @@ class _Config:
def __getitem__(self, attr):
return self._CONFIG[attr]
def write(self):
self._write_config(self._CONFIG)
def _write_config(self, config_dict):
with open(self.CONFIG_FILE, 'w') as configfile:
json.dump(config_dict, configfile, indent=4, sort_keys=True)

View File

@ -5,6 +5,7 @@ import time
import os
import logging
import sys
import copy
from anime_downloader.sites.exceptions import AnimeDLError, NotFoundError
from anime_downloader.sites import util
@ -55,6 +56,9 @@ class BaseAnime:
logging.debug('EPISODE IDS: length: {}, ids: {}'.format(
self._len, self._episodeIds))
self._episodeIds = [(no+1, id) for no, id in
enumerate(self._episodeIds)]
return self._episodeIds
def __len__(self):
@ -63,10 +67,11 @@ class BaseAnime:
def __getitem__(self, index):
if isinstance(index, int):
ep_id = self._episodeIds[index]
return self._episodeClass(ep_id, self.quality, parent=self,
ep_no=index+1)
return self._episodeClass(ep_id[1], self.quality, parent=self,
ep_no=ep_id[0])
elif isinstance(index, slice):
self._episodeIds = self._episodeIds[index]
anime = copy.deepcopy(self)
anime._episodeIds = anime._episodeIds[index]
return self
def __repr__(self):
@ -99,6 +104,9 @@ class BaseEpisode:
self.ep_no = ep_no
self.episode_id = episode_id
self.quality = quality
self._parent = parent
self.pretty_title = '{}-{}'.format(self._parent.title, self.ep_no)
logging.debug("Extracting stream info of id: {}".format(self.episode_id))
try:
@ -118,10 +126,11 @@ class BaseEpisode:
def getData(self):
raise NotImplementedError
def download(self, force=False, path=None):
logging.info('Downloading {}'.format(self.title))
file_name = util.slugify(self.title)
def download(self, force=False, path=None,
format='{anime_title}_{ep_no}'):
logging.info('Downloading {}'.format(self.pretty_title))
if format:
file_name = util.format_filename(format, self)+'.mp4'
if path is None:
path = './' + file_name
@ -134,6 +143,8 @@ class BaseEpisode:
r = requests.get(self.stream_url, stream=True)
util.make_dir(path.rsplit('/', 1)[0])
total_size = int(r.headers['Content-length'])
downloaded, chunksize = 0, 2048
start_time = time.time()

View File

@ -3,6 +3,8 @@ import json
import requests
from bs4 import BeautifulSoup
import re
import os
import errno
from anime_downloader.sites.exceptions import NotFoundError
@ -42,3 +44,22 @@ def get_stream_url_rapidvideo(url, quality):
def slugify(file_name):
file_name = str(file_name).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', file_name)
def format_filename(filename, epiosde):
rep_dict = {
'anime_title': slugify(epiosde._parent.title),
'ep_no': epiosde.ep_no,
}
filename = filename.format(**rep_dict)
return filename
def make_dir(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise

View File

@ -2,11 +2,13 @@ import logging
import sys
import shutil
import click
from anime_downloader.sites.nineanime import NineAnime
import subprocess
import platform
from anime_downloader.sites.nineanime import NineAnime
def setup_logger(log_level):
if log_level == 'DEBUG':
format = '%(levelname)s %(name)s: %(message)s'
@ -83,8 +85,8 @@ def print_episodeurl(episode):
print(episode.stream_url)
def download_episode(episode, *, force_download, download_dir):
episode.download(force=force_download, path=download_dir)
def download_episode(episode, **kwargs):
episode.download(**kwargs)
print()
@ -94,6 +96,6 @@ def play_epiosde(episode, *, player):
def print_info(version):
logging.info('Version: {}'.format(version))
logging.info('anime-downloader {}'.format(version))
logging.debug('Platform: {}'.format(platform.platform()))
logging.debug('Python {}'.format(platform.python_version()))

View File

@ -58,11 +58,13 @@ class Watcher:
return anime
def update_anime(self, anime):
anime_name = anime.title
anime.getEpisodes()
anime.title = anime_name
self.update(anime)
return anime
logging.info('Updating anime {}'.format(anime.title))
newanime = AnimeInfo(anime.url, episodes_done=anime.episodes_done,
timestamp=time())
newanime.title = anime.title
self.update(newanime)
return newanime
def add(self, anime):
self._append_to_watch_file(anime)