├── func ├── __init__.py ├── tachiBackup_generate.cmd ├── tachiBackup.proto ├── tachiBackup_pb2.py ├── anilist_request.py ├── trim_list.py ├── getNotOnTachi.py ├── anilist_getMedia.py └── main.py ├── run.cmd ├── requirements.txt ├── .gitattributes ├── CONTRIBUTING.md ├── ISSUE.md ├── .gitignore ├── main.py ├── README.md ├── anipy.py ├── doc └── VERSION.md └── LICENSE /func/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /run.cmd: -------------------------------------------------------------------------------- 1 | python main.py -------------------------------------------------------------------------------- /func/tachiBackup_generate.cmd: -------------------------------------------------------------------------------- 1 | protoc tachiBackup.proto --python_out=./ -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.25.1 2 | python-dateutil>=2.8.1 3 | protobuf>=3.19.4 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | ## Planned Features 4 | 5 | - Import XML File and Create Anilist entries. 6 | - Import Tachiyomi backup and Create Anilist entries. 7 | - ~~Support protobuf backup of Tachiyomi.~~ v1.20 8 | - ~~Flag to separate NSFW entries.~~ v1.13 9 | - ~~Have one-liner to set flags and parse commands.~~ v1.13 10 | -------------------------------------------------------------------------------- /func/tachiBackup.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package TachiyomiBackup; 4 | 5 | message Backup { 6 | repeated BackupManga backupManga = 1; 7 | } 8 | 9 | message BackupManga { 10 | string title = 3; 11 | repeated BackupTracking tracking = 18; 12 | } 13 | 14 | message BackupTracking { 15 | int32 syncId = 1; 16 | int64 libraryId = 2; 17 | int32 mediaId = 3; 18 | string trackingUrl = 4; 19 | } -------------------------------------------------------------------------------- /ISSUE.md: -------------------------------------------------------------------------------- 1 | # Reporting Issues 2 | 3 | - Post at **Issues** tab. 4 | - Standard format: 5 | 6 | Title: 7 | ``` 8 | [Tag] Short descriptive title 9 | ``` 10 | 11 | Content: 12 | ``` 13 | Release version 14 | Python version 15 | Short Summary 16 | Error message 17 | Screenshot (if applicable) 18 | ``` 19 | 20 | ### Tags allowed: 21 | - BUG 22 | - Bugs or errors. 23 | - FEATURE REQUEST 24 | - Request new feature. 25 | - CHANGE 26 | - Behavioural change of feature. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | # *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # Environments 101 | .env 102 | .venv 103 | env/ 104 | venv/ 105 | ENV/ 106 | env.bak/ 107 | venv.bak/ 108 | 109 | # Spyder project settings 110 | .spyderproject 111 | .spyproject 112 | 113 | # Rope project settings 114 | .ropeproject 115 | 116 | # mkdocs documentation 117 | /site 118 | 119 | # mypy 120 | .mypy_cache/ 121 | .dmypy.json 122 | dmypy.json 123 | 124 | # Pyre type checker 125 | .pyre/ 126 | 127 | # Custom List 128 | ignoreFiles/ 129 | output/ 130 | anilist_config.py 131 | anilistConfig.json 132 | tachiyomi_*.json 133 | tachiyomi_*.proto 134 | tachiyomi_*.gz 135 | -------------------------------------------------------------------------------- /func/tachiBackup_pb2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by the protocol buffer compiler. DO NOT EDIT! 3 | # source: tachiBackup.proto 4 | """Generated protocol buffer code.""" 5 | from google.protobuf import descriptor as _descriptor 6 | from google.protobuf import descriptor_pool as _descriptor_pool 7 | from google.protobuf import message as _message 8 | from google.protobuf import reflection as _reflection 9 | from google.protobuf import symbol_database as _symbol_database 10 | # @@protoc_insertion_point(imports) 11 | 12 | _sym_db = _symbol_database.Default() 13 | 14 | 15 | 16 | 17 | DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11tachiBackup.proto\x12\x0fTachiyomiBackup\";\n\x06\x42\x61\x63kup\x12\x31\n\x0b\x62\x61\x63kupManga\x18\x01 \x03(\x0b\x32\x1c.TachiyomiBackup.BackupManga\"O\n\x0b\x42\x61\x63kupManga\x12\r\n\x05title\x18\x03 \x01(\t\x12\x31\n\x08tracking\x18\x12 \x03(\x0b\x32\x1f.TachiyomiBackup.BackupTracking\"Y\n\x0e\x42\x61\x63kupTracking\x12\x0e\n\x06syncId\x18\x01 \x01(\x05\x12\x11\n\tlibraryId\x18\x02 \x01(\x03\x12\x0f\n\x07mediaId\x18\x03 \x01(\x05\x12\x13\n\x0btrackingUrl\x18\x04 \x01(\tb\x06proto3') 18 | 19 | 20 | 21 | _BACKUP = DESCRIPTOR.message_types_by_name['Backup'] 22 | _BACKUPMANGA = DESCRIPTOR.message_types_by_name['BackupManga'] 23 | _BACKUPTRACKING = DESCRIPTOR.message_types_by_name['BackupTracking'] 24 | Backup = _reflection.GeneratedProtocolMessageType('Backup', (_message.Message,), { 25 | 'DESCRIPTOR' : _BACKUP, 26 | '__module__' : 'tachiBackup_pb2' 27 | # @@protoc_insertion_point(class_scope:TachiyomiBackup.Backup) 28 | }) 29 | _sym_db.RegisterMessage(Backup) 30 | 31 | BackupManga = _reflection.GeneratedProtocolMessageType('BackupManga', (_message.Message,), { 32 | 'DESCRIPTOR' : _BACKUPMANGA, 33 | '__module__' : 'tachiBackup_pb2' 34 | # @@protoc_insertion_point(class_scope:TachiyomiBackup.BackupManga) 35 | }) 36 | _sym_db.RegisterMessage(BackupManga) 37 | 38 | BackupTracking = _reflection.GeneratedProtocolMessageType('BackupTracking', (_message.Message,), { 39 | 'DESCRIPTOR' : _BACKUPTRACKING, 40 | '__module__' : 'tachiBackup_pb2' 41 | # @@protoc_insertion_point(class_scope:TachiyomiBackup.BackupTracking) 42 | }) 43 | _sym_db.RegisterMessage(BackupTracking) 44 | 45 | if _descriptor._USE_C_DESCRIPTORS == False: 46 | 47 | DESCRIPTOR._options = None 48 | _BACKUP._serialized_start=38 49 | _BACKUP._serialized_end=97 50 | _BACKUPMANGA._serialized_start=99 51 | _BACKUPMANGA._serialized_end=178 52 | _BACKUPTRACKING._serialized_start=180 53 | _BACKUPTRACKING._serialized_end=269 54 | # @@protoc_insertion_point(module_scope) 55 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # imports 2 | import os 3 | # Local Imports 4 | import func.main as fMain 5 | import func.anilist_request as fReq 6 | from func.anilist_getMedia import getMediaEntries 7 | import func.trim_list as fTrim 8 | import func.getNotOnTachi as fNotOnTachi 9 | 10 | # App Properties 11 | appVersion = '1.20' 12 | appMode = 'AniPy (Easy)' 13 | mainsrc = "App" 14 | 15 | def main(): 16 | # Declare variables 17 | fMain.logString("Define Global Vars..", mainsrc) 18 | # Paths for Files 19 | PROJECT_PATH = os.path.dirname(os.path.realpath(__file__)) #os.path.dirname(sys.executable) 20 | fMain.logString("Current path: " + PROJECT_PATH, mainsrc) 21 | anilistConfig = os.path.join(PROJECT_PATH, "anilistConfig.json") 22 | entryLog = os.path.join(PROJECT_PATH, "output", "entries.log") # Log entries 23 | # Vars for Authentication 24 | ANICLIENT = "" 25 | ANISECRET = "" 26 | useOAuth = False 27 | # User vars 28 | userAnilist = None 29 | userMal = None 30 | userID = 0 31 | isSepNsfw = False # Separate nsfw entries on output 32 | isClearFile = False 33 | # Output files dictionary 34 | outputAnime = [] 35 | outputManga = [] 36 | 37 | # Create 'output' directory 38 | if not os.path.exists('output'): 39 | os.makedirs('output') 40 | 41 | # Toggle when skipping Public mode, or Authenticated mode 42 | inputChoice = fMain.inputX("Use Authenticated mode? [y/n] (Default: 'Public List mode'): ", "n") 43 | 44 | if inputChoice.lower()[0] == "y": 45 | # Import config for Anilist OAuth 46 | fMain.logString("Importing Anilist config", mainsrc) 47 | 48 | useOAuth, ANICLIENT, ANISECRET, REDIRECT_URL = fReq.setup_config(anilistConfig) 49 | 50 | if not useOAuth: 51 | accessToken = "" 52 | 53 | if useOAuth: 54 | code = fReq.request_pubcode(ANICLIENT, REDIRECT_URL) 55 | accessToken = fReq.request_accesstkn(ANICLIENT, ANISECRET, REDIRECT_URL, code) 56 | 57 | if accessToken: 58 | useOAuth = True 59 | fMain.logString("Has access token!", mainsrc) 60 | else: 61 | useOAuth = False 62 | fMain.logString("Cannot Authenticate! Will use Public Username.", mainsrc) 63 | else: 64 | useOAuth = False 65 | 66 | # Ask for MAL username 67 | userMal = fMain.inputX("Enter your MAL Username: ", "") 68 | 69 | # Check whether authenticated, or use public Username 70 | if not useOAuth: 71 | fMain.logString("'Public Username' Mode", mainsrc) 72 | accessToken = "" 73 | while (userID < 1): 74 | # Get Anilist Username 75 | userAnilist = fMain.inputX("Enter your Anilist Username: ", "") 76 | userID = fReq.anilist_getUserID(userAnilist) 77 | else: 78 | fMain.logString("Getting User ID, from Authenticated user..", mainsrc) 79 | userID = fReq.anilist_getUserID_auth(accessToken) 80 | if userID is not None: 81 | fMain.logString("User ID: " + str(userID), mainsrc) 82 | else: 83 | fMain.logString("User Id cannot be fetched!", mainsrc) 84 | 85 | # Confirm if separating nsfw entries on generating output files 86 | inputChoice = fMain.inputX("Separate NSFW entries? [y/n] (Default: n): ", "n") 87 | if inputChoice.lower()[0] == "y": 88 | isSepNsfw = True 89 | 90 | # Clear existing output files 91 | inputChoice = fMain.inputX("Clear existing output files? [y/n] (Default: n): ", "n") 92 | if inputChoice.lower()[0] == "y": 93 | isClearFile = True 94 | 95 | # Delete prev files 96 | fMain.deleteFile(entryLog) 97 | 98 | # Initiate parameter values 99 | paramvals = { 100 | 'root': PROJECT_PATH, 101 | 'log': entryLog, 102 | 'access_tkn': accessToken, 103 | 'user_id': userID, 104 | 'user_anilist': userAnilist, 105 | 'user_mal': userMal, 106 | 'use_auth': useOAuth, 107 | 'sep_nsfw': isSepNsfw, 108 | 'clear_files': isClearFile 109 | } 110 | 111 | # Request anime list 112 | outputAnime = getMediaEntries("ANIME", paramvals) 113 | 114 | # Request manga list 115 | outputManga = getMediaEntries("MANGA", paramvals) 116 | 117 | # Trim List 118 | tempTrim = fMain.inputX("Trim list (Create list of Entries not on MAL)? [y/n] (Default: n): ", "n") 119 | 120 | if tempTrim.lower()[0] == "y": 121 | fTrim.trim_results(PROJECT_PATH, outputAnime.get('main'), outputManga.get('main'), False) 122 | if isSepNsfw: 123 | fTrim.trim_results(PROJECT_PATH, outputAnime.get('nsfw'), outputManga.get('nsfw'), True) 124 | 125 | # Get Entries not on Tachi 126 | tempTachi = fMain.inputX("Tachiyomi backup file (json, proto, gz): ", None) 127 | if tempTachi: 128 | fNotOnTachi.getNotOnTachi(outputManga.get('main'), tempTachi, False) 129 | if isSepNsfw: 130 | fNotOnTachi.getNotOnTachi(outputManga.get('nsfw'), tempTachi, True) 131 | 132 | fMain.inputX("Press to exit..", "") 133 | 134 | 135 | if __name__ == "__main__": 136 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AniPy 2 | 3 | Create local backup of anime/manga list from [Anilist.co](https://anilist.co/). 4 | 5 | ![GitHub release](https://img.shields.io/github/v/release/Jacekun/AniPy?sort=semver&style=for-the-badge) 6 | 7 | | [**View Project History**](doc/VERSION.md) | [**Contribute to AniPy**](CONTRIBUTING.md) | [**Report Issues**](ISSUE.md) | 8 | |--------------------------------------------|--------------------------------------------|-------------------------------| 9 | 10 | # Features: 11 | - Export User Anime/Manga list to JSON file. 12 | - Export User Anime/Manga list to [MyAnimeList](https://myanimelist.net/) XML export file (Can be imported to [MyAnimeList](https://myanimelist.net/import.php)). 13 | - Uses Authentication to Fetch private lists. 14 | - Compare against Tachiyomi backup, and lists all entries not on your library. 15 | - Create Tachiyomi backup file containing Anilist entries not on your library. (*Skips COMPLETED AND DROPPED*) 16 | - Separate NSFW entries. Create files with prefix **'nsfw_'**. 17 | 18 | # Limitations: 19 | - Cannot get full information from **"Re-watches / Re-reads"**. 20 | - Cannot cherry-pick entries. (*Planned feature*) 21 | 22 | # Output files: 23 | 1. **anime.json** / **manga.json** : Local backup of User [Anilist.co](https://anilist.co/). 24 | 2. **anime.xml** / **manga.xml** : [MyAnimeList](https://myanimelist.net/) XML export. Can be [imported into MAL](https://myanimelist.net/import.php). 25 | 3. **anime_NotInMal.json** / **manga_NotInMal.json** : Entries not existing on MAL. 26 | 4. **animemanga_stats.txt** : Save Entries' stats. (Average score, Watch/Read count, etc..). 27 | 5. **manga_NotInTachi.json** : Anilist manga entries not on your Tachiyomi library. 28 | 6. **manga_TachiyomiBackup.json** : Tachiyomi backup file which contains Anilist entries not on your Tachiyomi library. Import it to your Tachiyomi, and Migrate each entries from **'Anilist'** category to appropriate sources. 29 | 30 | # Requirements: 31 | - Python 3.9 32 | - 2GB RAM, or higher. 33 | - Stable internet connection. 34 | 35 | # Setup: 36 | 1. Install required packages (run Command Prompt in the same folder as '*main.py*'):
37 | ```cmd 38 | pip3 install -r requirements.txt 39 | ``` 40 | 2. Go to Anilist [**Settings** -> **Developer**](https://anilist.co/settings/developer), and click **Create client**. 41 | - Type whatever in **Name** field, and use ``https://anilist.co/api/v2/oauth/pin`` as **Redirect URL**. 42 | - Get information from created client and input them in **anilistConfig.json** (Automatically created if not existing, you need to input the credentials). 43 | - File must contain these lines. *Replace lines with appropriate values*: 44 | ```json 45 | { 46 | "aniclient": "ID", 47 | "anisecret": "Secret", 48 | "redirectUrl": "https://anilist.co/api/v2/oauth/pin" 49 | } 50 | ``` 51 | - Alternatively, you can directly run 1 of the script modes to input the credentials. 52 | 53 | # Usage: 54 | ## 'Easy' mode 55 | 1. Navigate to folder where you saved the source code. 56 | 2. Run **[main.py](main.py)**, with command: ``python main.py``. 57 | 3. Follow on-screen instructions. 58 | 59 | ## 'Advanced' mode 60 | 1. Run command using: ``python anipy.py -[parameters] --[switches]`` 61 | 62 | ### Parameters: 63 | - ``-user ""`` -> Anilist username, if using 'Public Lists Mode'. 64 | - ``-mal ""`` -> MyAnimeList username. Will export XML file if provided. 65 | - ``-tachi ""`` -> Full filepath where Tachiyomi backup file is located. 66 | 67 | ### Switches: 68 | - ``--a`` -> Use Authentication to fetch for lists. Disregards the ``-user`` parameter. 69 | - ``--t`` -> Trim lists, showing which entries are not on MAL. Also, write stats to file. 70 | - ``--n`` -> Separate NSFW entries on generating output files. Creates files with prefix **'nsfw_'**. 71 | - ``--c`` -> Clear existing output files. 72 | - ``--m`` -> Use **Anilist** as **MAL** username, if **MAL** username is not provided. 73 | 74 | ### Sample command: 75 | 1. Backup all ANIME and MANGA using Authenticated Mode: 76 | 77 | ```bash 78 | python anipy.py --a 79 | ``` 80 | 2. Backup all ANIME and MANGA using Public Mode: 81 | ```bash 82 | python anipy.py -user Jace 83 | ``` 84 | 85 | 3. Trim current list and export Tachiyomi backup: 86 | ```bash 87 | python anipy.py -tachi "D:\Tachi\backup.proto.gz" --t 88 | ``` 89 | 90 | # Scripts and Files: 91 | ## Main scripts: 92 | **[anipy.py](anipy.py)** : Advance script, with one-liner command.
93 | **[main.py](main.py)** : Easy-to-follow script.
94 | 95 | ## External scripts (Modules): 96 | **[func / main.py](func/main.py)** : Main global functions.
97 | **[func / anilist_getMedia.py](func/anilist_getMedia.py)** : Generate Anime and Manga JSON/XML files with entries from [Anilist.co](https://anilist.co/).
98 | **[func / anilist_request.py](func/anilist_request.py)** : Query Requests to [Anilist.co](https://anilist.co/).
99 | **[func / getNotOnTachi.py](func/getNotOnTachi.py)** : Generates list of Entries not in Tachiyomi library.
100 | **[func / trim_list.py](func/trim_list.py)** : Generate list of Entries not in MAL. Also gets stats.
101 | 102 | ## Miscellaneous: 103 | **[requirements.txt](requirements.txt)** : List of packages required.
104 | -------------------------------------------------------------------------------- /anipy.py: -------------------------------------------------------------------------------- 1 | # imports 2 | import os 3 | import argparse 4 | # Local Imports 5 | import func.main as fMain 6 | import func.anilist_request as fReq 7 | from func.anilist_getMedia import getMediaEntries 8 | import func.trim_list as fTrim 9 | import func.getNotOnTachi as fNotOnTachi 10 | 11 | # App Properties 12 | appVersion = '1.20' 13 | appMode = 'AniPy (Advanced)' 14 | # Declare variables 15 | fMain.logger("Define Filepaths..") 16 | # Paths for Files 17 | PROJECT_PATH = os.path.dirname(os.path.realpath(__file__)) #os.path.dirname(sys.executable) 18 | fMain.logger("Current path: " + PROJECT_PATH) 19 | # Filepaths 20 | anilistConfig = os.path.join(PROJECT_PATH, "anilistConfig.json") 21 | entryLog = os.path.join(PROJECT_PATH, "output", "entries.log") # Log entries 22 | 23 | # Create 'output' directory 24 | if not os.path.exists('output'): 25 | os.makedirs('output') 26 | 27 | parser = argparse.ArgumentParser(description='AniPy parameters and flags') 28 | 29 | # Required params 30 | # Optional params 31 | parser.add_argument('-user', type=str, help='Anilist Username') 32 | parser.add_argument('-mal', type=str, help='MAL Username') 33 | parser.add_argument('-tachi', type=str, help='Tachiyomi legacy backup') 34 | # Flags 35 | parser.add_argument('--a', action='store_true', help='Use Authenticated mode. Disregard `user` parameter.') 36 | parser.add_argument('--t', action='store_true', help='Trim generated files.') 37 | parser.add_argument('--n', action='store_true', help='Separate NSFW entries on output files.') 38 | parser.add_argument('--c', action='store_true', help='Clear existing output files.') 39 | parser.add_argument('--m', action='store_true', help='Use Anilist as MAL username, if MAL username is not provided.') 40 | 41 | # Parse args 42 | args = parser.parse_args() 43 | 44 | # Vars for Authentication 45 | ANICLIENT = "" 46 | ANISECRET = "" 47 | useOAuth = False 48 | accessToken = "" 49 | # User vars 50 | userID = 0 51 | userAnilist = None 52 | userMal = None 53 | isSepNsfw = False # Separate nsfw entries on output 54 | isClearFile = False # Clear existing output files 55 | # Output file names 56 | outputAnime = [] 57 | outputManga = [] 58 | 59 | # Check boolean flags 60 | if (args.n): # Separate NSFW Entries 61 | isSepNsfw = True 62 | if (args.c): 63 | isClearFile = True 64 | 65 | # Check parameters 66 | if args.user is not None: 67 | userAnilist = str(args.user) 68 | 69 | if args.mal is not None: 70 | userMal = str(args.mal) 71 | 72 | if not userMal or userMal.isspace(): 73 | if (args.m): 74 | if userAnilist and not userAnilist.isspace(): 75 | userMal = userAnilist 76 | 77 | if not userMal or userMal.isspace(): 78 | fMain.logger("No MAL username provided! Certain features will not work.") 79 | 80 | # Check if using authentication 81 | if (args.a): 82 | useOAuth, ANICLIENT, ANISECRET, REDIRECT_URL = fReq.setup_config(anilistConfig) 83 | 84 | if not useOAuth: 85 | accessToken = "" 86 | 87 | if useOAuth: 88 | code = fReq.request_pubcode(ANICLIENT, REDIRECT_URL) 89 | accessToken = fReq.request_accesstkn(ANICLIENT, ANISECRET, REDIRECT_URL, code) 90 | 91 | if accessToken: 92 | useOAuth = True 93 | fMain.logger("Has access token!") 94 | else: 95 | useOAuth = False 96 | fMain.logger("Cannot Authenticate! Will use Public List.") 97 | 98 | # Check whether authenticated, or use public Username 99 | if not useOAuth: 100 | fMain.logger("Fetch user ID using Anilist username..") 101 | accessToken = "" 102 | if userAnilist: 103 | userID = fReq.anilist_getUserID(userAnilist) # Fetch UserID using username. Public mode. 104 | else: 105 | fMain.logger("No Anilist username provided!") 106 | else: 107 | fMain.logger("Getting User ID, from Authenticated user..") 108 | userID = fReq.anilist_getUserID_auth(accessToken) 109 | 110 | # Default to Public mode if user ID is invalid 111 | if userID is not None: 112 | if (userID < 1): 113 | fMain.logger(f'Invalid user ID: {userID}!') 114 | else: 115 | userID = -1 116 | fMain.logger("User Id cannot be fetched!") 117 | 118 | # Display User Info 119 | if userAnilist and userID > 0: 120 | fMain.logger(f"User: {str(userAnilist)} ({str(userID)})") 121 | else: 122 | fMain.logger(f"User: {str(userAnilist)}") 123 | 124 | # Delete prev files 125 | fMain.deleteFile(entryLog) 126 | 127 | # Initiate parameter values 128 | paramvals = { 129 | 'root': PROJECT_PATH, 130 | 'log': entryLog, 131 | 'access_tkn': accessToken, 132 | 'user_anilist': userAnilist, 133 | 'user_mal': userMal, 134 | 'user_id': userID, 135 | 'use_auth': useOAuth, 136 | 'sep_nsfw': isSepNsfw, 137 | 'clear_files': isClearFile 138 | } 139 | 140 | # Request anime list 141 | outputAnime = getMediaEntries("ANIME", paramvals) 142 | 143 | # Request manga list 144 | outputManga = getMediaEntries("MANGA", paramvals) 145 | 146 | # Trim List 147 | if args.t: 148 | fTrim.trim_results(PROJECT_PATH, outputAnime.get('main'), outputManga.get('main'), False) 149 | if isSepNsfw: 150 | fTrim.trim_results(PROJECT_PATH, outputAnime.get('nsfw'), outputManga.get('nsfw'), True) 151 | 152 | # Get Entries not on Tachi 153 | tempTachi = str(args.tachi) 154 | if tempTachi: 155 | fNotOnTachi.getNotOnTachi(outputManga.get('main'), tempTachi, False) 156 | if isSepNsfw: 157 | fNotOnTachi.getNotOnTachi(outputManga.get('nsfw'), tempTachi, True) 158 | 159 | fMain.inputX("Press to exit..", "") 160 | -------------------------------------------------------------------------------- /doc/VERSION.md: -------------------------------------------------------------------------------- 1 | # v1.20 2 | ## New features: 3 | - Fully support proto backup file for Tachiyomi. 4 | 5 | ## Changes: 6 | - Updated module versions. 7 | - Add **'isAdult'** to JSON output. 8 | - Various code cleanups and optimizations. 9 | 10 | # v1.13 11 | ## New features: 12 | - **Anipy.py** script for one-liner commands. 13 | - Option to separate NSFW entries. 14 | - Add **'rewatching_ep'** to MAL Anime export. 15 | 16 | # v1.12 17 | ## Changes: 18 | - Have default value for trimming list. (Defaults to 'n'). 19 | - Clarify default mode used for authentication. 20 | - Minor code refactors. 21 | - Add 'Contributing' document 22 | 23 | # v1.11 24 | ## Fixes and Changes: 25 | - FIX: Script would save output files outside 'output' folder on non-Windows OS, ([#2](https://github.com/Jacekun/AniPy/pull/2)). Thanks to [Kortzy](https://github.com/Kortzy) 26 | 27 | # v1.1 28 | ## New features: 29 | - Added Manga re-reading status to MAL xml file. 30 | 31 | ## Fixes and Changes: 32 | - Fixed JSON not encoding ASCII properly. Fixes [Issue #1](https://github.com/Jacekun/AniPy/issues/1) 33 | - Encodes double quotes to JSON, instead of replacing it into single quote. 34 | - Changed List trimming behavior. Now asks user for explicit permission. 35 | - Changed behavior of choosing **'Public'** or **'Authenticated'** mode. The default is now **'Public mode'**. 36 | 37 | ## Dev changes: 38 | - Re-written imports. Import locally instead of thru importlib. 39 | - Dump json result as a whole, instead of appending to text file for every result. 40 | - Pro: Ensures valid json result; Properly encodes ASCII; Properly write 'escape' characters. 41 | - Cons: Uses more RAM; If an exception happens, it doesn't write anything. 42 | - Combined **'anilist_getAnime'** and **'anilist_getManga'** scripts into one: **'anilist_getMedia'**. 43 | - Log imports from **'func'** subfolder. 44 | - Dropped all GUI supports. AniPy is now fully dedicated as an CLI tool. 45 | - Removed unused *imports* from scripts and *packages* from **'requirements.txt'**. 46 | 47 | # v1.08 48 | ## Fixes and Changes: 49 | - Clarify that only Legacy version backup of Tachiyomi is accepted. 50 | - Create **'anilistConfig.json'** file, if it does not exist. Needs to enter client Id and secret. 51 | - Use same format as logging when accepting inputs from user. 52 | 53 | # v1.07 54 | ## New features: 55 | - Create 'output' folder when not existing. 56 | - [WIP] New UI for the script, built using PySide6 and QtDesigner. 57 | - **Note: Currently, only 'Simple Mode' is working. 'Advance Mode' is still WIP.** 58 | 59 | ## Fixes and Changes: 60 | - Fix: Only use Tachiyomi compare script when file is not None/null. 61 | - Refactored code for better flow and execution. 62 | - Load anilist config, only when its the mode used. 63 | - Renamed **'packages.txt'** to **'requirements.txt'** following Github standard. 64 | - Correct some log messages. 65 | - Removed unused variables. 66 | - Removed download count from this file. 67 | 68 | # v1.06 69 | **This lists all changes after the last Executable update**
70 | ## New features: 71 | - Use Authentication to fetch private lists from user. 72 | - Compare list to Tachiyomi library backup and generate json file to be imported to Tachiyomi. 73 | - Use **Press key to Exit..** upon process done. 74 | - Count entries from Anilist not in MyAnimeList and export to **'animemanga_stats.txt'**. 75 | - Count total entries and export to **'animemanga_stats.txt'**. 76 | - Toggle use of Authenticated lists and Public list. 77 | 78 | ## Changes: 79 | - Use JSON file: **'anilistConfig.json'** to store Anilist config. 80 | - Append *current date* to the output filenames. 81 | - All output filepaths are declared inside their own modules, instead of inside **'main.py'**. 82 | - Pass global path to modules. 83 | - Delete previous **'entries.log'**, every run. 84 | - Updated **'packages.txt'** to match required *imports*. 85 | - Round Average score stat to 2 decimal places. 86 | - Updated logger format. 87 | - Added additional log info. 88 | - Code cleanups. 89 | **** 90 | 91 | # v1.2.0.3 - Improvements 92 | **New:** 93 | - Handles "Rewatching / Rereading", saves it as "Watching / Reading". 94 | - Moved all **'output files'**, from *'root directory'* to *'root/output'* subfolder. 95 | - Added "Rereading" Manga to MAL Manga XML file. 96 | - Added script to get Entries which does not exist on MAL. (*Output File:* **anime_NotInMal.json / manga_NotInMal.json**). 97 | - Get **'Average Score'** and **'Anime/Manga count for Each status'**. (*Output File:* **'animemanga_stats.txt'**). 98 | 99 | **Inside the Code:** 100 | - Moved code getting anime / manga entries, to separate modules. (*File:* **'func/anilist_getAnime.py', 'func/anilist_getManga.py'**) 101 | - Script file for Generating lists of Entries not in MAL. Also, gets stats. (*File:* **'func/trim_list.py'**). 102 | - Convert 'response.content' on 'anilist_request.py' to string, for proper error-logging. 103 | - Validated **'synonyms'**. If result is **"[]"**, return *empty string*. 104 | - Renamed module script: **'func.py'** to **'main.py'**. 105 | - Code cleanups. 106 | 107 | **Console-only changes:** 108 | - Ask for username, until a valid one is provided. 109 | - Changed **build.cmd**, to include files during **'executable'** build. 110 | - Added **'main_win.spec'**, to provide options during **'executable'** build. 111 | **** 112 | 113 | # v1.1.0.0 - Re-write 114 | **Fixes:** 115 | - Removed duplicate entries from List. 116 | 117 | **Inside the Code:** 118 | - Rewritten the Code, making the functions outside of the Main script. 119 | - Added Logger function, with Current Time. 120 | **** 121 | 122 | # v1.0.0.0 - First Version 123 | **Features:** 124 | - Export User Anime/Manga list to JSON file. 125 | - Export User Anime/Manga list to [MAL](https://myanimelist.net/) Xml export file (Can be imported to [MyAnimeList](https://myanimelist.net/import.php)). 126 | - Graphical User Interface, for easy use. -------------------------------------------------------------------------------- /func/anilist_request.py: -------------------------------------------------------------------------------- 1 | # Imports 2 | import os 3 | import json 4 | import requests 5 | import webbrowser 6 | # Local import 7 | from func.main import logString as logMain 8 | from func.main import inputX as inputX 9 | 10 | # Anilist API URL 11 | AnilistURL = 'https://graphql.anilist.co' 12 | 13 | logMain("Imported func.anilist_request", "") 14 | 15 | # Logger 16 | def logger(text): 17 | logMain(text, "anilist_request") 18 | 19 | # Return media query string 20 | def queryMedia(): 21 | query = ''' 22 | query ($userID: Int, $MEDIA: MediaType) { 23 | MediaListCollection (userId: $userID, type: $MEDIA) { 24 | lists { 25 | status 26 | entries 27 | { 28 | status 29 | completedAt { year month day } 30 | startedAt { year month day } 31 | progress 32 | progressVolumes 33 | score(format: POINT_10) 34 | notes 35 | private 36 | media 37 | { 38 | id 39 | idMal 40 | season 41 | seasonYear 42 | format 43 | source 44 | episodes 45 | chapters 46 | volumes 47 | title 48 | { 49 | english 50 | romaji 51 | } 52 | description 53 | coverImage { medium } 54 | synonyms 55 | isAdult 56 | } 57 | } 58 | } 59 | } 60 | } 61 | ''' 62 | return query 63 | 64 | # Return json query for user ID 65 | def queryUser(userName): 66 | queryUser = "query ($userName: String) { User (search: $userName) { id } }" 67 | varUser = { 'userName': "'" + userName + "'" } 68 | json={'query': queryUser, 'variables': varUser} 69 | return json 70 | 71 | # Return User ID, from Username 72 | def anilist_getUserID(userName): 73 | logger("Getting User ID from Anilist..") 74 | try: 75 | response = requests.post(AnilistURL, json=queryUser(userName)) 76 | except: 77 | logger("Internet error! Check your connection.") 78 | return -1 79 | 80 | # If successful, get User ID from Username 81 | if (response.status_code == 200): 82 | jsonParsed = json.loads(response.content) 83 | userID = jsonParsed["data"]["User"]["id"] 84 | logger("User ID: " + str(userID)) 85 | return userID 86 | else: 87 | logger("Cannot get User ID!") 88 | logger(str(response.content)) 89 | return 0 90 | 91 | # Return User ID, from Access Token 92 | def anilist_getUserID_auth(accessToken): 93 | try: 94 | resultUserID = requests.post("https://graphql.anilist.co", headers={"Authorization": f"Bearer {accessToken}"}, json={"query": "{Viewer{id}}"}).json() 95 | userID = resultUserID["data"]["Viewer"]["id"] 96 | return userID 97 | except: 98 | return None 99 | 100 | # Request user media list, returns JSON Object (Authenticated with token) 101 | def anilist_userlist(accessToken, userID, MEDIA = "ANIME"): 102 | logger("Getting " + MEDIA + " from Anilist..") 103 | varQuery = { 'userID': str(userID), 'MEDIA' : MEDIA } 104 | response = requests.post(AnilistURL, json={'query': queryMedia(), 'variables': varQuery}, headers={"Authorization": f"Bearer {accessToken}"}) 105 | if (response.status_code == 200): 106 | jsonParsed = json.loads(response.content) 107 | logger(MEDIA + " request success! Returned JSON object..") 108 | return jsonParsed 109 | else: 110 | logger(MEDIA + " Request Error! [Status code: " + str(response.status_code) + "]") 111 | logger(response.content) 112 | return None 113 | 114 | # Request user media list, returns JSON Object (Public List) 115 | def anilist_userlist_public(userID, MEDIA = "ANIME"): 116 | logger("Getting " + MEDIA + " from Anilist..") 117 | varQuery = { 'userID': str(userID), 'MEDIA' : MEDIA } 118 | response = requests.post(AnilistURL, json={'query': queryMedia(), 'variables': varQuery}) 119 | if (response.status_code == 200): 120 | jsonParsed = json.loads(response.content) 121 | logger(MEDIA + " request success! Returned JSON object..") 122 | return jsonParsed 123 | else: 124 | logger(MEDIA + " Request Error! [Status code: " + str(response.status_code) + "]") 125 | logger(response.content) 126 | return None 127 | 128 | # Request public code 129 | def request_pubcode(ANICLIENT, REDIRECT_URL): 130 | # Get OAuth and Access Token 131 | logger("Login Anilist on browser, and Authorize AniPy") 132 | url = f"https://anilist.co/api/v2/oauth/authorize?client_id={ANICLIENT}&redirect_uri={REDIRECT_URL}&response_type=code" 133 | webbrowser.open(url) 134 | 135 | code = inputX("Paste your token code here (Copied from Anilist webpage result): ", "") 136 | return code 137 | 138 | # Request access token, using code 139 | def request_accesstkn(ANICLIENT, ANISECRET, REDIRECT_URL, code): 140 | body = { 141 | 'grant_type': 'authorization_code', 142 | 'client_id': ANICLIENT, 143 | 'client_secret': ANISECRET, 144 | 'redirect_uri': REDIRECT_URL, 145 | 'code': code 146 | } 147 | try: 148 | accessToken = requests.post("https://anilist.co/api/v2/oauth/token", json=body).json().get("access_token") 149 | #logger("Access Token: [" + accessToken + "]") 150 | except: 151 | accessToken = None 152 | return accessToken 153 | 154 | # Setup Anilist config 155 | def setup_config(anilistConfig): 156 | ANICLIENT = "" 157 | ANISECRET = "" 158 | REDIRECT_URL = "" 159 | useOAuth = False 160 | 161 | if not os.path.exists(anilistConfig): 162 | while not ANICLIENT: 163 | ANICLIENT = inputX("Enter your Client ID: ", None) 164 | while not ANISECRET: 165 | ANISECRET = inputX("Enter your Client Secret: ", None) 166 | 167 | anilistConfigJson = { 168 | "aniclient" : ANICLIENT, 169 | "anisecret" : ANISECRET, 170 | "redirectUrl" : "https://anilist.co/api/v2/oauth/pin" 171 | } 172 | 173 | with open(anilistConfig, "w+", encoding='utf-8') as F: 174 | F.write(json.dumps(anilistConfigJson, ensure_ascii=False, indent=4).encode('utf8').decode()) 175 | 176 | try: 177 | with open(anilistConfig) as f: 178 | configData = json.load(f) 179 | ANICLIENT = configData['aniclient'] 180 | ANISECRET = configData['anisecret'] 181 | REDIRECT_URL = configData['redirectUrl'] 182 | # fMain.logger("\nClient: " + ANICLIENT + "\nSecret: " + ANISECRET) 183 | useOAuth = True 184 | except: 185 | logger(f"There's no correct {anilistConfig} file!") 186 | useOAuth = False 187 | 188 | return useOAuth, ANICLIENT, ANISECRET, REDIRECT_URL 189 | -------------------------------------------------------------------------------- /func/trim_list.py: -------------------------------------------------------------------------------- 1 | # Remove Entries that have MAL ID 2 | # And additional code to get stats 3 | # imports 4 | import os 5 | import json 6 | # Local imports 7 | import func.main as fMain 8 | 9 | # Other vars 10 | logSrc = "trim_list" 11 | fMain.logString("Imported func.trim_list", "") 12 | 13 | # Functions 14 | def sort_byval(json): 15 | try: 16 | return str(json['format']) 17 | except KeyError: 18 | return "" 19 | 20 | def trim_results(filepath, inputAnime, inputManga, isNsfw): 21 | # Declare filepaths 22 | if isNsfw: 23 | outputStats = os.path.join(filepath, "output", f'nsfw_animemanga_stats.txt') 24 | else: 25 | outputStats = os.path.join(filepath, "output", f'animemanga_stats.txt') 26 | 27 | outputAnime = f'{inputAnime[:-5]}_NotInMAL.json' 28 | outputManga = f'{inputManga[:-5]}_NotInMAL.json' 29 | # STATS variables 30 | statScoreTotal = 0 31 | statScoreCount = 0 32 | statInMAL = 0 33 | # Count entries 34 | cTotal = 0 35 | cCurrent = 0 36 | cComplete = 0 37 | cHold = 0 38 | cDrop = 0 39 | cPlan = 0 40 | 41 | # Delete prev files 42 | fMain.deleteFile(outputStats) 43 | 44 | # Load JSON objects 45 | # Check if anime file Exists! 46 | if not (os.path.exists(inputAnime)): 47 | fMain.logString("Anime json file does not exists!", logSrc) 48 | jsonAnime = None 49 | else: 50 | fMain.logString("Loading " + os.path.basename(inputAnime) + " into memory..", logSrc) 51 | with open(inputAnime, "r+", encoding='utf-8') as F: 52 | jsonAnime = json.load(F) 53 | jsonAnime.sort(key=sort_byval, reverse=True) 54 | fMain.logString("Anime json file loaded!", logSrc) 55 | # Check if manga file Exists! 56 | if not (os.path.exists(inputManga)): 57 | fMain.logString("Manga json file does not exists!", logSrc) 58 | jsonManga = None 59 | else: 60 | fMain.logString("Loading " + os.path.basename(inputManga) + " into memory..", logSrc) 61 | with open(inputManga, "r+", encoding='utf-8') as F: 62 | jsonManga = json.load(F) 63 | jsonManga.sort(key=sort_byval, reverse=True) 64 | fMain.logString("Manga json file loaded!", logSrc) 65 | 66 | # json Objects 67 | jsonOutputAnime = [] 68 | jsonOutputManga = [] 69 | 70 | # Get entries from Anime, not in MAL 71 | if jsonAnime is not None: 72 | fMain.logString("Checking anime list..", logSrc) 73 | for entry in jsonAnime: 74 | # Get each entry 75 | if (entry["idMal"] < 1): 76 | # If not in MAL, ID = 0 77 | statInMAL += 1 78 | jsonData = {} 79 | jsonData["idAnilist"] = entry["idAnilist"] 80 | jsonData["titleEnglish"] = entry["titleEnglish"] 81 | jsonData["titleRomaji"] = entry["titleRomaji"] 82 | if str(entry["synonyms"]) == "[]": 83 | jsonData["synonyms"] = "" 84 | else: 85 | jsonData["synonyms"] = entry["synonyms"] 86 | jsonData["format"] = entry["format"] 87 | jsonData["source"] = entry["source"] 88 | jsonData["status"] = entry["status"] 89 | jsonData["startedAt"] = entry["startedAt"] 90 | jsonData["completedAt"] = entry["completedAt"] 91 | jsonData["progress"] = entry["progress"] 92 | jsonData["totalEpisodes"] = entry["totalEpisodes"] 93 | jsonData["score"] = entry["score"] 94 | jsonData["notes"] = entry["notes"] 95 | # Append to JSON object 96 | jsonOutputAnime.append(jsonData) 97 | 98 | # Stats checker 99 | statScore = int(entry["score"]) 100 | if (statScore > 0): 101 | statScoreTotal = statScoreTotal + statScore 102 | statScoreCount = statScoreCount + 1 103 | 104 | # Count entries 105 | AnilistStatus = str(entry["status"]) 106 | if (AnilistStatus == "COMPLETED"): 107 | cComplete = cComplete + 1 108 | elif (AnilistStatus == "PAUSED"): 109 | cHold = cHold + 1 110 | elif (AnilistStatus == "CURRENT"): 111 | cCurrent = cCurrent + 1 112 | elif (AnilistStatus == "DROPPED"): 113 | cDrop = cDrop + 1 114 | elif (AnilistStatus == "PLANNING"): 115 | cPlan = cPlan + 1 116 | elif (AnilistStatus == "REPEATING"): 117 | cCurrent = cCurrent + 1 118 | 119 | # Write 'outputAnime' 120 | if jsonOutputAnime: 121 | fMain.createJsonFile(outputAnime, jsonOutputAnime, logSrc) 122 | 123 | # Write stats for Anime 124 | cTotal = cComplete + cCurrent + cHold + cPlan + cDrop 125 | fMain.logString("Appending to file (Average Score stats): " + os.path.basename(outputStats), logSrc) 126 | averageScore = "{:.2f}".format(statScoreTotal/statScoreCount * 10) 127 | fMain.write_append(outputStats, "Anime stats:\nAverage Score (out of 100): " + averageScore + "\n") 128 | fMain.write_append(outputStats, "Count:\nCompleted: " + str(cComplete) + "\nCurrently Watching: " + str(cCurrent) + "\nPaused: " + str(cHold) + "\nPlanning: " + str(cPlan) + "\nDropped: " + str(cDrop) + "\n") 129 | fMain.write_append(outputStats, "\nTotal: " + str(cTotal)) 130 | fMain.write_append(outputStats, "\nAnime Not in MAL: " + str(statInMAL) + "\n") 131 | 132 | # Add Line Break 133 | fMain.write_append(outputStats, "=========================================\n") 134 | # Reset vars 135 | statScoreTotal = 0 136 | statScoreCount = 0 137 | statInMAL = 0 138 | # Reset count 139 | cTotal = 0 140 | cCurrent = 0 141 | cComplete = 0 142 | cHold = 0 143 | cDrop = 0 144 | cPlan = 0 145 | 146 | # For MANGA 147 | # Get entries from MANGA, not in MAL 148 | if jsonManga is not None: 149 | fMain.logString("Checking manga list..", logSrc) 150 | for entry in jsonManga: 151 | # Get each entry 152 | if (entry["idMal"] < 1): 153 | # If not in MAL, ID = 0 154 | statInMAL += 1 155 | jsonData = {} 156 | jsonData["idAnilist"] = entry["idAnilist"] 157 | jsonData["titleEnglish"] = entry["titleEnglish"] 158 | jsonData["titleRomaji"] = entry["titleRomaji"] 159 | if str(entry["synonyms"]) == "[]": 160 | jsonData["synonyms"] = "" 161 | else: 162 | jsonData["synonyms"] = entry["synonyms"] 163 | jsonData["format"] = entry["format"] 164 | jsonData["source"] = entry["source"] 165 | jsonData["status"] = entry["status"] 166 | jsonData["startedAt"] = entry["startedAt"] 167 | jsonData["completedAt"] = entry["completedAt"] 168 | jsonData["progress"] = entry["progress"] 169 | jsonData["progressVolumes"] = entry["progressVolumes"] 170 | jsonData["totalChapters"] = entry["totalChapters"] 171 | jsonData["totalVol"] = entry["totalVol"] 172 | jsonData["score"] = entry["score"] 173 | jsonData["notes"] = entry["notes"] 174 | # Append to JSON object 175 | jsonOutputManga.append(jsonData) 176 | 177 | # Stats checker 178 | statScore = int(entry["score"]) 179 | if (statScore > 0): 180 | statScoreTotal = statScoreTotal + statScore 181 | statScoreCount = statScoreCount + 1 182 | 183 | # Count entries 184 | AnilistStatus = str(entry["status"]) 185 | if (AnilistStatus == "COMPLETED"): 186 | cComplete = cComplete + 1 187 | elif (AnilistStatus == "PAUSED"): 188 | cHold = cHold + 1 189 | elif (AnilistStatus == "CURRENT"): 190 | cCurrent = cCurrent + 1 191 | elif (AnilistStatus == "DROPPED"): 192 | cDrop = cDrop + 1 193 | elif (AnilistStatus == "PLANNING"): 194 | cPlan = cPlan + 1 195 | elif (AnilistStatus == "REPEATING"): 196 | cCurrent = cCurrent + 1 197 | 198 | # Write 'outputManga' 199 | if jsonOutputManga: 200 | fMain.createJsonFile(outputManga, jsonOutputManga, logSrc) 201 | 202 | # Write stats for Manga 203 | cTotal = cComplete + cCurrent + cHold + cPlan + cDrop 204 | fMain.logString("Appending to file (Average Score stats): " + os.path.basename(outputStats), logSrc) 205 | averageScore = "{:.2f}".format(statScoreTotal/statScoreCount * 10) 206 | fMain.write_append(outputStats, "Manga stats:\nAverage Score (out of 100): " + averageScore + "\n") 207 | fMain.write_append(outputStats, "Count:\nCompleted: " + str(cComplete) + "\nCurrently Reading: " + str(cCurrent) + "\nPaused: " + str(cHold) + "\nPlanning: " + str(cPlan) + "\nDropped: " + str(cDrop) + "\n") 208 | fMain.write_append(outputStats, "\nTotal: " + str(cTotal)) 209 | fMain.write_append(outputStats, "\nManga Not in MAL: " + str(statInMAL) + "\n") 210 | -------------------------------------------------------------------------------- /func/getNotOnTachi.py: -------------------------------------------------------------------------------- 1 | # Get entries in Anilist, not on your Tachiyomi library 2 | # imports 3 | import os 4 | import json 5 | from google import protobuf 6 | from google.protobuf import text_format 7 | from google.protobuf.json_format import ParseDict 8 | # Local import 9 | import func.main as fMain 10 | from func import tachiBackup_pb2 as tachiBackupProto 11 | 12 | fMain.logString("Imported func.getNotOnTachi", "") 13 | 14 | # Functions 15 | def logString(text): 16 | fMain.logString(text, "getNotOnTachi") 17 | 18 | def sort_byval(json): 19 | try: 20 | return str(json['format']) 21 | except KeyError: 22 | return "" 23 | 24 | # Open json tachiyomi backup file, and load all Anilist-tracked entries 25 | def parseLegacyBackup(inputMangaPath: str) -> list: 26 | listReturn = [] 27 | loadTachi = None 28 | logString("Loading legacy backup '" + os.path.basename(inputMangaPath) + "' into memory..") 29 | with open(inputMangaPath, "r+", encoding='utf-8') as F: 30 | loadTachi = json.load(F) 31 | logString("Tachi library json file loaded!") 32 | 33 | # Get entries from Tachiyomi json (legacy backup), and turn into simple list 34 | if loadTachi is not None: 35 | logString("Checking Tachiyomi library..") 36 | for tachiEntry in loadTachi["mangas"]: 37 | try: 38 | tempTracker = tachiEntry["track"] 39 | if tempTracker is not None: 40 | for tachiTrack in tempTracker: 41 | tempTrackLink = str(tachiTrack["u"]) 42 | if "anilist" in tempTrackLink: 43 | # logString("Id: [" + tempTrackLink[25:] + "]") 44 | # listReturn.append(tempTrackLink[25:]) 45 | listReturn.append(str(tachiTrack["r"])) 46 | except: 47 | # logString("No tracking!") 48 | pass 49 | return listReturn 50 | 51 | # Open proto tachiyomi backup file, and load all Anilist-tracked entries 52 | def parseProtoBackup(inputMangaPath: str) -> list: 53 | listReturn = [] 54 | #logString("Loading backup: " + inputMangaPath) 55 | logString("Loading backup '" + os.path.basename(inputMangaPath) + "' into memory..") 56 | _backupManga = None 57 | try: 58 | with open(inputMangaPath, "rb") as f: 59 | logString("Initiating backup..") 60 | _backupManga = tachiBackupProto.Backup() 61 | logString("Parsing backup..") 62 | _backupManga.ParseFromString(f.read()) 63 | 64 | if _backupManga is not None: 65 | logString("Backup file has contents!") 66 | _backupMangaList = _backupManga.backupManga 67 | logString("Accessed Backup root!") 68 | if _backupMangaList is not None: 69 | logString("Backup file has manga list!") 70 | for _entry in _backupMangaList: 71 | if _entry is not None: 72 | #logString("Parsing: " + _entry.title) 73 | _trackers = _entry.tracking 74 | if _trackers: 75 | for _track in _trackers: 76 | if _track is not None: 77 | if str(_track.syncId) == "2": 78 | listReturn.append(str(_track.mediaId)) 79 | break 80 | except Exception as e: 81 | logString("Exception on reading backup!") 82 | print(e) 83 | return listReturn 84 | 85 | # Function called on main script 86 | def getNotOnTachi(inputManga: str, inputTachi: str, isNsfw: bool): 87 | # Vars 88 | logSrc = "getNotOnTachi" 89 | listTachiTracked = [] 90 | listSkippedStatus = [ "COMPLETED", "DROPPED" ] 91 | 92 | # Declare filepaths 93 | inputMangaFileName: str = inputManga[:-5] 94 | outputSuffix: str = "_nsfw" if isNsfw else "" 95 | outputManga: str = f'{inputMangaFileName}_NotInTachi{outputSuffix}.json' 96 | outputTachiBackup: str = f'{inputMangaFileName}_TachiyomiBackup{outputSuffix}.json' 97 | outputProtoBackup: str = f'{inputMangaFileName}_TachiyomiBackup{outputSuffix}.proto' 98 | 99 | # Delete previous file 100 | fMain.deleteFile(outputManga) 101 | 102 | # json Objects 103 | jsonOutputManga = [] 104 | tachiBackupJson = { 105 | "version": 2, 106 | "mangas": [], 107 | "categories": [ 108 | [ "Anilist", 0 ] 109 | ] 110 | } 111 | protoBackupManga = { 112 | "backupManga": [] 113 | } 114 | 115 | # Load Tachiyomi Library 116 | if not (os.path.exists(inputTachi)): 117 | logString("Tachiyomi library does not exists!") 118 | else: 119 | if inputTachi[-4:] == "json": 120 | listTachiTracked = parseLegacyBackup(inputTachi) 121 | elif inputTachi[-5:] == "proto": 122 | listTachiTracked = parseProtoBackup(inputTachi) 123 | elif inputTachi[-2:] == "gz": 124 | extracted = fMain.extractGz(inputTachi) 125 | listTachiTracked = parseProtoBackup(extracted) 126 | else: 127 | logString("Unrecognized Tachiyomi backup file! Make sure you use Tachiyomi-generate file.") 128 | 129 | # Skip if tachi backup has no tracked entries 130 | if not listTachiTracked: 131 | logString("No tracked Manga on Tachiyomi backup file!") 132 | # Else, continue 133 | else: 134 | # Load Anilist MANGA 135 | if not (os.path.exists(inputManga)): 136 | logString("Manga data file does not exists!") 137 | jsonManga = None 138 | else: 139 | logString("Loading " + os.path.basename(inputManga) + " into memory..") 140 | with open(inputManga, "r+", encoding='utf-8') as F: 141 | jsonManga = json.load(F) 142 | jsonManga.sort(key=sort_byval, reverse=True) 143 | logString("Manga JSON File loaded!") 144 | # Get entries from Anilist Manga, and dispose entries already on Tachi tracked lib 145 | if jsonManga is not None: 146 | logString("Checking Anilist manga entries..") 147 | for entry in jsonManga: 148 | # Iterate every manga entry, and check if its already tracked on provided Tachiyomi backup file. 149 | idAnilist: str = str(entry["idAnilist"]) 150 | if idAnilist not in listTachiTracked: 151 | # If entry should be included, or skipped. 152 | if str(entry["status"]) not in listSkippedStatus: 153 | # Disregard NOVEL entries. 154 | if str(entry["format"]) != "NOVEL": 155 | # Create JSON object 156 | jsonData = {} 157 | jsonData["idAnilist"] = entry["idAnilist"] 158 | jsonData["titleEnglish"] = entry["titleEnglish"] 159 | jsonData["titleRomaji"] = entry["titleRomaji"] 160 | if str(entry["synonyms"]) == "[]": 161 | jsonData["synonyms"] = "" 162 | else: 163 | jsonData["synonyms"] = entry["synonyms"] 164 | jsonData["status"] = entry["status"] 165 | 166 | # Append to JSON object 167 | jsonOutputManga.append(jsonData) # add to json list of manga_NotInTachi 168 | 169 | # Add to Tachiyomi backup json 170 | titleEntry = "" 171 | if jsonData["titleEnglish"] is not None: 172 | titleEntry = str(jsonData["titleEnglish"]) 173 | if titleEntry == "": 174 | if jsonData["titleRomaji"] is not None: 175 | titleEntry = str(jsonData["titleRomaji"]) 176 | 177 | TachiBackupEntry = { 178 | "manga": [ 179 | titleEntry, 180 | titleEntry, 181 | 0, 182 | 0, 183 | 0 184 | ], 185 | "categories": [ 186 | "Anilist" 187 | ] 188 | } 189 | tachiBackupJson["mangas"].append(TachiBackupEntry) 190 | 191 | # Add to Proto backup file 192 | protoDataTrack = { 193 | "syncId": 2, 194 | "mediaId": int(idAnilist), 195 | "trackingUrl": "https://anilist.co/manga/" + idAnilist 196 | } 197 | protoDataManga = { 198 | "title" : titleEntry, 199 | "tracking": [ 200 | protoDataTrack 201 | ] 202 | } 203 | protoBackupManga["backupManga"].append(protoDataManga) 204 | 205 | # Write 'outputManga': manga_NotInTachi 206 | fMain.createJsonFile(outputManga, jsonOutputManga, logSrc) 207 | # Write 'tachiBackupJson' to file: __TachiyomiBackup.json 208 | fMain.createJsonFile(outputTachiBackup, tachiBackupJson, logSrc) 209 | 210 | # Write proto backup file 211 | try: 212 | logString("Generating proto backup file..") 213 | protoBackupMessage = ParseDict(protoBackupManga, tachiBackupProto.Backup()) 214 | with open(outputProtoBackup, "w") as F: 215 | text_format.PrintMessage(protoBackupMessage, F) 216 | logString(f'File generated: {outputProtoBackup}') 217 | outputProtoBackupGz = fMain.compressGz(outputProtoBackup) 218 | logString(f'File compressed: {outputProtoBackupGz}') 219 | except: 220 | logString(f"Cannot write proto file: {outputProtoBackup}") 221 | 222 | logString("Done Tachiyomi parsing functions.") -------------------------------------------------------------------------------- /func/anilist_getMedia.py: -------------------------------------------------------------------------------- 1 | # Imports 2 | import os 3 | from datetime import datetime 4 | import array as arr 5 | # Local Imports 6 | import func.main as fMain 7 | import func.anilist_request as fReq 8 | 9 | fMain.logString("Imported func.anilist_getMedia", "") 10 | 11 | # Main Function 12 | def getMediaEntries(mediaType, paramvals): 13 | # Vars and Objects 14 | userMal = None 15 | filepath = str(paramvals['root']) 16 | entryLog = str(paramvals['log']) 17 | accessToken = str(paramvals['access_tkn']) 18 | userID = int(paramvals['user_id']) 19 | useOAuth = bool(paramvals['use_auth']) 20 | isSepNsfw = bool(paramvals['sep_nsfw']) 21 | isClearFile = bool(paramvals['clear_files']) 22 | if paramvals['user_mal']: 23 | userMal = str(paramvals['user_mal']) 24 | 25 | returnMedia = {} 26 | entryID = [] # List of IDs, to prevent duplicates 27 | jsonToDump = [] # List of Json dict object of results 28 | jsonToDumpNsfw = [] # List of Json dict object of results, 18+ entries 29 | isAdult = False # Bool for 'isAdult' flag from Anilist 30 | isExportMal = True # Export to MAL backup. 31 | nsfwToggle = 0 # 0=main, 1=nsfw. For arrays toggle 32 | source = "anilist_get" + mediaType 33 | fMain.logString("All vars are initiated", source) 34 | 35 | if not userMal: 36 | isExportMal = False 37 | fMain.logString("Skipping MAL export.", source) 38 | else: 39 | fMain.logString(f"MAL Username: {userMal}", source) 40 | 41 | # Declare filepaths 42 | if mediaType == "ANIME": 43 | outputMedia = os.path.join(filepath, "output", "anime_" + datetime.now().strftime("%Y-%m-%d") + ".json") 44 | xmlMedia = os.path.join(filepath, "output", "anime_" + datetime.now().strftime("%Y-%m-%d") + ".xml") 45 | outputMedia18 = os.path.join(filepath, "output", "nsfw_anime_" + datetime.now().strftime("%Y-%m-%d") + ".json") 46 | xmlMedia18 = os.path.join(filepath, "output", "nsfw_anime_" + datetime.now().strftime("%Y-%m-%d") + ".xml") 47 | else: 48 | outputMedia = os.path.join(filepath, "output", "manga_" + datetime.now().strftime("%Y-%m-%d") + ".json") 49 | xmlMedia = os.path.join(filepath, "output", "manga_" + datetime.now().strftime("%Y-%m-%d") + ".xml") 50 | outputMedia18 = os.path.join(filepath, "output", "nsfw_manga_" + datetime.now().strftime("%Y-%m-%d") + ".json") 51 | xmlMedia18 = os.path.join(filepath, "output", "nsfw_manga_" + datetime.now().strftime("%Y-%m-%d") + ".xml") 52 | 53 | # Clear files if already existing 54 | fMain.logString(f"Will clear output files: {isClearFile}") 55 | if isClearFile: 56 | try: 57 | fMain.logString("Deleting output files..") 58 | fMain.deleteFile(outputMedia) 59 | fMain.deleteFile(xmlMedia) 60 | fMain.deleteFile(outputMedia18) 61 | fMain.deleteFile(xmlMedia18) 62 | fMain.logString("Done deleting output files!") 63 | except Exception as e: 64 | fMain.logString(f"Clear File error: {e}", source) 65 | 66 | # Check if not existing 67 | if not (os.path.exists(outputMedia)): 68 | # Get JSON object 69 | if useOAuth: 70 | jsonMedia = fReq.anilist_userlist(accessToken, userID, mediaType) 71 | else: 72 | jsonMedia = fReq.anilist_userlist_public(userID, mediaType) 73 | 74 | # Check if not null 75 | if jsonMedia is not None: 76 | listMedia = jsonMedia["data"]["MediaListCollection"]["lists"] 77 | 78 | # Create vars 79 | # Count Manga entries 80 | cTotal = arr.array('i', [0, 0]) 81 | cWatch = arr.array('i', [0, 0]) 82 | cComplete = arr.array('i', [0, 0]) 83 | cHold = arr.array('i', [0, 0]) 84 | cDrop = arr.array('i', [0, 0]) 85 | cPtw = arr.array('i', [0, 0]) 86 | 87 | # Start generating JSON and XML.. 88 | fMain.logString("Generating export files..", source) 89 | 90 | # Log duplicate entries 91 | fMain.logFile(entryLog, f'{mediaType} Entries') 92 | entryID.clear() # Clear list 93 | 94 | # Iterate over the MediaCollection List 95 | for anime in listMedia: 96 | # Get entries 97 | animeInfo = anime["entries"] 98 | # Iterate over the anime information, inside the entries 99 | for entry in animeInfo: 100 | # Get Anilist ID 101 | anilistID = entry["media"]["id"] 102 | # Get Anilist Status 103 | AnilistStatus = fMain.validateStr(entry["status"]) 104 | # Get isAdult flag 105 | isAdult = bool(entry["media"]["isAdult"]) 106 | 107 | # Check if already exists 108 | if anilistID in entryID: 109 | fMain.logFile(entryLog, f'Skipped: {str(anilistID)}, Duplicate {mediaType} entry.') 110 | continue 111 | else: 112 | entryID.append(anilistID) 113 | 114 | # Write to json file 115 | if isAdult and isSepNsfw: 116 | jsonToDumpNsfw.append(fMain.entry_json(entry, mediaType)) 117 | else: 118 | jsonToDump.append(fMain.entry_json(entry, mediaType)) 119 | 120 | # Write to MAL Xml File 121 | malID = fMain.validateInt(entry["media"]["idMal"]) 122 | if malID != '0' and isExportMal: 123 | # Get XML strings 124 | xmltoWrite = fMain.entry_xmlstr(mediaType, malID, entry, str(AnilistStatus)) 125 | # Write to xml file 126 | if isAdult and isSepNsfw: 127 | nsfwToggle = 1 128 | fMain.write_append(xmlMedia18, xmltoWrite) 129 | else: 130 | nsfwToggle = 0 131 | fMain.write_append(xmlMedia, xmltoWrite) 132 | 133 | # Add count 134 | cTotal[nsfwToggle] += 1 135 | if (AnilistStatus == "COMPLETED"): 136 | cComplete[nsfwToggle] += 1 137 | elif (AnilistStatus == "PAUSED"): 138 | cHold[nsfwToggle] += 1 139 | elif (AnilistStatus == "CURRENT"): 140 | cWatch[nsfwToggle] += 1 141 | elif (AnilistStatus == "DROPPED"): 142 | cDrop[nsfwToggle] += 1 143 | elif (AnilistStatus == "PLANNING"): 144 | cPtw[nsfwToggle] += 1 145 | elif (AnilistStatus == "REPEATING"): 146 | cWatch[nsfwToggle] += 1 147 | 148 | # Dump JSON to file.. 149 | if (fMain.dumpToJson(jsonToDump, outputMedia)): 150 | fMain.logString("Succesfully created json file!", source) 151 | else: 152 | fMain.logString("Error with creating json file!", source) 153 | fMain.logString(f"Done with {mediaType} JSON file..", source) 154 | 155 | # Dump JSON (nsfw) to file.. 156 | if isSepNsfw: 157 | if (fMain.dumpToJson(jsonToDumpNsfw, outputMedia18)): 158 | fMain.logString("Succesfully created json file!", source) 159 | else: 160 | fMain.logString("Error with creating json file!", source) 161 | fMain.logString(f"Done with {mediaType} JSON file..", source) 162 | 163 | # Write to MAL xml file 164 | if isExportMal: 165 | fMain.logString(f"Finalizing {mediaType} XML file..", source) 166 | malprepend = "" 167 | malprepend18 = "" 168 | 169 | mediastring = "" 170 | mediaexport = '0' 171 | mediawatchread = "" 172 | if mediaType == "ANIME": 173 | mediastring = "anime" 174 | mediaexport = '1' 175 | mediawatchread = "watch" 176 | else: 177 | mediastring = "manga" 178 | mediaexport = '2' 179 | mediawatchread = "read" 180 | 181 | fMain.write_append(xmlMedia, f'') 182 | if isSepNsfw: 183 | fMain.write_append(xmlMedia18, f'') 184 | 185 | # Total counts for MAL 186 | fMain.logString(f"Prepend 'myinfo' to {mediaType} XML file..", source) 187 | malprepend = f'\n\n' 188 | malprepend += '\t\n' 189 | malprepend += '\t\t' + fMain.toMalval('', 'user_id') + '\n' 190 | malprepend += '\t\t' + fMain.toMalval(userMal, 'user_name') + '\n' 191 | malprepend += '\t\t' + fMain.toMalval(mediaexport, 'user_export_type') + '\n' 192 | 193 | malprepend18 = malprepend # Same prepend values as 'main' 194 | # Count for 'main' 195 | malprepend += '\t\t' + fMain.toMalval(str(cTotal[0]), f'user_total_{mediastring}') + '\n' 196 | malprepend += '\t\t' + fMain.toMalval(str(cWatch[0]), f'user_total_{mediawatchread}ing') + '\n' 197 | malprepend += '\t\t' + fMain.toMalval(str(cComplete[0]), 'user_total_completed') + '\n' 198 | malprepend += '\t\t' + fMain.toMalval(str(cHold[0]), 'user_total_onhold') + '\n' 199 | malprepend += '\t\t' + fMain.toMalval(str(cDrop[0]), 'user_total_dropped') + '\n' 200 | malprepend += '\t\t' + fMain.toMalval(str(cPtw[0]), f'user_total_planto{mediawatchread}') + '\n' 201 | # Count for 'nsfw' 202 | if isSepNsfw: 203 | malprepend18 += '\t\t' + fMain.toMalval(str(cTotal[1]), f'user_total_{mediastring}') + '\n' 204 | malprepend18 += '\t\t' + fMain.toMalval(str(cWatch[1]), f'user_total_{mediawatchread}ing') + '\n' 205 | malprepend18 += '\t\t' + fMain.toMalval(str(cComplete[1]), 'user_total_completed') + '\n' 206 | malprepend18 += '\t\t' + fMain.toMalval(str(cHold[1]), 'user_total_onhold') + '\n' 207 | malprepend18 += '\t\t' + fMain.toMalval(str(cDrop[1]), 'user_total_dropped') + '\n' 208 | malprepend18 += '\t\t' + fMain.toMalval(str(cPtw[1]), f'user_total_planto{mediawatchread}') + '\n' 209 | 210 | malprepend += '\t\n' 211 | malprepend18 += '\t\n' 212 | 213 | fMain.line_prepender(xmlMedia, malprepend) 214 | if isSepNsfw: 215 | fMain.line_prepender(xmlMedia18, malprepend18) 216 | fMain.logString(f"Done with {mediaType} XML file..", source) 217 | 218 | # Done anime/manga 219 | fMain.logString("Done! File generated: " + outputMedia, source) 220 | if isExportMal: 221 | fMain.logString("Done! File generated: " + xmlMedia, source) 222 | if isSepNsfw: 223 | fMain.logString("Done! File generated: " + outputMedia18, source) 224 | if isExportMal: 225 | fMain.logString("Done! File generated: " + xmlMedia18, source) 226 | 227 | # Already existing! 228 | else: 229 | fMain.logString(f"{mediaType} file already exist!: " + outputMedia, source) 230 | 231 | returnMedia = {'main':outputMedia, 'nsfw':outputMedia18} 232 | return returnMedia 233 | -------------------------------------------------------------------------------- /func/main.py: -------------------------------------------------------------------------------- 1 | # Global functions (Main functions) 2 | # Imports 3 | import os 4 | from datetime import datetime 5 | import json 6 | import gzip 7 | import shutil 8 | # 9 | print(f'[{datetime.now().strftime("%H:%M:%S")}][]: Imported func.main') 10 | 11 | # Simple log 12 | def logger(text: str) -> str: 13 | print(f'[{datetime.now().strftime("%H:%M:%S")}][main]: {text}') 14 | 15 | # Log string, and return it 16 | def logString(text: str, source="main") -> str: 17 | print(f'[{datetime.now().strftime("%H:%M:%S")}][{source}]: {text}') 18 | return text 19 | 20 | # Log string to file 21 | def logFile(file: str, text: str): 22 | write_append(file, f'[{datetime.now().strftime("%Y-%m-%d")} {datetime.now().strftime("%H:%M:%S")}]: {text}\n') 23 | 24 | # Ask for Input 25 | def inputX(text: str, defVal: str): 26 | try: 27 | inputval = input(f'[{datetime.now().strftime("%H:%M:%S")}][main]: {text}') 28 | if not inputval: 29 | inputval = defVal 30 | return inputval 31 | except: 32 | return "" 33 | 34 | # Check if not Null, and return 35 | def validateStr(x) -> str: 36 | if x is not None: 37 | #fixed = re.sub(r'(? 0): 54 | return str(x) 55 | return '0' 56 | return '0' 57 | 58 | def validateIntAsInt(x): 59 | if x is not None: 60 | if (x > 0): 61 | return x 62 | return 0 63 | return 0 64 | 65 | # Check if not Null, and return 66 | def validateDate(year, month, day): 67 | date = validateStr(year) + "-" + validateStr(month) + "-" + validateStr(day) 68 | if (date == "--"): 69 | return "" 70 | else: 71 | dateArr = date.split('-') 72 | if len(dateArr[1]) < 2: 73 | dateArr[1] = '0' + dateArr[1] 74 | if len(dateArr[2]) < 2: 75 | dateArr[2] = '0' + dateArr[2] 76 | date = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2] 77 | return date 78 | 79 | # Create string/int for MAL XML file 80 | def toMalstr(content, name): 81 | fixed = validateStr(content) 82 | return "<" + name + ">" 83 | 84 | def toMalval(content, name): 85 | return "<" + name + ">" + content + "" 86 | 87 | def toMaldate(year, month, day): 88 | date = validateDate(year, month, day) 89 | if (date == ""): 90 | return "0000-00-00" 91 | return date 92 | 93 | def toMalStatus(status, media): 94 | AnilistStatus = validateStr(status) 95 | if (AnilistStatus == "COMPLETED"): 96 | return "Completed" 97 | elif (AnilistStatus == "PAUSED"): 98 | return "On-Hold" 99 | elif (AnilistStatus == "CURRENT"): 100 | if (media == 'anime'): 101 | return "Watching" 102 | else: 103 | return "Reading" 104 | elif (AnilistStatus == "DROPPED"): 105 | return "Dropped" 106 | elif (AnilistStatus == "PLANNING"): 107 | if (media == 'anime'): 108 | return "Plan to Watch" 109 | else: 110 | return "Plan to Read" 111 | elif (AnilistStatus == "REPEATING"): 112 | if (media == 'anime'): 113 | return "Watching" 114 | else: 115 | return "Reading" 116 | else: 117 | return "" 118 | 119 | # Read file and return contents 120 | def read_file(filename) -> str: 121 | content: str = "" 122 | try: 123 | with open(filename, 'r+', encoding='utf-8') as f: 124 | content = f.read() 125 | except Exception as e: 126 | logString(f'Failed to read file: {filename}') 127 | 128 | return content 129 | 130 | # Add texts on beginning of file 131 | def line_prepender(filename, line): 132 | with open(filename, 'r+', encoding='utf-8') as f: 133 | content = f.read() 134 | f.seek(0, 0) 135 | f.write(line + '\n' + content) 136 | 137 | # Write 'contents' to end of file (append string to file) 138 | def write_append(filename, content): 139 | with open(filename, "a+", encoding='utf-8') as f: 140 | f.write(content) 141 | 142 | # Remove characters from end of file 143 | def write_remove(filename, char_count): 144 | with open(filename, 'rb+') as filehandle: 145 | filehandle.seek(-char_count, os.SEEK_END) 146 | filehandle.truncate() 147 | 148 | # Return json dict object to be appended 149 | def entry_json(entry, mediaType: str): 150 | jsonObj = {} 151 | # ID 152 | jsonObj["idAnilist"] = validateIntAsInt(entry["media"]["id"]) 153 | malID = validateIntAsInt(entry["media"]["idMal"]) 154 | jsonObj["idMal"] = malID 155 | # Titles 156 | jsonObj["titleEnglish"] = validateStr(entry["media"]["title"]["english"]) 157 | jsonObj["titleRomaji"] = validateStr(entry["media"]["title"]["romaji"]) 158 | jsonObj["synonyms"] = validateStrArr(entry["media"]["synonyms"]) 159 | # Format and Source 160 | jsonObj["format"] = validateStr(entry["media"]["format"]) 161 | jsonObj["source"] = validateStr(entry["media"]["source"]) 162 | # Status and dates 163 | jsonObj["status"] = validateStr(entry["status"]) 164 | jsonObj["startedAt"] = validateDate(entry["startedAt"]["year"], entry["startedAt"]["month"], entry["startedAt"]["day"]) 165 | jsonObj["completedAt"] = validateDate(entry["completedAt"]["year"], entry["completedAt"]["month"], entry["completedAt"]["day"]) 166 | # Progress 167 | jsonObj["progress"] = validateIntAsInt(entry["progress"]) 168 | 169 | if (mediaType == 'ANIME'): 170 | jsonObj["totalEpisodes"] = validateIntAsInt(entry["media"]["episodes"]) 171 | else: 172 | jsonObj["progressVolumes"] = validateIntAsInt(entry["progressVolumes"]) 173 | jsonObj["totalChapters"] = validateIntAsInt(entry["media"]["chapters"]) 174 | jsonObj["totalVol"] = validateIntAsInt(entry["media"]["volumes"]) 175 | 176 | # Others 177 | jsonObj["score"] = validateIntAsInt(entry["score"]) 178 | jsonObj["private"] = str(entry["private"]) 179 | jsonObj["notes"] = validateStr(entry["notes"]) 180 | jsonObj["isAdult"] = entry["media"]["isAdult"] 181 | return jsonObj 182 | 183 | # Return strings to add to json 184 | def entry_json_str(entry, mediaType): 185 | jsontoAdd = "\t{\n" 186 | # ID 187 | jsontoAdd += '\t\t"idAnilist": ' + str(entry["media"]["id"]) + ",\n" 188 | malID = validateInt(entry["media"]["idMal"]) 189 | jsontoAdd += '\t\t"idMal": ' + malID + ",\n" 190 | # Titles 191 | jsontoAdd += '\t\t"titleEnglish": "' + validateStr(entry["media"]["title"]["english"]) + '",\n' 192 | jsontoAdd += '\t\t"titleRomaji": "' + validateStr(entry["media"]["title"]["romaji"]) + '",\n' 193 | jsontoAdd += '\t\t"synonyms": "' + validateStrArr(entry["media"]["synonyms"]) + '",\n' 194 | # Format and Source 195 | jsontoAdd += '\t\t"format": "' + validateStr(entry["media"]["format"]) + '",\n' 196 | jsontoAdd += '\t\t"source": "' + validateStr(entry["media"]["source"]) + '",\n' 197 | # Status and dates 198 | jsontoAdd += '\t\t"status": "' + validateStr(entry["status"]) + '",\n' 199 | jsontoAdd += '\t\t"startedAt": "' + validateDate(entry["startedAt"]["year"], entry["startedAt"]["month"], entry["startedAt"]["day"]) + '",\n' 200 | jsontoAdd += '\t\t"completedAt": "' + validateDate(entry["completedAt"]["year"], entry["completedAt"]["month"], entry["completedAt"]["day"]) + '",\n' 201 | # Progress 202 | jsontoAdd += '\t\t"progress": ' + validateInt(entry["progress"]) + ',\n' 203 | 204 | if (mediaType == 'ANIME'): 205 | jsontoAdd += '\t\t"totalEpisodes": ' + validateInt(entry["media"]["episodes"]) + ",\n" 206 | else: 207 | jsontoAdd += '\t\t"progressVolumes": ' + validateInt(entry["progressVolumes"]) + ",\n" 208 | jsontoAdd += '\t\t"totalChapters": ' + validateInt(entry["media"]["chapters"]) + ",\n" 209 | jsontoAdd += '\t\t"totalVol": ' + validateInt(entry["media"]["volumes"]) + ",\n" 210 | 211 | # Others 212 | jsontoAdd += '\t\t"score": ' + validateInt(entry["score"]) + ",\n" 213 | jsontoAdd += '\t\t"private": "' + str(entry["private"]) + '",\n' 214 | jsontoAdd += '\t\t"notes": "' + validateStr(entry["notes"]) + '"\n\t},\n' 215 | return jsontoAdd 216 | 217 | # Return string to add to MAL XML 218 | def entry_xmlstr(mediaType, malID, entry, status): 219 | if mediaType == "ANIME": 220 | xmltoWrite = "\t\n" 221 | xmltoWrite += "\t\t" + toMalval(malID, 'series_animedb_id') + '\n' 222 | xmltoWrite += "\t\t" + toMalstr(validateStr(entry["media"]["title"]["romaji"]), 'series_title') + '\n' 223 | xmltoWrite += "\t\t" + toMalval('', 'series_type') + '\n' 224 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["media"]["episodes"]), 'series_episodes') + '\n' 225 | xmltoWrite += "\t\t" + toMalval('0', 'my_id') + '\n' 226 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["progress"]), 'my_watched_episodes') + '\n' 227 | xmltoWrite += "\t\t" + toMalval(toMaldate(entry["startedAt"]["year"],entry["startedAt"]["month"],entry["startedAt"]["day"]), 'my_start_date') + '\n' 228 | xmltoWrite += "\t\t" + toMalval(toMaldate(entry["completedAt"]["year"],entry["completedAt"]["month"],entry["completedAt"]["day"]), 'my_finish_date') + '\n' 229 | xmltoWrite += "\t\t" + toMalval('', 'my_rated') + '\n' 230 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["score"]), 'my_score') + '\n' 231 | xmltoWrite += "\t\t" + toMalval('', 'my_dvd') + '\n' 232 | xmltoWrite += "\t\t" + toMalval('', 'my_storage') + '\n' 233 | xmltoWrite += "\t\t" + toMalval(toMalStatus(entry["status"], 'anime'), 'my_status') + '\n' 234 | xmltoWrite += "\t\t" + toMalstr(validateStr(entry["notes"]), 'my_comments') + '\n' 235 | xmltoWrite += "\t\t" + toMalval('0', 'my_times_watched') + '\n' 236 | xmltoWrite += "\t\t" + toMalval('', 'my_rewatch_value') + '\n' 237 | xmltoWrite += "\t\t" + toMalstr('', 'my_tags') + '\n' 238 | if (status=="REPEATING"): 239 | xmltoWrite += "\t\t" + toMalval('YES', 'my_rewatching') + '\n' 240 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["progress"]), 'my_rewatching_ep') + '\n' 241 | else: 242 | xmltoWrite += "\t\t" + toMalval('NO', 'my_rewatching') + '\n' 243 | xmltoWrite += "\t\t" + toMalval('0', 'my_rewatching_ep') + '\n' 244 | 245 | xmltoWrite += "\t\t" + toMalval('1', 'update_on_import') + '\n' 246 | xmltoWrite += "\t\n" 247 | else: 248 | xmltoWrite = "\t\n" 249 | xmltoWrite += "\t\t" + toMalval(malID, 'manga_mangadb_id') + '\n' 250 | xmltoWrite += "\t\t" + toMalstr(validateStr(entry["media"]["title"]["romaji"]), 'manga_title') + '\n' 251 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["media"]["volumes"]), 'manga_volumes') + '\n' 252 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["media"]["chapters"]), 'manga_chapters') + '\n' 253 | xmltoWrite += "\t\t" + toMalval('', 'my_id') + '\n' 254 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["progressVolumes"]), 'my_read_volumes') + '\n' 255 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["progress"]), 'my_read_chapters') + '\n' 256 | xmltoWrite += "\t\t" + toMalval(toMaldate(entry["startedAt"]["year"],entry["startedAt"]["month"],entry["startedAt"]["day"]), 'my_start_date') + '\n' 257 | xmltoWrite += "\t\t" + toMalval(toMaldate(entry["completedAt"]["year"],entry["completedAt"]["month"],entry["completedAt"]["day"]), 'my_finish_date') + '\n' 258 | xmltoWrite += "\t\t" + toMalstr('', 'my_scanalation_group') + '\n' 259 | xmltoWrite += "\t\t" + toMalval(validateInt(entry["score"]), 'my_score') + '\n' 260 | xmltoWrite += "\t\t" + toMalval('', 'my_storage') + '\n' 261 | xmltoWrite += "\t\t" + toMalval(toMalStatus(entry["status"], 'manga'), 'my_status') + '\n' 262 | xmltoWrite += "\t\t" + toMalstr(validateStr(entry["notes"]), 'my_comments') + '\n' 263 | xmltoWrite += "\t\t" + toMalval('0', 'my_times_read') + '\n' 264 | xmltoWrite += "\t\t" + toMalstr('', 'my_tags') + '\n' 265 | xmltoWrite += "\t\t" + toMalval('', 'my_reread_value') + '\n' 266 | if (status=="REPEATING"): 267 | xmltoWrite += "\t\t" + toMalval('YES', 'my_rereading') + '\n' 268 | else: 269 | xmltoWrite += "\t\t" + toMalval('NO', 'my_rereading') + '\n' 270 | xmltoWrite += "\t\t" + toMalval('1', 'update_on_import') + '\n' 271 | xmltoWrite += "\t\n" 272 | return xmltoWrite 273 | 274 | # Delete file 275 | def deleteFile(file): 276 | if os.path.exists(file): 277 | os.remove(file) 278 | 279 | # Dump object to json file 280 | def dumpToJson(objToDump, filePath): 281 | try: 282 | with open(filePath, "w+", encoding='utf-8') as F: 283 | F.write(json.dumps(objToDump, ensure_ascii=True, indent=4).encode('utf8').decode()) 284 | return True 285 | except: 286 | return False 287 | 288 | def createJsonFile(filepath, jsonObject, logSrc = "main"): 289 | logString("Writing to file " + os.path.basename(filepath), logSrc) 290 | try: 291 | with open(filepath, "w+", encoding='utf-8') as F: 292 | F.write(json.dumps(jsonObject, ensure_ascii=False, indent=4).encode('utf8').decode()) 293 | logString("File generated: " + filepath, logSrc) 294 | except: 295 | logString(f"Cannot write json file: {filepath}", logSrc) 296 | 297 | # Extract gz file 298 | def extractGz(input: str) -> str: 299 | #logString("Input: " + input) 300 | output = input[:-3] 301 | with gzip.open(input, 'rb') as f_in: 302 | #logString(f"Output: {output}") 303 | with open(output, 'wb') as f_out: 304 | shutil.copyfileobj(f_in, f_out) 305 | return output 306 | 307 | # Compress file to gz 308 | def compressGz(input: str) -> str: 309 | logString("Compressing file to gz..") 310 | output:str = f'{input}.gz' 311 | with open(input, 'rb') as f_in, gzip.open(output, 'wb') as f_out: 312 | f_out.writelines(f_in) 313 | return output 314 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 2020 Jacekun (github.com/Jacekun) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | AniPy Copyright (C) 2020 Jacekun (github.com/Jacekun) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------