Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
akazukin5151 committed Jul 26, 2020
2 parents c9a5df9 + 9ff9a3b commit df58e7e
Show file tree
Hide file tree
Showing 21 changed files with 339 additions and 129 deletions.
138 changes: 138 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,141 @@ dist/
*egg-info/
.coverage
testing/htmlcov/

__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
8 changes: 5 additions & 3 deletions HACKING.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,13 @@ Now, this paints a rosy picture but in reality, there was no initial planning so

Here are some good tips:
* "The way to figure out the separation is by doing as much as you can without mutation, and then encapsulating the mutation separately" (Gary Bernhardt)
* "Create your application to work without either a UI or a database so you can run automated regression-tests against the application, work when the database becomes unavailable, and **link applications together without any user involvement**" ([Alistair Cockburn](https://github.com/jschairb/sandbox/wiki/HexagonalArchitecture)) (Emphasis mine; it is possible to adapt koneko to work with sites other than pixiv)
* At the very least, only the api and download modules need to be replaced.
* `data.py` will need to be adapted to your new API structure.
* "Create your application to work without either a UI or a database so you can run automated regression-tests against the application, work when the database becomes unavailable, and **link applications together without any user involvement**" ([Alistair Cockburn](https://github.com/jschairb/sandbox/wiki/HexagonalArchitecture)) (Emphasis mine)

It is possible to adapt koneko to work with sites other than pixiv:
* At the very least, only the `api` and `data` modules need to be replaced.
* The config already handles username and passwords, but you can add something like an API key or OTP auth
* The navigation routes (eg pages, prompt handling) are in `ui.py`, while the starting dispatch logic is in `main.py`
* See the [koneko-twitter](https://github.com/twenty5151/koneko-twitter) and [koneko-gelbooru](https://github.com/twenty5151/koneko-gelbooru/) repos for some rough examples


## Cache directory structure
Expand Down
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,26 @@ For full changelogs please see [releases](https://github.com/twenty5151/koneko/r

### Version 0.10.1

* Two new examples of koneko being applied to another site:
* [koneko-twitter](https://github.com/twenty5151/koneko-twitter)
* [koneko-gelbooru](https://github.com/twenty5151/koneko-gelbooru/)

#### Features

#### Bug fixes
* Fix inconsistent 'page' / 'image' in ui.Image
* Fixed inconsistent 'page' / 'image' in ui.Image
* Fixed `du` not working in macOS
* Fixed `xdg-open` not present in macOS, use `open` in that case instead
* Fixed bug where artist name with '/' isn't downloaded
* Fixed users mode prefetching page 1 again

#### Code maintenance
* Added more tests
* Use int page_num for gallery data cache keys
* Extract duplicated init method in gdata and udata to ABC
* Remove sys path modifications by changing pytest command & conftest path. No need to run pytest with the `-s` argument. There is a `conftest.py` symlink in root, pointing to the original path in `testing/`
* Fixed tests sometimes showing a (pixcat) image: mock and assert pixcat in lscat.icat()
* Use default github gitignore for python


# Roadmap
Expand Down
18 changes: 9 additions & 9 deletions koneko/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def _login_with_token(self) -> bool:
return True


def _login_with_creds(self) -> 'Optional[dict[dict[str]]]':
def _login_with_creds(self) -> 'Optional[dict[str, dict[str]]]':
try:
return self._api.login(
self._credentials['Username'],
Expand All @@ -71,53 +71,53 @@ def _login_with_creds(self) -> 'Optional[dict[dict[str]]]':
# Public API request functions for each mode
@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
@utils.spinner('')
def artist_gallery(self, artist_user_id, offset):
def artist_gallery(self, artist_user_id, offset) -> 'Json':
"""Mode 1"""
self._await_login()
return self._api.user_illusts(artist_user_id, offset=offset)

@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
def protected_illust_detail(self, image_id):
def protected_illust_detail(self, image_id) -> 'Json':
"""Mode 2"""
self._await_login()
return self._api.illust_detail(image_id)

@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
def following_user_request(self, user_id, publicity, offset):
def following_user_request(self, user_id, publicity, offset) -> 'Json':
"""Mode 3"""
self._await_login()
return self._api.user_following(user_id, restrict=publicity, offset=offset)

@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
def search_user_request(self, searchstr, offset):
def search_user_request(self, searchstr, offset) -> 'Json':
"""Mode 4"""
self._await_login()
return self._api.search_user(searchstr, offset=offset)

@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
@utils.spinner('')
def illust_follow_request(self, restrict, offset):
def illust_follow_request(self, restrict, offset) -> 'Json':
"""Mode 5"""
self._await_login()
return self._api.illust_follow(restrict=restrict, offset=offset)

@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
@utils.spinner('')
def illust_related_request(self, image_id, offset):
def illust_related_request(self, image_id, offset) -> 'Json':
"""Mode 15 (1.5 * 10 so it's an int)"""
self._await_login()
return self._api.illust_related(illust_id=image_id, offset=offset)

@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
@utils.spinner('')
def illust_recommended_request(self, offset):
def illust_recommended_request(self, offset) -> 'Json':
"""Mode 6"""
self._await_login()
return self._api.illust_recommended(offset=offset)

# Download
@funcy.retry(tries=3, errors=(ConnectionError, PixivError))
def protected_download(self, url, path, name):
def protected_download(self, url, path, name) -> 'IO':
"""Protect api download function with funcy.retry so it doesn't crash"""
self._await_login()
self._api.download(url, path=path, name=name)
Expand Down
6 changes: 3 additions & 3 deletions koneko/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def handle_vh() -> 'Optional[dict]':
return args


def launch_mode(args, your_id):
def launch_mode(args: 'docopt.Dict[str, str]', your_id: str):
print('Logging in...')

if (url_or_str := args['<link>']):
Expand All @@ -68,7 +68,7 @@ def launch_mode(args, your_id):
return parse_mode_given(args)


def parse_no_mode(url_or_str: str, your_id):
def parse_no_mode(url_or_str: str, your_id: str):
if 'users' in url_or_str:
return main.ArtistModeLoop(pure.process_user_url(url_or_str)).start()

Expand All @@ -93,7 +93,7 @@ def parse_no_mode(url_or_str: str, your_id):
return main.SearchUsersModeLoop(url_or_str).start()


def parse_mode_given(args: 'dict') -> (str, str):
def parse_mode_given(args: 'docopt.Dict[str, str]'):
url_or_id = args['<link_or_id>']

if args['1'] or args['a']:
Expand Down
8 changes: 4 additions & 4 deletions koneko/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,13 @@ def gallery_print_spacing_config() -> 'list[str]':



def credentials_from_config(config_object, config_path) -> ('config', str):
def credentials_from_config(config_object, config_path) -> 'IO[(config, str)]':
credentials = get_config_section('Credentials').unwrap()
your_id = credentials.get('ID', '')
return credentials, your_id

# Technically frontend
def begin_config() -> ('IO[config]', str):
def begin_config() -> 'IO[(config, str)]':
os.system('clear')
config_path = Path('~/.config/koneko/config.ini').expanduser()
config_object = ConfigParser()
Expand All @@ -129,7 +129,7 @@ def begin_config() -> ('IO[config]', str):
return init_config(config_object, config_path)


def init_config(config_object, config_path) -> ('IO[config]', str):
def init_config(config_object, config_path) -> 'IO[(config, str)]':
# Identical to `_ask_your_id(_ask_credentials(config_object))`
config_object, your_id = flow(
config_object,
Expand All @@ -150,7 +150,7 @@ def _ask_credentials(config_object) -> 'IO[config]':
return config_object


def _ask_your_id(config_object) -> ('IO[config]', str):
def _ask_your_id(config_object) -> 'IO[(config, str)]':
print('\nDo you want to save your pixiv ID? It will be more convenient')
print('to view artists you are following')
ans = input()
Expand Down
17 changes: 8 additions & 9 deletions koneko/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Functionally pure, no side effects (but stores state)
"""
from abc import ABC, abstractmethod
from functools import lru_cache, cached_property
from functools import lru_cache

from koneko import pure, KONEKODIR

Expand Down Expand Up @@ -125,37 +125,36 @@ def artist_user_id(self, post_number: int) -> str:
"""Get the artist user id for a specified post number"""
return self._iterate_cache(lambda x: x['user']['id'])[post_number]

@cached_property
@property
def all_urls(self) -> 'list[str]':
return self.profile_pic_urls + self.image_urls

@cached_property
@property
def all_names(self) -> 'list[str]':
preview_names_ext = map(pure.split_backslash_last, self.image_urls)
preview_names = [x.split('.')[0] for x in preview_names_ext]
return self.names + preview_names

# Unique
@cached_property
@property
def names(self) -> 'list[str]':
return self._iterate_cache(lambda x: x['user']['name'])

@cached_property
@property
def profile_pic_urls(self) -> 'list[str]':
return self._iterate_cache(lambda x: x['user']['profile_image_urls']['medium'])

@lru_cache
def _iterate_cache(self, func) -> 'list[str]':
def _iterate_cache(self, func: 'fn(x: Json) -> str') -> 'list[str]':
return [func(x) for x in self.all_pages_cache[self.page_num]]

@cached_property
@property
def image_urls(self) -> 'list[str]':
return [illust['image_urls']['square_medium']
for post in self.all_pages_cache[self.page_num]
for illust in post['illusts']]


@cached_property
@property
def splitpoint(self) -> int:
"""Number of artists. The number where artists stop and previews start"""
return len(self.profile_pic_urls)
Expand Down
2 changes: 1 addition & 1 deletion koneko/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def filter_modes_allowed(modes: 'list[str]') -> 'set[str]':
return allowed_names


def filter_modes_predicate(modes: 'list[str]', allowed_names: 'set[str]') -> 'func(str) -> bool':
def filter_modes_predicate(modes: 'list[str]', allowed_names: 'set[str]') -> 'fn(str) -> bool':
"""Pure"""
if '1' in modes:
return lambda d: d.isdigit() or d in allowed_names
Expand Down
Loading

0 comments on commit df58e7e

Please sign in to comment.