├── .github ├── CIBuildFIles │ ├── android-makefile │ ├── buildLinux.spec │ ├── buildMac.spec │ └── buildWindows.spec ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ ├── question.md │ └── request-immediate-triage.md ├── icon.png ├── previews │ ├── achievements.png │ ├── autocomplete.png │ ├── backup.png │ ├── editAchievements.png │ ├── editAchievementsMin.png │ ├── editBiome.png │ ├── editParty.png │ ├── editStarter.png │ ├── editStats.png │ ├── egg_list.png │ ├── eggs.gif │ ├── eggsLegendary.png │ ├── eggsManaphy.png │ ├── field2.png │ ├── fun1.png │ ├── fun2.png │ ├── itemEditor.png │ ├── itemEditorIngame.png │ ├── loginMethods.png │ ├── main.png │ ├── money.png │ ├── networkResolution.png │ ├── pokeballs.png │ ├── starter.png │ ├── stats.png │ ├── tickets.png │ ├── tool.png │ ├── updateChecker.png │ └── voucher.png ├── release-drafter.yml └── workflows │ ├── autobuild.yaml │ ├── black.yml │ ├── dependency-review.yml │ ├── release-drafter.yml │ ├── ruff.yml │ └── workflow-overview.txt ├── .gitignore ├── LICENSE ├── PREVIEW.md ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── SECURITY.md └── src ├── main.py ├── modules ├── __init__.py ├── config.py ├── data │ ├── __init__.py │ └── dataParser.py ├── handler │ ├── __init__.py │ ├── httpResponseHandling.py │ ├── inputHandler.py │ └── operationResponseHandling.py ├── itemLogic.py ├── mainLogic.py ├── requestsLogic.py └── seleniumLogic.py ├── offlineSaveConverter ├── index.html ├── js │ ├── cryptography-js.min.js │ └── script.js └── readme.md ├── requirements.txt └── utilities ├── __init__.py ├── cFormatter.py ├── eggLogic.py ├── enumLoader.py ├── generator.py ├── limiter.py ├── logger.py └── propagateMessage.py /.github/CIBuildFIles/android-makefile: -------------------------------------------------------------------------------- 1 | # Makefile for pyRogue 2 | 3 | # Variables 4 | SRC_DIR := ../../src 5 | UTILITIES_DIR := $(SRC_DIR)/utilities 6 | MODULES_DIR := $(SRC_DIR)/modules 7 | MAIN_FILE := $(SRC_DIR)/main.py 8 | BUILD_DIR := build 9 | DIST_DIR := dist 10 | 11 | # List of added files with their respective directories 12 | ADDED_FILES := $(UTILITIES_DIR)/*.py:utilities $(MODULES_DIR)/*.py:modules 13 | 14 | # Build target 15 | build: 16 | @echo "Building pyRogue..." 17 | @kivy_pyinstaller -F --name pyRogue --windowed --icon icon.ico --add-data "$(ADDED_FILES)" $(MAIN_FILE) 18 | @echo "Build completed. Find the executable in $(DIST_DIR)" 19 | @echo "Modifying permissions..." 20 | @echo "{\"app_name\": \"pyRogue\", \"permissions\": [\"INTERNET\", \"KEYBOARD\"]}" > $(DIST_DIR)/kivy_permissions.json 21 | @echo "Permissions set." 22 | 23 | # Clean target 24 | clean: 25 | @echo "Cleaning up..." 26 | @rm -rf $(BUILD_DIR) $(DIST_DIR) 27 | @echo "Cleanup completed." 28 | -------------------------------------------------------------------------------- /.github/CIBuildFIles/buildLinux.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | from PyInstaller.utils.hooks import collect_data_files 4 | 5 | added_files = [ 6 | ('../../src/utilities/*.py', 'utilities'), 7 | ('../../src/modules/*.py', 'modules') 8 | ] 9 | 10 | a = Analysis( 11 | ['../../src/main.py'], 12 | pathex=[], 13 | binaries=[], 14 | datas=added_files, 15 | hiddenimports=['_cffi_backend'], 16 | hookspath=[], 17 | hooksconfig={}, 18 | runtime_hooks=[], 19 | excludes=[], 20 | noarchive=False, 21 | optimize=0, 22 | ) 23 | pyz = PYZ(a.pure) 24 | 25 | exe = EXE( 26 | pyz, 27 | a.scripts, 28 | a.binaries, 29 | a.datas, 30 | [], 31 | name='pyRogue-Linux.sh', 32 | debug=False, 33 | bootloader_ignore_signals=False, 34 | strip=False, 35 | upx=True, 36 | upx_exclude=[], 37 | runtime_tmpdir=None, 38 | console=True, 39 | disable_windowed_traceback=False, 40 | argv_emulation=False, 41 | target_arch=None, 42 | codesign_identity=None, 43 | entitlements_file=None, 44 | icon=None, 45 | ) 46 | -------------------------------------------------------------------------------- /.github/CIBuildFIles/buildMac.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | added_files = [ 4 | ('../../src/utilities/*.py', 'utilities'), 5 | ('../../src/modules/*.py', 'modules') 6 | ] 7 | 8 | 9 | a = Analysis( 10 | ['../../src/main.py'], 11 | pathex=[], 12 | binaries=[], 13 | datas=added_files, 14 | hiddenimports=['_cffi_backend'], 15 | hookspath=[], 16 | hooksconfig={}, 17 | runtime_hooks=[], 18 | excludes=[], 19 | noarchive=False, 20 | optimize=0, 21 | ) 22 | pyz = PYZ(a.pure) 23 | 24 | exe = EXE( 25 | pyz, 26 | a.scripts, 27 | a.binaries, 28 | a.datas, 29 | [], 30 | name='pyRogue-MacIntel.sh', 31 | debug=False, 32 | bootloader_ignore_signals=False, 33 | strip=False, 34 | upx=True, 35 | upx_exclude=[], 36 | runtime_tmpdir=None, 37 | console=True, 38 | disable_windowed_traceback=False, 39 | argv_emulation=False, 40 | target_arch=None, 41 | codesign_identity=None, 42 | entitlements_file=None, 43 | icon=None, 44 | ) 45 | -------------------------------------------------------------------------------- /.github/CIBuildFIles/buildWindows.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | added_files = [ 4 | ('../../src/utilities/*.py', 'utilities'), 5 | ('../../src/modules/*.py', 'modules') 6 | ] 7 | 8 | 9 | a = Analysis( 10 | ['../../src/main.py'], 11 | pathex=[], 12 | binaries=[], 13 | datas=added_files, 14 | hiddenimports=['_cffi_backend'], 15 | hookspath=[], 16 | hooksconfig={}, 17 | runtime_hooks=[], 18 | excludes=[], 19 | noarchive=False, 20 | optimize=0, 21 | ) 22 | pyz = PYZ(a.pure) 23 | 24 | exe = EXE( 25 | pyz, 26 | a.scripts, 27 | a.binaries, 28 | a.datas, 29 | [], 30 | name='pyRogue-Windows.exe', 31 | debug=False, 32 | bootloader_ignore_signals=False, 33 | strip=False, 34 | upx=True, 35 | upx_exclude=[], 36 | runtime_tmpdir=None, 37 | console=True, 38 | disable_windowed_traceback=False, 39 | argv_emulation=False, 40 | target_arch=None, 41 | codesign_identity=None, 42 | entitlements_file=None, 43 | icon=None, 44 | ) 45 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: 'Bug: Need attention immediately' 5 | labels: bug 6 | assignees: M6D6M6A, claudiunderthehood, JulianStiebler 7 | 8 | --- 9 | 10 | **What Operating System are you on** - Windows, Ubuntu, Mac, ... 11 | - ... 12 | 13 | **Describe the bug** - A clear and concise description of what the bug is. 14 | - ... 15 | 16 | **To Reproduce** - Describe the steps needed to reproduce the bug. 17 | - ... 18 | 19 | **Expected behavior** A clear and concise description of what you expected to happen. 20 | - ... 21 | 22 | **Screenshots** - If applicable, add screenshots to help explain your problem. 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: 'Feature: Requested' 5 | labels: feature 6 | assignees: M6D6M6A, claudiunderthehood, JulianStiebler 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | - ... 12 | 13 | **Describe the solution you'd like to see implemented** 14 | - ... 15 | 16 | **If you can link to the related source files that'd be great!** 17 | https://github.com/pagefaultgames/pokerogue 18 | https://github.com/pagefaultgames/rogueserver 19 | 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: If you have a question propose it here. 4 | title: 'Question: Attention needed' 5 | labels: question 6 | assignees: M6D6M6A, claudiunderthehood, JulianStiebler 7 | 8 | --- 9 | 10 | **A clear and concise description of what the question is.** 11 | - ... -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/request-immediate-triage.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Request immediate triage 3 | about: Request an immediate response to something unfortunate. 4 | title: '' 5 | labels: research, triage 6 | assignees: M6D6M6A, claudiunderthehood, JulianStiebler 7 | 8 | --- 9 | 10 | **Please describe clear what is happening as these will trigger some notifications to ensure activity.** 11 | -------------------------------------------------------------------------------- /.github/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/icon.png -------------------------------------------------------------------------------- /.github/previews/achievements.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/achievements.png -------------------------------------------------------------------------------- /.github/previews/autocomplete.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/autocomplete.png -------------------------------------------------------------------------------- /.github/previews/backup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/backup.png -------------------------------------------------------------------------------- /.github/previews/editAchievements.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/editAchievements.png -------------------------------------------------------------------------------- /.github/previews/editAchievementsMin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/editAchievementsMin.png -------------------------------------------------------------------------------- /.github/previews/editBiome.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/editBiome.png -------------------------------------------------------------------------------- /.github/previews/editParty.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/editParty.png -------------------------------------------------------------------------------- /.github/previews/editStarter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/editStarter.png -------------------------------------------------------------------------------- /.github/previews/editStats.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/editStats.png -------------------------------------------------------------------------------- /.github/previews/egg_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/egg_list.png -------------------------------------------------------------------------------- /.github/previews/eggs.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/eggs.gif -------------------------------------------------------------------------------- /.github/previews/eggsLegendary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/eggsLegendary.png -------------------------------------------------------------------------------- /.github/previews/eggsManaphy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/eggsManaphy.png -------------------------------------------------------------------------------- /.github/previews/field2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/field2.png -------------------------------------------------------------------------------- /.github/previews/fun1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/fun1.png -------------------------------------------------------------------------------- /.github/previews/fun2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/fun2.png -------------------------------------------------------------------------------- /.github/previews/itemEditor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/itemEditor.png -------------------------------------------------------------------------------- /.github/previews/itemEditorIngame.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/itemEditorIngame.png -------------------------------------------------------------------------------- /.github/previews/loginMethods.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/loginMethods.png -------------------------------------------------------------------------------- /.github/previews/main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/main.png -------------------------------------------------------------------------------- /.github/previews/money.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/money.png -------------------------------------------------------------------------------- /.github/previews/networkResolution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/networkResolution.png -------------------------------------------------------------------------------- /.github/previews/pokeballs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/pokeballs.png -------------------------------------------------------------------------------- /.github/previews/starter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/starter.png -------------------------------------------------------------------------------- /.github/previews/stats.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/stats.png -------------------------------------------------------------------------------- /.github/previews/tickets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/tickets.png -------------------------------------------------------------------------------- /.github/previews/tool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/tool.png -------------------------------------------------------------------------------- /.github/previews/updateChecker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/updateChecker.png -------------------------------------------------------------------------------- /.github/previews/voucher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RogueEdit/pyRogue/a2fecb67aff08687c6fcd4f32d3030032c6f130d/.github/previews/voucher.png -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: 'v$RESOLVED_VERSION 🌈' 2 | tag-template: 'v$RESOLVED_VERSION' 3 | 4 | # Specify Categories for Release Drafter 5 | categories: 6 | - title: '🚀 Added Features' 7 | collapse-after: 8 8 | label: 'feature' 9 | - title: '🔑 Security Additions' 10 | collapse-after: 8 11 | label: 'security' 12 | - title: '🐛 Bug Fixes' 13 | collapse-after: 8 14 | label: 'bug' 15 | - title: '🐢 Optimization' 16 | collapse-after: 8 17 | label: 'optimization' 18 | - title: '🧰 from Dependency import Changes' 19 | collapse-after: 8 20 | label: 'dependency' 21 | - title: '⚡ Workflow Changes' 22 | collapse-after: 8 23 | label: 'workflow' 24 | - title: '📝 # Documentation Changes' 25 | collapse-after: 8 26 | label: 'documentation' 27 | - title: '⚡ Changes made to the Data-handling' 28 | collapse-after: 8 29 | label: 'workflow' 30 | 31 | #Autolabeler, define your labels here and when to trigger. Escpae for '' is needed 32 | # example '/feature/' 33 | autolabeler: 34 | # Label: Feature ------------------------- 35 | - label: 'feature' 36 | body: 37 | - '/feature/' 38 | - '/Feature/' 39 | title: 40 | - '/feature/' 41 | - '/Feature/' 42 | 43 | # Label: Security ------------------------- 44 | - label: 'security' 45 | body: 46 | - '/security/' 47 | - '/Security/' 48 | - '/CVE/' 49 | title: 50 | - '/security/' 51 | - '/Security/' 52 | - '/CVE/' 53 | 54 | # Label: Bug ------------------------- 55 | - label: 'bug' 56 | body: 57 | - '/bug/' 58 | - '/Bug/' 59 | - '/bugfix/' 60 | title: 61 | - '/bug/' 62 | - '/Bug/' 63 | - '/bugfix/' 64 | - '/error/' 65 | - '/fix/' 66 | 67 | # Label: Optimization ------------------------- 68 | - label: 'optimization' 69 | body: 70 | - '/optimization/' 71 | - '/performance/' 72 | title: 73 | - '/optimization/' 74 | - '/performance/' 75 | 76 | # Label: Dependency ------------------------- 77 | - label: 'dependency' 78 | body: 79 | - '/dependency/' 80 | - '/Dependency/' 81 | - '/dependabot/' 82 | title: 83 | - '/dependency' 84 | - '/Dependency/' 85 | - '/dependabot/' 86 | - '/bump' 87 | 88 | # Label: Workflow ------------------------- 89 | - label: 'workflow' 90 | body: 91 | - '/workflow/' 92 | - '/Workflow/' 93 | - '/yaml/' 94 | title: 95 | - '/workflow/' 96 | - '/Workflow/' 97 | - '/yaml/' 98 | 99 | # Label: Documentation ------------------------- 100 | - label: 'documentation' 101 | body: 102 | - '/documentation/' 103 | - '/Documentation/' 104 | - '/.md/' 105 | title: 106 | - '/documentation/' 107 | - '/Documentation/' 108 | - '/.md/' 109 | 110 | # Label: Database ------------------------- 111 | - label: 'database' 112 | body: 113 | - '/database/' 114 | - '/Database/' 115 | - '/.db/' 116 | title: 117 | - '/database/' 118 | - '/Database/' 119 | - '/.db/' 120 | 121 | # Label: enhancement ------------------------- 122 | - label: 'enhancement' 123 | title: 124 | - '/enhance/' 125 | - '/enhancement/' 126 | 127 | change-template: '- $TITLE @$AUTHOR (#$NUMBER)' 128 | change-title-escapes: '\<*_&' 129 | 130 | template: | 131 | ## 🔆 What changed? 132 | 133 | $CHANGES -------------------------------------------------------------------------------- /.github/workflows/autobuild.yaml: -------------------------------------------------------------------------------- 1 | name: Build binary files to selected branch (DANGER AREA) 2 | on: 3 | workflow_dispatch: 4 | 5 | jobs: 6 | prepare: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | name: Checkout 11 | 12 | - name: Refresh data folder from source 13 | run: | 14 | rm -rf compiled/data 15 | cp -rf src/data/ compiled/ 16 | 17 | build: 18 | needs: prepare 19 | strategy: 20 | matrix: 21 | os: ['windows-latest', 'ubuntu-latest', 'macos-latest'] 22 | python-version: ["3.10"] 23 | runs-on: ${{ matrix.os }} 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | name: Checkout 28 | 29 | - uses: actions/setup-python@v5 30 | name: Setup Python 31 | with: 32 | python-version: ${{ matrix['python-version'] }} 33 | 34 | - name: Build Executables (Windows) 35 | if: ${{ matrix.os == 'windows-latest' }} 36 | run: | 37 | python3 -m ensurepip 38 | python -m pip install --upgrade pip 39 | pip install pyinstaller -r src/requirements.txt 40 | pyinstaller .github/CIBuildFIles/buildWindows.spec 41 | 42 | - name: Upload Artifacts (Windows) 43 | if: ${{ matrix.os == 'windows-latest' }} 44 | uses: actions/upload-artifact@v4 45 | with: 46 | name: pyRogue-Windows 47 | path: | 48 | dist/pyRogue-windows.exe 49 | 50 | - name: Build Executables (Linux) 51 | if: ${{ matrix.os == 'ubuntu-latest' }} 52 | run: | 53 | python3 -m ensurepip 54 | python3 -m pip install --upgrade pip 55 | pip install pyinstaller -r src/requirements.txt 56 | pyinstaller .github/CIBuildFIles/buildLinux.spec 57 | 58 | - name: Upload Artifacts (Linux) 59 | if: ${{ matrix.os == 'ubuntu-latest' }} 60 | uses: actions/upload-artifact@v4 61 | with: 62 | name: pyRogue-Linux 63 | path: | 64 | dist/pyRogue-Linux.sh 65 | 66 | - name: Build Executables (Mac) 67 | if: ${{ matrix.os == 'macos-latest' }} 68 | run: | 69 | python3 -m ensurepip 70 | python3 -m pip install --upgrade pip 71 | pip install pyinstaller -r src/requirements.txt 72 | pyinstaller .github/CIBuildFIles/buildMac.spec 73 | 74 | - name: Upload Artifacts (Mac) 75 | if: ${{ matrix.os == 'macos-latest' }} 76 | uses: actions/upload-artifact@v4 77 | with: 78 | name: pyRogue-MacIntel 79 | path: | 80 | dist/pyRogue-MacIntel.sh 81 | -------------------------------------------------------------------------------- /.github/workflows/black.yml: -------------------------------------------------------------------------------- 1 | name: Black (Formatter) 2 | 3 | on: 4 | pull_request: 5 | branches: ["main", "patch", "dev", "test"] 6 | 7 | 8 | jobs: 9 | lint: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: psf/black@stable 14 | with: 15 | options: ". -v" 16 | version: "~= 22.0" -------------------------------------------------------------------------------- /.github/workflows/dependency-review.yml: -------------------------------------------------------------------------------- 1 | # Dependency Review Action 2 | # 3 | # This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. 4 | # 5 | # Source repository: https://github.com/actions/dependency-review-action 6 | # Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement 7 | name: 'Dependency Review' 8 | on: 9 | pull_request: 10 | branches: ["main", "patch", "dev", "test"] 11 | 12 | permissions: 13 | contents: read 14 | 15 | jobs: 16 | dependency-review: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: 'Checkout Repository' 20 | uses: actions/checkout@v4 21 | - name: 'Dependency Review' 22 | uses: actions/dependency-review-action@v3 23 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | # branches to consider in the event; optional, defaults to all 6 | branches: 7 | - main 8 | - dev 9 | - test 10 | # pull_request event is required only for autolabeler 11 | pull_request: 12 | # Only following types are handled by the action, but one can default to all as well 13 | types: [opened, reopened, synchronize] 14 | # pull_request_target event is required for autolabeler to support PRs from forks 15 | # pull_request_target: 16 | # types: [opened, reopened, synchronize] 17 | 18 | permissions: 19 | contents: read 20 | 21 | jobs: 22 | update_release_draft: 23 | permissions: 24 | # write permission is required to create a github release 25 | contents: write 26 | # write permission is required for autolabeler 27 | # otherwise, read permission is required at least 28 | pull-requests: write 29 | runs-on: ubuntu-latest 30 | steps: 31 | # (Optional) GitHub Enterprise requires GHE_HOST variable set 32 | #- name: Set GHE_HOST 33 | # run: | 34 | # echo "GHE_HOST=${GITHUB_SERVER_URL##https:\/\/}" >> $GITHUB_ENV 35 | 36 | # Drafts your next Release notes as Pull Requests are merged into "master" 37 | - uses: release-drafter/release-drafter@v5 38 | # (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml 39 | # with: 40 | # config-name: my-config.yml 41 | # disable-autolabeler: true 42 | env: 43 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 44 | -------------------------------------------------------------------------------- /.github/workflows/ruff.yml: -------------------------------------------------------------------------------- 1 | name: ruff 2 | on: [push, pull_request] 3 | jobs: 4 | ruff: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v4 8 | - run: pip install --user ruff 9 | - run: ruff check . -v --fix -------------------------------------------------------------------------------- /.github/workflows/workflow-overview.txt: -------------------------------------------------------------------------------- 1 | ---- 2 | Branches 3 | main -> need pull-request with author review and 1 approval+ passed workflow checks 4 | dev -> need pull-request force mergeable bypassing checks, 5 | test -> nothing 6 | ---- 7 | Developing on test, when a feature/fix etc done PR to Dev with a nice Pull-Request title 8 | then click ACtions > Build .exe to create a full /compiled/ suite for all OS 9 | release drafter will reflect those PR in the draft 10 | ---- 11 | PR to Test -> Ruff & CodeQL (Security Analysis) 12 | PR from Test to Dev -> automatic build of .exes in /compiled/ with bypassable checks on pull, but they will run afterwards 13 | PR to Dev to Main -> automatic release since all checks have to be passed 14 | --- 15 | Build Setup 16 | deletes /compiled/ and all files 17 | moves src/data/ to /compiled/data/ 18 | moves src/patch/game-data.ts to /compiled/patch/game-data.ts 19 | builds .exes and places accordingly 20 | 21 | Triggered from PR Test -> Dev 22 | --- 23 | Release Setup 24 | Bundles 25 | 26 | SavefileConverter 27 | respective .exe/.sh and /data/ of offlineEditor 28 | respective .exe/.sh and game-data.ts of Patcher 29 | 30 | Triggered by PR from Dev -> Main 31 | --- 32 | All Pull-Requests and issues will be automatically labeled based on keywords like 33 | bugfix, enhance, workflow, feature, optimization, database 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .venv/* 2 | src/modules/__pycache__/* 3 | src/utilities/__pycache__/* 4 | */__pycache__/* 5 | src/backups/* 6 | src/logs/*.log 7 | src/trainer.json 8 | src/slot_*.json 9 | /src/tests/menuTest/__pycache__ 10 | /src/backup 11 | .vs/* 12 | /src/.vs 13 | src/modules/dev/slot_2.json 14 | src/dev/slot_4.json 15 | src/dev/slot_2.json 16 | /dist 17 | /build 18 | /src/modules/handler/__pycache__ 19 | src/data/extra.json 20 | /src/data 21 | *.pyc 22 | /src/modules/handler/__pycache__ 23 | /src/dev/* 24 | /data 25 | /src/logs 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | Copyright (C) <2022+> PagefaultGames 633 | Copyright (C) <2024+> . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /PREVIEW.md: -------------------------------------------------------------------------------- 1 | ![Preview Image](.github/previews/tool.png) 2 | ![Preview Image](.github/previews/editParty.png) 3 | ![Preview Image](.github/previews/fun1.png) 4 | ![Preview Image](.github/previews/itemEditorIngame.png) 5 | ![Preview Image](.github/previews/itemEditor.png) 6 | ![Preview Image](.github/previews/backup.png) 7 | ![Preview Image](.github/previews/editAchievements.png) 8 | ![Preview Image](.github/previews/editAchievementsMin.png) 9 | ![Preview Image](.github/previews/editBiome.png) 10 | ![Preview Image](.github/previews/editStarter.png) 11 | ![Preview Image](.github/previews/editStats.png) 12 | ![Preview Image](.github/previews/eggs.gif) 13 | ![Preview Image](.github/previews/achievements.png) 14 | ![Preview Image](.github/previews/eggsLegendary.png) 15 | ![Preview Image](.github/previews/eggsManaphy.png) 16 | ![Preview Image](.github/previews/fun2.png) 17 | ![Preview Image](.github/previews/field2.png) 18 | ![Preview Image](.github/previews/loginMethods.png) 19 | ![Preview Image](.github/previews/main.png) 20 | ![Preview Image](.github/previews/money.png) 21 | ![Preview Image](.github/previews/pokeballs.png) 22 | ![Preview Image](.github/previews/starter.png) 23 | ![Preview Image](.github/previews/stats.png) 24 | ![Preview Image](.github/previews/tickets.png) 25 | ![Preview Image](.github/previews/updateChecker.png) 26 | ![Preview Image](.github/previews/autocomplete.png) 27 | ![Preview Image](.github/previews/voucher.png) 28 | 29 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the changes and, if any, the related issue. Ideally also include relevant motivation and context. 4 | 5 | Fixes # (issue) 6 | 7 | ## Type of change 8 | 9 | - [ ] Bug fix (non-breaking change which fixes an issue) 10 | - [ ] New feature (non-breaking change which adds functionality) 11 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 12 | - [ ] This change requires a documentation update 13 | 14 | # Checklist: 15 | 16 | - [ ] My code follows the style guidelines of this project 17 | - [ ] I have performed a self-review of my own code 18 | - [ ] I have commented my code, particularly in hard-to-understand areas 19 | - [ ] I have made corresponding changes to the documentation 20 | - [ ] My changes generate no *new* warnings 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyRogue 2 | > ## **pyRogue** is a `educational` project. Not longer updated. 3 | 4 | > ### This project was alive before they released any ToC, Usage Policy's and such. Since they set down some policys, this project is no longer maintained or updated. Hence, the codebase may or may not work. 5 | > ### You accessing the API with this codebase is against they're usage policy's and ToS. Please read them thoroughly. 6 | 7 | ![Stars](https://img.shields.io/github/stars/rogueEdit/pyRogue?style=social) ![Watchers](https://img.shields.io/github/watchers/rogueEdit/pyRogue?style=social) ![GitHub Forks](https://img.shields.io/github/forks/rogueEdit/pyRogue?style=social) 8 | 9 | 10 | ![Release Version][Badge Release Version] ![Release Date][Badge Release Date] ![Docstring Coverage][Badge Docstring Coverage] ![Downloads][Badge Downloads] 11 | 12 | ![Badge Last Commit][Badge Last Commit] ![Badge Security Policy][Badge Security Policy] ![Badge Open Issues][Badge Open Issues] ![Badge Open Pull Requests][Badge Open Pull Requests] ![Badge Contributors][Badge Contributors] 13 | 14 | 15 | --- 16 | 17 | 18 | ![Preview Image](.github/previews/main.png) 19 | ![Preview Image](.github/previews/tool.png) 20 | 21 | [All Previews](PREVIEW.md) 22 | 23 | # Table of Contents 24 | - [Important Foreword](#important-foreword) 25 | - [FAQ](#faq) 26 | - [How to Run the Project](#how-to-run-the-project) 27 | - [Prerequisites](#prerequisites) 28 | - [Downloading the Source Code](#downloading-the-source-code) 29 | - [Option 1: Download and Extract](#option-1-download-and-extract) 30 | - [Option 2: Clone the Repository](#option-2-clone-the-repository) 31 | - [Running the Project](#running-the-project) 32 | - [Windows](#windows) 33 | - [Linux](#linux) 34 | - [macOS](#macos) 35 | - [License](#license) 36 | - [Reversed Stuff](#reversed-stuff) 37 | - [Regarding Bans and Limited Accounts](#regarding-bans-and-limited-accounts) 38 | 39 | # Important foreword 40 | 41 | We learned enough about freezing python to binarys so from here on out it will be source code only. 42 | 43 | We will not sent you any files or contact you about anything. You can see who contributed and everything regarding us will be only done on GitHub. We will not contact you in any matter or will send you files. There are scammers out there. Here you can read the full source code, compile it from scratch and such or download a VT-checked official release. 44 | 45 | Attention: When ever this tool detects you are trying to manipulate a daily seeded run it will abort. We only do this for educating us and provide the source code opensource in compliance with PokeRogue's License. 46 | 47 | - We take no responsibility for your actions when using this tool. Whenever you startup tho a backup is created and stand: 03.07.2024 - they are applicable no matter created when. 48 | 49 | - [Security Notice](TRANSPARENCY.md) 50 | 51 | # FAQ 52 | 53 | - How do i revert my changes? 54 | - The programm will always create backups everytime you login! When you load the first time it will create a `base_gameData(trainerID)_03.07.2024_18.03.22.json` unique based on your trainerID coupled with a timestamp. This applies for slot' data aswell; `backup_slotData(slotNumber_trainerID)_03.07.2024_18.03.22.json`. All subsequent backups will be prefixed with `backup_` and you can restore to any file back in time. 55 | 56 | ![Preview Image](.github/previews/backup.png) 57 | 58 | - Will this get me banned? 59 | - See [Regarding Bans and Limited Accounts](https://github.com/RogueEdit/onlineRogueEditor?tab=readme-ov-file#regarding-bans-and-limited-accounts) 60 | 61 | - Where can i donate? 62 | - We will not accept any money or any form of payment. If you want to help then only by contributing. We do it for education only, any critique welcome. 63 | 64 | --- 65 | 66 | # How to run from code 67 | ### Prerequisites 68 | - **Python**: Ensure that Python 3 is installed on your system. You can download it from [python.org](https://www.python.org/downloads/). 69 | 70 | ## Downloading the Source Code 71 | You can either download the source code as a ZIP file and extract it, or clone the repository using Git. 72 | 73 | ### Option 1: Download and Extract 74 | 1. Download the ZIP file containing the source code. 75 | 2. Extract the contents to your desired location. 76 | 77 | ### Option 2: Clone the Repository 78 | 1. Open a terminal or command prompt. 79 | 2. Use the following command to clone the repository, including submodules: 80 | ```bash 81 | git clone --recursive https://github.com/RogueEdit/pyRogue 82 | 83 | --- 84 | 85 | ## Running the Project 86 | 87 | > Some Enviroments use `python3` (Microsoft Store) and some need to write `py` only. 88 | 89 | ### Windows 90 | 1. **Navigate to the Source Directory**: 91 | - Open a terminal (Command Prompt or PowerShell). 92 | - Navigate to the source directory: 93 | ```bash 94 | cd [extracted_folder]/src/ 95 | ``` 96 | 2. **Install Dependencies**: 97 | - Use `pip` to install the required packages: 98 | ```bash 99 | python -m pip install -r requirements.txt 100 | ``` 101 | 3. **Run the Application**: 102 | - Run the main script: 103 | ```bash 104 | python main.py 105 | ``` 106 | 107 | --- 108 | 109 | ### Linux 110 | 1. **Navigate to the Source Directory**: 111 | - Open a terminal. 112 | - Navigate to the source directory: 113 | ```bash 114 | cd [extracted_folder]/src/ 115 | ``` 116 | 2. **Make the Main Script Executable**: 117 | - Use the following command to ensure the script is executable: 118 | ```bash 119 | chmod +x main.py 120 | ``` 121 | 3. **Install Dependencies**: 122 | - Use `pip` to install the required packages: 123 | ```bash 124 | python3 -m pip install -r requirements.txt 125 | ``` 126 | 4. **Run the Application**: 127 | - Execute the main script: 128 | ```bash 129 | ./main.py 130 | ``` 131 | 132 | --- 133 | 134 | ### macOS 135 | The steps for macOS are generally similar to those for Linux: 136 | 137 | 1. **Navigate to the Source Directory**: 138 | - Open Terminal. 139 | - Navigate to the source directory: 140 | ```bash 141 | cd [extracted_folder]/src/ 142 | ``` 143 | 2. **Make the Main Script Executable**: 144 | - Ensure the script is executable: 145 | ```bash 146 | chmod +x main.py 147 | ``` 148 | 3. **Install Dependencies**: 149 | - Use `pip` to install the required packages: 150 | ```bash 151 | python3 -m pip install -r requirements.txt 152 | ``` 153 | 4. **Run the Application**: 154 | - Execute the main script: 155 | ```bash 156 | ./main.py 157 | ``` 158 | 159 | --- 160 | 161 | # License 162 | 163 | - [Based on the Source Code of pokerogue.net](https://github.com/pagefaultgames/pokerogue) 164 | > In compliance with Pokerogue's License this project here is also released under AGPL3. 165 | 166 | No copyright or trademark infringement is intended in using Pokémon related names and IDs. 167 | Pokémon © 2002-2024 Pokémon. © 1995-2024 Nintendo/Creatures Inc./GAME FREAK inc. TM, ® and Pokémon character names are trademarks of Nintendo. 168 | 169 | --- 170 | 171 | # Reversed Stuff 172 | - Extensive logging for easy debug in a log file 173 | 174 | --- 175 | - When logging in it will automatically create backups for you. 176 | - You can restore backups easily see preview above 177 | --- 178 | - Change selected slot 179 | - This will fetch the chosen new slot_x.json containing your session save data 180 | --- 181 | - Edit a starter - This will ask you to take any input: 182 | 183 | ![Preview Image](.github/previews/editStarter.png) 184 | 185 | --- 186 | - Unlock all starters | same as above but for all pokemons 187 | - This will unlock every single Pokemon depending on your choosings like above 188 | 189 | ![alt text](.github/previews/starter.png) 190 | --- 191 | - Modify the number of egg-tickets you have 192 | - This allows you to set the amount of egg gacha tickets you have of every tier 193 | 194 | ![alt text](.github/previews/tickets.png) 195 | --- 196 | - Edit a pokemon in your party 197 | - Let's you edit g-max, fusions, moves, species, level, luck, fusion etc... 198 | 199 | ![grafik](.github/previews/editParty.png) 200 | 201 | --- 202 | - Item Editor 203 | 204 | ![Preview Image](.github/previews/itemEditor.png) 205 | 206 | --- 207 | - Unlock all game modes 208 | - Unlocks: classic, endless, spliced endless 209 | 210 | - Add one or unlock all 211 | - Vouchers 212 | 213 | ![Preview Image](.github/previews/voucher.png) 214 | 215 | - Achievements 216 | 217 | ![Preview Image](.github/previews/achievements.png) 218 | 219 | ![Preview Image](.github/previews/editAchievementsMin.png) 220 | 221 | --- 222 | - Edit amount of money 223 | - ![alt text](.github/previews/money.png) 224 | - Edit pokeballs amount 225 | - ![alt text](.github/previews/pokeballs.png) 226 | - Edit biome 227 | - Edit candies on a pokemon 228 | --- 229 | - Generate eggs 230 | - Depending on your liking, whatever rarity - gacha type and such 231 | 232 | ![preview](.github/previews/eggsManaphy.png) 233 | 234 | - Set your eggs to hatch 235 | - Edit account stats 236 | 237 | ![preview](.github/previews/stats.png) 238 | - Randomize all 239 | - Set all in a loop 240 | - Set specific ones 241 | 242 | ![preview](.github/previews/editStats.png) 243 | --- 244 | - Unlock everything 245 | - Just calls mulitiple features from above 246 | - Will also edit account stats with "legit" constraints. Based on your seen variables and such and randomized between reasonable values. 247 | --- 248 | - Display all Pokemon with their names and id 249 | - Display all Biomes IDs 250 | - Display all Moves IDs 251 | - Display all Voucher IDs 252 | - Display all Natures 253 | - Display all Nature Slot IDs 254 | - Save data to server via open accesible API calls 255 | 256 | ![alt text](.github/previews/fun1.png) 257 | 258 | # Regarding Bans and Limited Accounts 259 | https://www.reddit.com/r/pokerogue/comments/1d8hncf/cheats_and_exploits_post_followup_bannable/ 260 | 261 | https://www.reddit.com/r/pokerogue/comments/1d8ldlw/a_cheating_and_account_deletionwipe_followup/ 262 | 263 | 264 | 265 | 266 | [Badge Stars]: https://img.shields.io/github/stars/rogueEdit/pyRogue?style=social 267 | [Badge Watchers]: https://img.shields.io/github/watchers/rogueEdit/pyRogue?style=social 268 | [Badge Forks]: https://img.shields.io/github/forks/rogueEdit/pyRogue?style=social 269 | 270 | [Badge CodeQL]: https://img.shields.io/github/actions/workflow/status/rogueEdit/pyRogue/codeql.yml?branch=main&label=CodeQL&logo=github&logoColor=white&style=for-the-badge 271 | [Badge Ruff]: https://img.shields.io/github/actions/workflow/status/rogueEdit/pyRogue/codeql.yml?branch=main&label=Ruff%20Lint&logo=ruff&logoColor=white&style=for-the-badge 272 | 273 | [Badge Release Version]: https://img.shields.io/github/v/release/rogueEdit/pyRogue?style=for-the-badge&logo=empty 274 | [Badge Release Date]: https://img.shields.io/github/release-date/rogueEdit/pyRogue?style=for-the-badge&logo=empty 275 | [Badge Code Size]: https://img.shields.io/github/languages/code-size/rogueEdit/pyRogue?style=for-the-badge&logo=empty 276 | 277 | [Badge Last Commit]: https://img.shields.io/github/last-commit/rogueEdit/pyRogue?style=for-the-badge&logo=empty 278 | [Badge Security Policy]: https://img.shields.io/badge/Security-Policy-red.svg?style=for-the-badge&logo=empty 279 | [Badge Open Issues]: https://img.shields.io/github/issues-raw/rogueEdit/pyRogue?style=for-the-badge&logo=empty 280 | [Badge Open Pull Requests]: https://img.shields.io/github/issues-pr-raw/rogueEdit/pyRogue?style=for-the-badge&logo=empty 281 | [Badge Contributors]: https://img.shields.io/github/contributors/rogueEdit/pyRogue?style=for-the-badge&logo=empty 282 | [Badge Docstring Coverage]: https://img.shields.io/badge/docstr%20coverage-90%25-blue?style=for-the-badge&logo=empty 283 | 284 | [Badge Downloads]: https://img.shields.io/github/downloads/rogueEdit/pyRogue/total?style=for-the-badge&logo=empty 285 | [Badge License]: https://img.shields.io/github/license/rogueEdit/pyRogue?style=for-the-badge&logo=empty 286 | 287 | 288 | [MD Security]: ./SECURITY.md 289 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ---------------------- | ------------------ | 7 | | v0.4.8 | :white_check_mark: | 8 | | v0.4.8 | :white_check_mark: | 9 | | lesser than v0.4.7-h | :x: | 10 | 11 | 12 | ## We request in the web with a trusted Certificate 13 | - What calls to the internet do we do? 14 | - We call to: 15 | - `Starting new HTTPS connection (1): api.pokerogue.net:443` 16 | - and its endpoints for example 17 | - https://api.pokerogue.net:443 "POST /account/login HTTP/11" 200 None 18 | - CURL's hosted SSL certificate 19 | - https://curl.se/docs/caextract.html 20 | - Our GitHub repo 21 | - https://api.github.com:443 "GET /repositories/807308129/commits?since=[UTF DATE] HTTP/1.1" 200 2 22 | 23 | ![Preview image](.github/previews/networkResolution.png) 24 | --- 25 | ## WE DO NOT SAVE ANYTHING and do NOT send any analytics, nothing 26 | - Only thing we "save" locally is game related and specifically tool related: 27 | - `trainer.json` 28 | - any `slot_*.json` 29 | - any `backups/*.json` 30 | - The username and password are volatile and are deleted from memory and never stored once logged in 31 | - They are solely used to log in 32 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: https://github.com/claudiunderthehood 5 | # Date of release: 13.06.2024 6 | # Last Edited: 28.06.2024 7 | # Based on: https://github.com/pagefaultgames/pokerogue/ 8 | 9 | """ 10 | This script facilitates user login and session initialization for PokeRogue. It offers a menu-driven interface to 11 | perform various account and game data actions after a successful login using either requests or Selenium. 12 | 13 | Features: 14 | - User login through requests or Selenium. 15 | - Various account and game data actions through a menu-driven interface. 16 | - Custom logging and colored console output. 17 | 18 | Modules: 19 | - getpass: For securely obtaining the password from the user. 20 | - requests: For handling HTTP sessions and requests. 21 | - brotli: (Imported but not directly used in this script). 22 | - loginLogic: Custom module for handling login logic using requests. 23 | - Rogue: Custom module for initializing and interacting with the PokeRogue session. 24 | - SeleniumLogic: Custom module for handling login using Selenium. 25 | - cFormatter: Custom formatter for colored printing and logging. 26 | - Color: Enumeration defining color codes for cFormatter. 27 | - CustomLogger: Custom logging functionality. 28 | - config: Custom module for configuration and update checking. 29 | - datetime, timedelta: For date and time operations. 30 | - colorama: For terminal text color formatting. 31 | """ 32 | 33 | import getpass 34 | import requests 35 | import brotli # noqa: F401 36 | 37 | from modules import requestsLogic, Rogue, SeleniumLogic, config 38 | from modules.handler import OperationSuccessful, dec_handleOperationExceptions, OperationCancel, OperationSoftCancel 39 | from colorama import Fore, Style, init 40 | from utilities import cFormatter, Color, CustomLogger 41 | from datetime import datetime, timedelta 42 | from utilities import fh_printMessageBuffer 43 | from sys import exit 44 | init() 45 | logger = CustomLogger() 46 | 47 | if not config.debug: 48 | config.f_checkForUpdates(requests, datetime, timedelta, Style) 49 | 50 | 51 | @dec_handleOperationExceptions 52 | def m_executeOptions(choice_index, valid_choices): 53 | for idx, func in valid_choices: 54 | if idx == choice_index: 55 | func() 56 | break 57 | elif idx == 'exit': 58 | raise KeyboardInterrupt 59 | 60 | @dec_handleOperationExceptions 61 | def m_mainMenu(rogue, editOffline: bool = False): 62 | title = f'{config.title}>' 63 | useWhenDone = f'{Fore.LIGHTYELLOW_EX}(Use when Done)' 64 | reworked = f'{Fore.GREEN}(REWORKED)' 65 | 66 | term = [ 67 | (title, 'title'), 68 | ('Account Actions', 'category'), 69 | ((f'{Fore.YELLOW}Create a backup', reworked), rogue.f_createBackup), 70 | ((f'{Fore.YELLOW}Recover your backup', reworked), rogue.f_restoreBackup), 71 | (('Load Game-Data from server', reworked), rogue.f_getGameData), 72 | (('Change save-slot to edit', reworked), rogue.f_changeSaveSlot), 73 | (('Edit account stats', reworked), rogue.f_editAccountStats), 74 | 75 | ('Edits', 'category'), 76 | ((f'{Fore.YELLOW}Create eggs', reworked), rogue.f_addEggsGenerator), 77 | ((f'Edit {Fore.YELLOW}Egg-hatch durations', reworked), rogue.f_editHatchWaves), 78 | ((f'Edit {Fore.YELLOW}egg-tickets', reworked), rogue.f_addTicket), 79 | ((f'Edit {Fore.YELLOW}a starter', reworked), rogue.f_editStarter), 80 | ((f'Edit {Fore.YELLOW}candies{Style.RESET_ALL} on a starter', reworked), rogue.f_addCandies), 81 | 82 | ('Unlocks', 'category'), 83 | ((f'Unlock {Fore.YELLOW}achievements', reworked), rogue.f_unlockAchievements), 84 | ((f'Unlock {Fore.YELLOW}vouchers', reworked), rogue.f_unlockVouchers), 85 | ((f'Unlock {Fore.YELLOW}all starters', reworked), rogue.f_unlockStarters), 86 | ((f'Unlock {Fore.YELLOW}all gamemodes', reworked), rogue.f_unlockGamemodes), 87 | ((f'Unlock {Fore.YELLOW}Everything', reworked), rogue.f_unlockAllCombined), 88 | 89 | ('Session Data Actions', 'category'), 90 | ((f'Edit {Fore.YELLOW}current Party', reworked), rogue.f_editParty), 91 | ((f'Edit {Fore.YELLOW}money amount', reworked), rogue.f_editMoney), 92 | ((f'Edit {Fore.YELLOW}pokeballs amount', reworked), rogue.f_editPokeballs), 93 | ((f'Edit {Fore.YELLOW}current biome', reworked), rogue.f_editBiome), 94 | ((f'Edit {Fore.YELLOW}Items', reworked), rogue.f_submenuItemEditor), 95 | 96 | ('Print game information', 'category'), 97 | (('Show all Species ID', reworked), rogue.legacy_pokedex), 98 | (('Show all Biome IDs', reworked), rogue.legacy_printBiomes), 99 | (('Show all Move IDs', reworked), rogue.legacy_moves), 100 | (('Show all Vouchers IDs', reworked), rogue.legacy_vouchers), 101 | (('Show all Natures IDs', reworked), rogue.legacy_natures), 102 | (('Show all NaturesSlot IDs', reworked), rogue.legacy_natureSlot), 103 | 104 | ('You can always edit your JSON manually as well!', 'helper'), 105 | ((f'{Fore.YELLOW}Save data and upload to the Server', useWhenDone), rogue.f_updateAllToServer), 106 | (('Print help and program information', ''), config.f_printHelp), 107 | (('Logout', ''), rogue.f_logout), 108 | (title, 'title') 109 | ] 110 | if editOffline or config.debug: 111 | # Filter entrys that would break offline 112 | term = [entry for entry in term if entry[1] != rogue.f_updateAllToServer] 113 | term = [entry for entry in term if entry[1] != rogue.f_getGameData] 114 | term = [entry for entry in term if entry[1] != rogue.f_logout] 115 | replaceEntry = ('Offline-Edits are directly applied', 'helper') 116 | term = [replaceEntry if entry == ('You can always edit your JSON manually as well!', 'helper') else entry for entry in term] 117 | 118 | try: 119 | while True: 120 | validChoices = cFormatter.m_initializeMenu(term) 121 | fh_printMessageBuffer() 122 | userInput = input('Command: ').strip().lower() 123 | 124 | if userInput == 'exit': 125 | raise KeyboardInterrupt 126 | if userInput == 'lb': 127 | rogue.f_lb() 128 | 129 | if userInput.isdigit() and int(userInput) <= len(validChoices): 130 | choiceIndex = int(userInput) 131 | m_executeOptions(choiceIndex, validChoices) 132 | 133 | except OperationSuccessful as os: 134 | cFormatter.print(Color.DEBUG, f'Operation successful: {os}') 135 | except KeyboardInterrupt: 136 | cFormatter.print(Color.DEBUG, '\nProgram interrupted by user.') 137 | exit() 138 | 139 | @dec_handleOperationExceptions 140 | def main(): 141 | if config.debug: 142 | rogue = Rogue(requests.session(), 'Invalid Auth Token', config.debug) 143 | m_mainMenu(rogue) 144 | else: 145 | while True: 146 | try: 147 | config.f_printWelcomeText() 148 | loginChoice = int(input('Please choose a method of logging in: ')) 149 | if loginChoice not in [1, 2, 3, 4]: 150 | cFormatter.print(Color.DEBUG, 'Please choose a valid option.') 151 | continue # Prompt user again if choice is not valid 152 | 153 | if loginChoice != 4: 154 | username = input('Username: ') 155 | password = getpass.getpass('Password (password is hidden): ') 156 | 157 | 158 | session = requests.Session() 159 | if loginChoice == 1: 160 | login = requestsLogic(username, password) 161 | try: 162 | if login.login(): 163 | cFormatter.print(Color.INFO, f'Logged in as: {config.f_anonymizeName(username)}') 164 | session.cookies.set('pokerogue_sessionId', login.sessionId, domain='pokerogue.net') 165 | rogue = Rogue(session, login.token, login.sessionId) 166 | break 167 | except Exception as e: 168 | cFormatter.print(Color.CRITICAL, f'Something went wrong. {e}', isLogging=True) 169 | 170 | elif loginChoice in [2, 3]: 171 | if loginChoice == 3: 172 | cFormatter.print(Color.INFO, 'Do not close your browser and do not browse in the game!') 173 | cFormatter.print(Color.INFO, 'Do not close your browser and do not browse in the game!') 174 | cFormatter.print(Color.INFO, 'Do not close your browser and do not browse in the game!') 175 | seleniumLogic = SeleniumLogic(username, password, 120, useScripts=(loginChoice == 3)) 176 | sessionId, token, driver = seleniumLogic.logic() 177 | 178 | if sessionId and token: 179 | if not driver: 180 | driver = None 181 | print('Driver error') 182 | cFormatter.print(Color.INFO, f'Logged in as: {config.f_anonymizeName(username)}') 183 | session.cookies.set('pokerogue_sessionId', sessionId, domain='pokerogue.net') 184 | rogue = Rogue(session, authToken=token, clientSessionId=sessionId, driver=driver, useScripts=(loginChoice == 3)) 185 | break 186 | else: 187 | cFormatter.print(Color.CRITICAL, 'Failed to retrieve necessary authentication data from Selenium.') 188 | 189 | 190 | elif loginChoice == 4: 191 | rogue = Rogue(session, authToken='Invalid Auth Token', editOffline=True) 192 | break 193 | 194 | else: 195 | cFormatter.print(Color.CRITICAL, 'Invalid choice. Please choose a valid method.') 196 | 197 | except KeyboardInterrupt: 198 | exit() 199 | if loginChoice != 4: 200 | del username, password 201 | m_mainMenu(rogue, editOffline=(loginChoice == 4)) 202 | 203 | if __name__ == '__main__': 204 | while True: 205 | try: 206 | main() 207 | except OperationSuccessful as os: 208 | cFormatter.print(Color.DEBUG, f'Operation successful: {os}') 209 | except KeyboardInterrupt: 210 | cFormatter.print(Color.DEBUG, '\nProgram interrupted by user.') 211 | exit() 212 | except OperationCancel: 213 | cFormatter.print(Color.DEBUG, '\nProgram interrupted by user.') 214 | exit() 215 | except OperationSoftCancel: 216 | cFormatter.print(Color.DEBUG, '\nProgram interrupted by user.') 217 | exit() 218 | 219 | 220 | -------------------------------------------------------------------------------- /src/modules/__init__.py: -------------------------------------------------------------------------------- 1 | from . import config 2 | from .requestsLogic import requestsLogic, HeaderGenerator, fh_handleErrorResponse 3 | from .mainLogic import Rogue 4 | from .seleniumLogic import SeleniumLogic 5 | from .itemLogic import ModifierEditor 6 | from .handler import dec_handleOperationExceptions, OperationSuccessful, OperationCancel, OperationError, PropagateResponse, OperationSoftCancel 7 | from .handler import dec_handleHTTPExceptions, HTTPEmptyResponse 8 | from .handler import fh_getChoiceInput, fh_getCompleterInput, fh_getIntegerInput 9 | from .data import dataParser 10 | 11 | __all__ = [ 12 | 'config', 13 | 'requestsLogic', 'HeaderGenerator', 'fh_handleErrorResponse', 14 | 'Rogue', 'SeleniumLogic', 15 | 'ModifierEditor', 16 | 17 | # CustomExceptions 18 | 'dec_handleOperationExceptions', 'OperationSuccessful', 'OperationCancel', 'OperationError', 'PropagateResponse', 'OperationSoftCancel', 19 | 'dec_handleHTTPExceptions', 'HTTPEmptyResponse', 20 | 'fh_getChoiceInput', 'fh_getCompleterInput', 'fh_getIntegerInput', 21 | 'dataParser' 22 | ] -------------------------------------------------------------------------------- /src/modules/config.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Authors 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | """ 9 | Online Rogue Editor Update Checker and Initialization 10 | 11 | This script checks for updates on a GitHub repository and initializes necessary directories 12 | for logging and backups if they do not already exist. 13 | 14 | Modules: 15 | - requests: HTTP library for sending GET and POST requests to GitHub's API. 16 | - datetime: Provides classes for manipulating dates and times. 17 | - timedelta: Represents a duration, the difference between two dates or times. 18 | - utilities.cFormatter: Custom formatter for printing colored console output. 19 | - os: Provides functions for interacting with the operating system, such as creating directories. 20 | 21 | Workflow: 22 | 1. Initialize necessary directories (logs, backups, data) if they do not exist. 23 | 2. Check for updates on the GitHub repository using `check_for_updates` function. 24 | 3. Print initialization messages and helpful information using `initialize_text` and `print_help` functions. 25 | """ 26 | 27 | import os 28 | from datetime import datetime, timedelta 29 | import requests 30 | # need to manually do it to avoid circular imports 31 | from colorama import Fore, Style, init 32 | 33 | init(autoreset=True) 34 | 35 | logsDirectory: str = os.path.join(os.getcwd(), 'logs') 36 | backupDirectory: str = os.path.join(os.getcwd(), 'backups') 37 | dataDirectory: str = os.path.join(os.getcwd(), 'data') 38 | timestampFile: str = os.path.join(dataDirectory, 'extra.json') 39 | 40 | if not os.path.exists(logsDirectory): 41 | os.makedirs(logsDirectory) 42 | print(f'{Fore.GREEN}Created logs directory: {logsDirectory}') 43 | # Create the backups directory if it doesn't exist 44 | if not os.path.exists(backupDirectory): 45 | os.makedirs(backupDirectory) 46 | print(f'{Fore.GREEN}Created backup directory: {backupDirectory}') 47 | if not os.path.exists(dataDirectory): 48 | os.makedirs(dataDirectory) 49 | print(f'{Fore.GREEN}Created data directory: {dataDirectory}') 50 | 51 | 52 | # Settings this to true will deactivate backups, skip prompts and use offline mode automatically 53 | debug: bool = False 54 | debugDeactivateBackup: bool = False if debug else False 55 | debugEnableTraceback: bool = True if debug else False 56 | 57 | cacertURL = 'https://curl.se/ca/cacert.pem' 58 | cacertPath = f'{dataDirectory}/cacert.pem' 59 | if not os.path.exists(cacertPath): 60 | print(f'{Fore.RED}\ncacert.pem not found. This is needed for SSL Connections. \n Fetching from {cacertURL}...{Style.RESET_ALL}') 61 | print(f'{Fore.RED}\nIf it is your first time starting up that is normal.{Style.RESET_ALL}') 62 | # Fetch the file using requests library 63 | response = requests.get(cacertURL) 64 | 65 | # Check if the request was successful 66 | if response.status_code == 200: 67 | # Save the content to local file 68 | with open(cacertPath, 'wb') as f: 69 | f.write(response.content) 70 | print(f'{Fore.GREEN}Successfully fetched {cacertURL} and saved as {cacertPath}.{Style.RESET_ALL}') 71 | else: 72 | print(f'Failed to fetch {cacertURL}. \n Status code: {response.status_code}. \n Cannot use SSL but the program might work.') 73 | cacertPath = False 74 | 75 | useCaCert = False if debug else cacertPath 76 | version: str = 'v0.4.8p' 77 | title: str = f'<(^.^(< pyRogue {version} >)^.^)>' 78 | owner: str = 'rogueEdit' 79 | repo: str = 'onlineRogueEditor' 80 | repoURL: str = f'https://github.com/{owner}/{repo}/' 81 | releaseDate: str = '19.07.2024 23:00' # releaed 20:00 roughly but setting ahead in case some stuff pops up 82 | 83 | 84 | def f_checkForUpdates(requests: requests, datetime: datetime, timedelta: timedelta, Style: object) -> None: 85 | """ 86 | Check for updates on the GitHub repository since a specified release date. 87 | 88 | Args: 89 | requests (requests): HTTP library for sending requests to GitHub's API. 90 | datetime (datetime): Module for date and time manipulation. 91 | timedelta (timedelta): Represents a duration, the difference between two dates or times. 92 | Style (object): Object representing a formatting style (not used in this function). 93 | 94 | Usage Example: 95 | >>> check_for_updates(requests, datetime, timedelta, Style) 96 | 97 | Output Example: 98 | - Prints commit details if updates are found. 99 | - Provides a URL to view the latest code. 100 | - Advises updating the source code if updates are found. 101 | 102 | Modules/Librarys used and for what purpose exactly in each function: 103 | - requests: Sends HTTP GET requests to retrieve commit history from GitHub repository. 104 | - datetime: Converts release date to ISO 8601 format for GitHub API query. 105 | - timedelta: Calculates local timezone offset for converting release date to UTC. 106 | - utilities.cFormatter: Prints colored console output for displaying update details. 107 | """ 108 | def f_convertToISOFormat(date_string: str, timedelta: timedelta) -> str: 109 | """ 110 | Convert a date string to ISO 8601 format in UTC timezone. 111 | 112 | Args: 113 | date_string (str): Date string in format 'dd.mm.yyyy HH:MM'. 114 | timedelta (timedelta): Represents a duration, the difference between two dates or times. 115 | 116 | Returns: 117 | str: ISO 8601 formatted date string in UTC timezone. 118 | 119 | Raises: 120 | ValueError: If the input date format is incorrect. 121 | 122 | Usage Example: 123 | >>> convert_to_iso_format('20.06.2024 6:00', timedelta) 124 | 125 | Modules/Librarys used and for what purpose exactly in each function: 126 | - datetime: Parses and formats the input date string. 127 | """ 128 | # Parse the input date string 129 | dateFormat = '%d.%m.%Y %H:%M' 130 | try: 131 | dt = datetime.strptime(date_string, dateFormat) 132 | except ValueError as e: 133 | raise ValueError("Incorrect date format, should be 'dd.mm.yyyy HH:MM'") from e 134 | 135 | # Determine local timezone offset for Central European Time (CET) 136 | isDST = datetime.now().timetuple().tm_isdst 137 | timezoneOffset = timedelta(hours=2) if isDST else timedelta(hours=1) 138 | 139 | # Apply local timezone offset to convert to UTC 140 | utcDT = dt - timezoneOffset 141 | 142 | # Format datetime object to ISO 8601 format with UTC timezone 'Z' (Zulu time) 143 | isoFormat = utcDT.strftime('%Y-%m-%dT%H:%M:%SZ') 144 | 145 | return isoFormat 146 | 147 | try: 148 | # Convert release date to ISO 8601 format 149 | check_date = datetime.fromisoformat(f_convertToISOFormat(releaseDate, timedelta)) 150 | 151 | # Construct GitHub API URL and parameters 152 | url = f'https://api.github.com/repos/{owner}/{repo}/commits' 153 | params = {'since': check_date.isoformat()} 154 | 155 | # Send GET request to GitHub API 156 | response = requests.get(url, params=params) 157 | response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx) 158 | 159 | commits = response.json() # Parse JSON response 160 | 161 | # Extract commit titles and SHAs 162 | commitList = [{'sha': commit["sha"], 'message': commit["commit"]["message"]} for commit in commits] 163 | 164 | if commitList: 165 | print(f'{Fore.YELLOW}********* Outdated source code found. New commits: *********{Style.RESET_ALL}') 166 | for commit in commitList: 167 | print(f'{Fore.YELLOW}---- Commit Name: ({commit["message"]}{Style.RESET_ALL})') 168 | print(f'{Fore.BLUE}------> with SHA ({commit["sha"]}{Style.RESET_ALL})') 169 | print(f'{Fore.YELLOW}You can view the latest code here: {repoURL}{Style.RESET_ALL}') 170 | print(f'{Fore.YELLOW}It is highly recommended to update the source code. Some things might not be working as expected.{Style.RESET_ALL}') 171 | print(f'{Fore.YELLOW}------------------------------------------------------------{Style.RESET_ALL}') 172 | else: 173 | print(f'{Fore.GREEN}No updates found.') 174 | 175 | except ValueError as ve: 176 | print(f'{Fore.RED}Couldnt resolve check_for_updates() - ValueError occurred: {ve}') 177 | except requests.exceptions.RequestException as re: 178 | print(f'{Fore.RED}Couldnt resolve check_for_updates() - RequestException occurred: {re}') 179 | except Exception as e: 180 | print(f'{Fore.RED}Couldnt resolve check_for_updates() - An unexpected error occurred: {e}') 181 | 182 | def f_printWelcomeText() -> None: 183 | """ 184 | Print initialization messages for the program. 185 | 186 | This function prints messages regarding program initialization, network settings, and program version. 187 | 188 | Usage Example: 189 | >>> initialize_text() 190 | 191 | Modules/Librarys used and for what purpose exactly in each function: 192 | - utilities.cFormatter: Prints colored console output for initialization messages. 193 | """ 194 | print(f'{Fore.GREEN}') 195 | print(f'{Fore.GREEN}We create base-backups on every login and further backups every time you start or choose so manually.') 196 | print(f'{Fore.GREEN}When changes do not seem to apply, refresh without cache / use a private tab.') 197 | print(f'{Fore.GREEN}Otherwise please visit {repoURL} and report the issue.') 198 | print(f'{Fore.YELLOW}Please refer to SECURITY.md if you have security concerns.') 199 | print('------------------------------------------------------------') 200 | print(f'{Fore.MAGENTA}{Style.BRIGHT}1: Using no browser with requests.') 201 | print(f'{Fore.MAGENTA}{Style.BRIGHT}2: Using own browser with requests.') 202 | print(f'{Fore.MAGENTA}{Style.BRIGHT}3: Using own browser with JavaScript.') 203 | print(f'{Fore.MAGENTA}{Style.BRIGHT}4: Just edit an existing trainer.json') 204 | 205 | def f_printHelp() -> None: 206 | """ 207 | Print helpful information for the user. 208 | 209 | This function prints various helpful messages for the user, including information 210 | about manual JSON editing, assistance through the program's GitHub page, release 211 | version details, and cautions about account safety and program authenticity. 212 | 213 | Usage Example: 214 | >>> print_help() 215 | 216 | Modules/Librarys used and for what purpose exactly in each function: 217 | - utilities.cFormatter: Prints colored console output for help messages. 218 | """ 219 | print(f'{Fore.YELLOW}You can always edit your JSON manually as well.') 220 | print(f'{Fore.YELLOW}If you need assistance, please refer to the program\'s GitHub page.') 221 | print(f'{Fore.YELLOW}{repoURL}') 222 | print(f'{Fore.YELLOW}This is release version {version} - please include that in your issue or question report.') 223 | print(f'{Fore.YELLOW}This version now also features a log file.') 224 | print(f'{Fore.YELLOW}We do not take responsibility if your accounts get flagged or banned, and') 225 | print(f'{Fore.YELLOW}you never know if there is a clone of this program. If you are not sure, please') 226 | print(f'{Fore.YELLOW}calculate the checksum of this binary and visit {repoURL}') 227 | print(f'{Fore.YELLOW}to see the value it should have to know it\'s original from source.') 228 | 229 | def f_anonymizeName(username): 230 | if len(username) < 3: # If username length is less than 3, return as is (minimum 2 characters) 231 | return username 232 | 233 | visibleChars = max(int(len(username) * 0.2), 1) # Calculate how many characters to leave visible 234 | startVisible = max(visibleChars // 2, 1) # At least 1 character visible from the start 235 | endVisible = visibleChars - startVisible # Remaining visible characters from the end 236 | 237 | # Construct the masked username 238 | maskedUsername = username[:startVisible] + '*' * (len(username) - startVisible - endVisible) 239 | 240 | return maskedUsername 241 | -------------------------------------------------------------------------------- /src/modules/data/__init__.py: -------------------------------------------------------------------------------- 1 | from . import dataParser 2 | 3 | __all__ = [ 4 | 'dataParser' 5 | ] -------------------------------------------------------------------------------- /src/modules/data/dataParser.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Authors 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | # Unlike the other code, reusing this in your own project is forbidden. 9 | 10 | import json 11 | from enum import Enum 12 | from dataclasses import dataclass, field, asdict 13 | from typing import List, Optional, Any, Dict, Union 14 | from modules.config import dataDirectory 15 | from colorama import Fore, Style 16 | 17 | def __createEnum(name, values): 18 | return Enum(name, values) 19 | 20 | def __modifiySpeciesName(name): 21 | return name.replace('_', ' ').title() 22 | 23 | with open(f'{dataDirectory}/hasForms.json') as f: 24 | hasForms = json.load(f)["hasForms"] 25 | 26 | with open(f'{dataDirectory}/species.json') as f: 27 | dexEnum = json.load(f)["dex"] 28 | 29 | with open(f'{dataDirectory}/noPassive.json') as f: 30 | noPassive = json.load(f)["noPassive"] 31 | 32 | with open(f'{dataDirectory}/starter.json') as f: 33 | startersList = json.load(f)["dex"] 34 | 35 | Dex = __createEnum('Dex', {name.capitalize(): id_ for name, id_ in dexEnum.items()}) 36 | noPassiveSet = {int(id_) for id_ in noPassive.keys()} 37 | startersSet = {dexEnum[name] for name in startersList} 38 | 39 | class DexAttr(Enum): 40 | NON_SHINY = 1 41 | SHINY = 2 42 | MALE = 4 43 | FEMALE = 8 44 | VARIANT_1 = 16 45 | VARIANT_2 = 32 46 | VARIANT_3 = 64 47 | DEFAULT_FORM = 128 48 | 49 | @dataclass 50 | class Modifier: 51 | args: List[Optional[Union[int, bool]]] 52 | className: Optional[str] 53 | player: Optional[bool] 54 | stackCount: Optional[int] 55 | typeId: Optional[str] 56 | typePregenArgs: Optional[List[Optional[int]]] 57 | 58 | def toDict(self): 59 | return asdict(self) 60 | 61 | @dataclass 62 | class ModifierEnemyData: 63 | modifiers: List[Optional[Modifier]] 64 | 65 | def toDict(self): 66 | return asdict(self) 67 | 68 | @dataclass 69 | class ModifierPlayerData: 70 | modifiers: List[Optional[Modifier]] 71 | 72 | @dataclass 73 | class Move: 74 | moveId: Optional[int] = None 75 | ppUp: Optional[int] = None 76 | ppUsed: Optional[int] = None 77 | virtual: Optional[bool] = None 78 | 79 | def toDict(self): 80 | return asdict(self) 81 | 82 | @dataclass 83 | class PartySummonData: 84 | abilitiesApplied: Optional[Any] = None 85 | ability: Optional[int] = None 86 | abilitySuppressed: Optional[bool] = None 87 | battleStats: List[Optional[int]] = field(default_factory=lambda: [None, None, None, None, None, None, None]) 88 | disabledMove: Optional[int] = None 89 | disabledTurns: Optional[int] = None 90 | moveQueue: Optional[Any] = None 91 | tags: Optional[Any] = None 92 | types: Optional[Any] = None 93 | 94 | def toDict(self): 95 | return asdict(self) 96 | 97 | @dataclass 98 | class PartyDetails: 99 | abilityIndex: Optional[int] = None 100 | boss: Optional[bool] = None 101 | exp: Optional[int] = None 102 | formIndex: Optional[int] = None 103 | friendship: Optional[int] = None 104 | fusionFormIndex: Optional[int] = None 105 | fusionLuck: Optional[int] = None 106 | fusionShiny: Optional[int] = None 107 | fusionSpecies: Optional[int] = None 108 | fusionVariant: Optional[int] = None 109 | gender: Optional[int] = None 110 | hp: Optional[int] = None 111 | id: Optional[int] = None 112 | ivs: List[Optional[int]] = field(default_factory=lambda: [None, None, None, None, None, None]) 113 | level: Optional[int] = None 114 | levelExp: Optional[int] = None 115 | luck: Optional[int] = None 116 | metBiome: Optional[int] = None 117 | metLevel: Optional[int] = None 118 | moveset: List[Move] = field(default_factory=lambda: [Move(), Move(), Move(), Move()]) 119 | nature: Optional[int] = None 120 | natureOverride: Optional[int] = None 121 | passive: Optional[bool] = None 122 | pauseEvolutions: Optional[bool] = None 123 | player: Optional[bool] = None 124 | pokeball: Optional[int] = None 125 | pokerus: Optional[bool] = None 126 | shiny: Optional[bool] = None 127 | species: Optional[int] = None 128 | stats: List[Optional[int]] = field(default_factory=lambda: [None, None, None, None, None, None]) 129 | summonData: PartySummonData = field(default_factory=PartySummonData) 130 | variant: Optional[int] = None 131 | 132 | def toDict(self): 133 | return asdict(self) 134 | 135 | @dataclass 136 | class PartyPlayer: 137 | partyInfo: Optional[PartyDetails] = field(default_factory=PartyDetails) 138 | partyData: Optional[PartySummonData] = field(default_factory=PartySummonData) 139 | 140 | def toDict(self): 141 | return asdict(self) 142 | 143 | @dataclass 144 | class PartyEnemy: 145 | partyInfo: Optional[PartyDetails] = field(default_factory=PartyDetails) 146 | partyData: Optional[PartySummonData] = field(default_factory=PartySummonData) 147 | 148 | def toDict(self): 149 | return asdict(self) 150 | 151 | @dataclass 152 | class SpeciesDexData: 153 | seenAttr: int = 0 154 | caughtAttr: int = 0 155 | natureAttr: int = 0 156 | seenCount: int = 0 157 | caughtCount: int = 0 158 | hatchedCount: int = 0 159 | ivs: List[int] = field(default_factory=lambda: [0, 0, 0, 0, 0, 0]) 160 | 161 | def toDict(self): 162 | return asdict(self) 163 | 164 | @dataclass 165 | class SpeciesStarterData: 166 | moveset: Optional[List[int]] = field(default_factory=lambda: []) 167 | eggMoves: Optional[int] = None 168 | candyCount: Optional[int] = 0 169 | friendship: Optional[int] = 0 170 | abilityAttr: Optional[int] = 0 171 | passiveAttr: Optional[int] = 0 172 | valueReduction: Optional[int] = 0 173 | classicWinCount: Optional[int] = 0 174 | 175 | def toDict(self): 176 | return asdict(self) 177 | 178 | @dataclass 179 | class SpeciesForm: 180 | name: str 181 | variant1: Optional[int] = None 182 | variant2: Optional[int] = None 183 | variant3: Optional[int] = None 184 | nonShiny: Optional[int] = None 185 | index: int = 0 186 | 187 | def toDict(self): 188 | return asdict(self) 189 | 190 | @dataclass 191 | class Species: 192 | name: str 193 | dex: int 194 | forms: List[SpeciesForm] 195 | hasPassive: bool 196 | isStarter: bool 197 | isNormalForm: bool 198 | 199 | # User Data 200 | # put starterData and dexData here 201 | 202 | def __post_init__(self): 203 | self.formMap = {form.name: form for form in self.forms} 204 | 205 | def getFormAttribute(self, formName: str, attribute: str) -> Optional[int]: 206 | form = self.formMap.get(formName) 207 | if form: 208 | return getattr(form, attribute, None) 209 | else: 210 | return None 211 | 212 | def toDict(self): 213 | return asdict(self) 214 | 215 | def computeVariant(speciesData, variantFlag, defaultFlag, variantAdjustment): 216 | caughtAttr = {} 217 | 218 | for speciesID, speciesInfo in speciesData.items(): 219 | caughtAttr[speciesID] = {} 220 | 221 | for speciesName, forms in speciesInfo.items(): 222 | if speciesName == "isNormalForm": 223 | continue 224 | 225 | formAttributes = {} 226 | combinedCaughtAttr = { 227 | "variant1": 31, 228 | "variant2": 63, 229 | "variant3": 127, 230 | "nonShiny": 255 231 | } 232 | 233 | for index, formName in enumerate(forms): 234 | formFlag = defaultFlag | (1 << (index + 7)) 235 | formCaughtAttr = 255 | formFlag | variantFlag 236 | 237 | adjustedFormCaughtAttr = formCaughtAttr - variantAdjustment 238 | formAttributes[formName] = adjustedFormCaughtAttr 239 | 240 | combinedCaughtAttr["variant1"] |= adjustedFormCaughtAttr 241 | combinedCaughtAttr["variant2"] |= adjustedFormCaughtAttr 242 | combinedCaughtAttr["variant3"] |= adjustedFormCaughtAttr 243 | combinedCaughtAttr["nonShiny"] |= adjustedFormCaughtAttr 244 | 245 | caughtAttr[speciesID][speciesName] = formAttributes 246 | 247 | caughtAttr[speciesID]["Combined"] = { 248 | "variant1": combinedCaughtAttr["variant1"] + 128, 249 | "variant2": combinedCaughtAttr["variant2"] + 128, 250 | "variant3": combinedCaughtAttr["variant3"] + 128, 251 | "nonShiny": combinedCaughtAttr["nonShiny"] + 128 252 | } 253 | 254 | return caughtAttr 255 | 256 | variant1CaughtAttr = computeVariant(hasForms, DexAttr.VARIANT_1.value, DexAttr.DEFAULT_FORM.value, 224) 257 | variant2CaughtAttr = computeVariant(hasForms, DexAttr.VARIANT_2.value, DexAttr.DEFAULT_FORM.value, 192) 258 | variant3CaughtAttr = computeVariant(hasForms, DexAttr.VARIANT_3.value, DexAttr.DEFAULT_FORM.value, 128) 259 | nonShinyCaughtAttr = computeVariant(hasForms, DexAttr.NON_SHINY.value, DexAttr.DEFAULT_FORM.value, 255) 260 | 261 | specieses = [] 262 | speciesDict = {} 263 | 264 | for speciesName, speciesId in dexEnum.items(): 265 | modifiedName = __modifiySpeciesName(speciesName) 266 | hasPassive = int(speciesId) not in noPassiveSet 267 | isStarter = speciesId in startersSet 268 | speciesIdString = str(speciesId) 269 | 270 | forms = [] 271 | isNormalForm = False 272 | if speciesIdString in hasForms: 273 | formNames = hasForms[speciesIdString].get(modifiedName, []) 274 | isNormalForm = hasForms[speciesIdString].get("isNormalForm", False) 275 | combinedCaughtAttr = { 276 | "variant1": 31, 277 | "variant2": 63, 278 | "variant3": 127, 279 | "nonShiny": 255 280 | } 281 | for index, formName in enumerate(formNames): 282 | form = SpeciesForm( 283 | name=formName, 284 | variant1=variant1CaughtAttr[speciesIdString][modifiedName][formName], 285 | variant2=variant2CaughtAttr[speciesIdString][modifiedName][formName], 286 | variant3=variant3CaughtAttr[speciesIdString][modifiedName][formName], 287 | nonShiny=nonShinyCaughtAttr[speciesIdString][modifiedName][formName], 288 | index=index 289 | ) 290 | forms.append(form) 291 | combinedCaughtAttr["variant1"] |= form.variant1 292 | combinedCaughtAttr["variant2"] |= form.variant2 293 | combinedCaughtAttr["variant3"] |= form.variant3 294 | combinedCaughtAttr["nonShiny"] |= form.nonShiny 295 | 296 | # Add the imaginary "Combined" form with proper variant values 297 | forms.append(SpeciesForm( 298 | name="Combined", 299 | variant1=combinedCaughtAttr["variant1"] + 128, 300 | variant2=combinedCaughtAttr["variant2"] + 128, 301 | variant3=combinedCaughtAttr["variant3"] + 128, 302 | nonShiny=combinedCaughtAttr["nonShiny"] + 128, 303 | index=len(forms) 304 | )) 305 | 306 | species = Species( 307 | name=modifiedName, 308 | dex=int(speciesId), 309 | forms=forms, 310 | hasPassive=hasPassive, 311 | isStarter=isStarter, 312 | isNormalForm=isNormalForm 313 | ) 314 | specieses.append(species) 315 | speciesDict[speciesName] = species 316 | speciesDict[speciesId] = species 317 | 318 | @dataclass 319 | class SessionData: 320 | seed: Optional[str] = None 321 | playTime: Optional[int] = 0 322 | gameMode: Optional[int] = 0 323 | party: Optional[PartyPlayer] = field(default_factory=PartyPlayer) 324 | enemyParty: Optional[PartyEnemy] = field(default_factory=PartyEnemy) 325 | playerModifier: Optional[ModifierPlayerData] = field(default_factory=ModifierPlayerData) 326 | enemyModifier: Optional[ModifierEnemyData] = field(default_factory=ModifierEnemyData) 327 | arena: Optional[Dict[str, Union[int, None]]] = field(default_factory=lambda: {"biome": 0, "tags": None}) 328 | pokeballCounts: Optional[Dict[str, Optional[int]]] = field(default_factory=lambda: {"0": 5, "1": 0, "2": 0, "3": 0, "4": 0}) 329 | money: Optional[int] = None 330 | score: Optional[int] = None 331 | victoryCount: Optional[int] = None 332 | faintCount: Optional[int] = None 333 | reviveCount: Optional[int] = None 334 | waveIndex: Optional[int] = None 335 | battleType: Optional[int] = None 336 | trainer: Optional[int] = None 337 | gameVersion: Optional[str] = None 338 | timestamp: Optional[int] = None 339 | challenges: Optional[Dict[str, None]] = None 340 | 341 | def toDict(self): 342 | return asdict(self) 343 | 344 | 345 | @dataclass 346 | class TrainerData: 347 | trainerId: Optional[int] = None 348 | secretId: Optional[int] = None 349 | gender: Optional[int] = None 350 | dexData: Optional[SpeciesDexData] = field(default_factory=SpeciesDexData) 351 | starterData: Optional[SpeciesStarterData] = field(default_factory=SpeciesStarterData) 352 | starterMoveData: Optional[List[int]] = field(default_factory=lambda: []) 353 | starterEggMoveData: Optional[List[int]] = field(default_factory=lambda: []) 354 | gameStats: Optional[Dict[str, Optional[int]]] = None 355 | unlocks: Optional[Dict[str, Optional[bool]]] = None 356 | achvUnlocks: Optional[Dict[str, Optional[int]]] = None 357 | voucherUnlocks: Optional[Dict[str, Optional[int]]] = None 358 | voucherCounts: Optional[Dict[str, Optional[int]]] = None 359 | eggs: Optional[Dict[str, None]] = None 360 | eggPity: Optional[List[int]] = field(default_factory=lambda: [0, 0, 0, 0]) 361 | unlockPity: Optional[List[int]] = field(default_factory=lambda: [0, 0, 0, 0]) 362 | gameVersion: Optional[int] = None 363 | timestamp: Optional[int] = None 364 | 365 | def toDict(self): 366 | return asdict(self) 367 | 368 | 369 | 370 | def fh_getCombinedIDs(includeStarter=True, onlyNormalForms=True): 371 | combinedFormIds = [] 372 | 373 | for species in specieses: 374 | if (includeStarter or not species.isStarter) and (not onlyNormalForms or species.isNormalForm): 375 | for form in species.forms: 376 | if form.name == "Combined": 377 | combinedFormIds.append({ 378 | "speciesID": species.dex, 379 | "speciesName": species.name, 380 | "formName": form.name, 381 | "caughtAttr": form.variant3, 382 | "formIndex": form.index 383 | }) 384 | 385 | return combinedFormIds 386 | 387 | @staticmethod 388 | def data_iterateParty(slotData, speciesNameByIDHelper, moveNamesByIDHelper, natureNamesByIDHelper): 389 | currentParty = [] 390 | pokeballList = { 391 | 0: "Pokeball", 392 | 1: "Great Ball", 393 | 2: "Hyper Ball", 394 | 3: "Rogue Ball", 395 | 4: "Master Ball", 396 | 5: "Luxury Ball" 397 | } 398 | for object in slotData.get("party", []): # Use .get() to avoid KeyError if "party" doesn't exist 399 | # Define IDs and indices 400 | speciesDexID = str(object.get('species', 1)) 401 | speciesFusionID = str(object.get('fusionSpecies', 0)) 402 | speciesFormIndex = int(object.get('formIndex', 0)) 403 | speciesFusionFormIndex = int(object.get('fusionFormIndex', 0)) 404 | 405 | # Get base names 406 | speciesDexName = speciesNameByIDHelper.get(speciesDexID, f'Unknown Dex ID {speciesDexID}') 407 | speciesFusionName = speciesNameByIDHelper.get(speciesFusionID, f'Unknown Fuse ID {speciesFusionID}') 408 | 409 | # Modify names based on form index 410 | if speciesFormIndex > 0 and int(speciesDexID) in speciesDict and len(speciesDict[int(speciesDexID)].forms) > speciesFormIndex: 411 | speciesFormName = speciesDict[int(speciesDexID)].forms[speciesFormIndex].name 412 | speciesDexName = f'{speciesFormName} {speciesDexName}' 413 | 414 | if speciesFusionFormIndex > 0 and speciesFusionID != '0' and int(speciesFusionID) in speciesDict and len(speciesDict[int(speciesFusionID)].forms) > speciesFusionFormIndex: 415 | speciesFusionFormName = speciesDict[int(speciesFusionID)].forms[speciesFusionFormIndex].name 416 | speciesFusionName = f'{speciesFusionFormName} {speciesFusionName}' 417 | 418 | # General fusion info 419 | speciesFusionLuck = object.get('fusionLuck', None) 420 | speciesFusionisShiny = object.get('fusionShiny', None) 421 | speciesFusionVariant = object.get('fusionVariant', None) 422 | 423 | # General species info 424 | speciesIsShiny = object.get('shiny', False) 425 | speciesShinyVariant = object.get('variant', 0) 426 | speciesLuck = object.get('luck', 1) 427 | speciesLevel = object.get('level', 1) 428 | 429 | # Ensure moveset is a list and handle missing move IDs 430 | speciesMoves = [moveNamesByIDHelper.get(str(move.get("moveId", 0)), "Unknown Move") for move in object.get("moveset", [])] 431 | 432 | speciesNatureID = str(object.get('nature', 0)) 433 | speciesNatureName = natureNamesByIDHelper.get(speciesNatureID, "None") 434 | speciesIVs = object.get('ivs', 1) 435 | speciesHP = object.get('hp', 1) 436 | speciesPassive = object.get('passive', False) 437 | 438 | # Check if the species has a passive ability 439 | if int(speciesDexID) in speciesDict and hasattr(speciesDict[int(speciesDexID)], 'hasPassive') and speciesDict[int(speciesDexID)].hasPassive: 440 | speciesPassiveStatus = object.get('passive', False) 441 | else: 442 | speciesPassiveStatus = 'Not available' 443 | 444 | speciesPokerus = object.get('pokerus', False) 445 | speciesPokeball = object.get('pokeball', 0) 446 | 447 | # Handle missing Pokeball types 448 | speciesPokeballStatus = pokeballList.get(speciesPokeball, "Unknown Pokeball") 449 | 450 | speciesInfo = { 451 | 'id': speciesDexID, 452 | 'fusionID': speciesFusionID, 453 | 'formIndex': speciesFormIndex, 454 | 'fusionFormIndex': speciesFusionFormIndex, 455 | 'name': speciesDexName.title(), 456 | 457 | 'fusion': speciesFusionName.title(), 458 | 'fusionLuck': speciesFusionLuck, 459 | 'fusionIsShiny': speciesFusionisShiny, 460 | 'fusionVariant': speciesFusionVariant, 461 | 462 | 'shiny': speciesIsShiny, 463 | 'variant': speciesShinyVariant, 464 | 'luck': speciesLuck, 465 | 'level': speciesLevel, 466 | 'moves': speciesMoves, 467 | 'natureID': speciesNatureID, 468 | 'nature': speciesNatureName, 469 | 'ivs': speciesIVs, 470 | 'hp': speciesHP, 471 | 'passive': speciesPassive, 472 | 'passiveStatus': speciesPassiveStatus, 473 | 'pokerus': speciesPokerus, 474 | 'pokeball': speciesPokeball, 475 | 476 | 'pokeballStatus': speciesPokeballStatus, 477 | 'fusionStatus': '' if speciesFusionID == '0' else f'Fused with {Fore.YELLOW}{speciesFusionName.title()}{Style.RESET_ALL}', 478 | 'shinyStatus': f'Shiny {speciesShinyVariant + 1}' if speciesIsShiny else 'Not Shiny', 479 | 'luckCount': speciesLuck if speciesFusionID == '0' else (speciesLuck + (speciesFusionLuck if speciesFusionLuck is not None else 0)), 480 | 'data_ref': object 481 | } 482 | 483 | currentParty.append(speciesInfo) 484 | 485 | return currentParty -------------------------------------------------------------------------------- /src/modules/handler/__init__.py: -------------------------------------------------------------------------------- 1 | from .httpResponseHandling import dec_handleHTTPExceptions, HTTPEmptyResponse 2 | 3 | from .operationResponseHandling import dec_handleOperationExceptions 4 | from .operationResponseHandling import OperationCancel, OperationError, OperationSuccessful, PropagateResponse, OperationSoftCancel 5 | from .inputHandler import fh_getChoiceInput, fh_getCompleterInput, fh_getIntegerInput 6 | 7 | __all__ = [ 8 | 'dec_handleOperationExceptions', 9 | 'OperationCancel', 'OperationError', 'OperationSuccessful', 'PropagateResponse', 'OperationSoftCancel', 10 | 11 | 'dec_handleHTTPExceptions', 'HTTPEmptyResponse', 12 | 'fh_getChoiceInput', 'fh_getCompleterInput', 'fh_getIntegerInput' 13 | ] -------------------------------------------------------------------------------- /src/modules/handler/httpResponseHandling.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 24.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | from functools import wraps 9 | from utilities import cFormatter, Color 10 | 11 | class HTTPEmptyResponse(Exception): 12 | def __init__(self, message='Response content is empty.'): 13 | self.message = message 14 | super().__init__(self.message) 15 | 16 | # Custom status messages for specific HTTP status codes 17 | statusMessages = { 18 | 200: (Color.BRIGHT_GREEN, 'Response 200 - That seemed to have worked!'), 19 | 400: (Color.WARNING, 'Response 400 - Bad Request: The server could not understand the request due to invalid syntax. This is usually related to wrong credentials.'), 20 | 401: (Color.BRIGHT_RED, 'Response 401 - Unauthorized: Authentication is required and has failed or has not yet been provided.'), 21 | 403: (Color.BRIGHT_RED, 'Response 403 - Forbidden. We have no authorization to access the resource.'), 22 | 404: (Color.BRIGHT_RED, 'Response 404 - Not Found: The server can not find the requested resource.'), 23 | 405: (Color.BRIGHT_RED, 'Response 405 - Method Not Allowed: The request method is known by the server but is not supported by the target resource.'), 24 | 406: (Color.BRIGHT_RED, 'Response 406 - Not Acceptable: The server cannot produce a response matching the list of acceptable values defined in the request\'s proactive content negotiation headers.'), 25 | 407: (Color.BRIGHT_RED, 'Response 407 - Proxy Authentication Required: The client must first authenticate itself with the proxy.'), 26 | 408: (Color.BRIGHT_RED, 'Response 408 - Request Timeout: The server would like to shut down this unused connection.'), 27 | 413: (Color.BRIGHT_RED, 'Response 413 - Payload Too Large: The request entity is larger than limits defined by server.'), 28 | 429: (Color.BRIGHT_RED, 'Response 429 - Too Many Requests: The user has sent too many requests in a given amount of time ("rate limiting").'), 29 | 500: (Color.CRITICAL, 'Error 500 - Internal Server Error: The server has encountered a situation it does not know how to handle.'), 30 | 502: (Color.CRITICAL, 'Error 502 - Bad Gateway: The server was acting as a gateway or proxy and received an invalid response from the upstream server.'), 31 | 503: (Color.CRITICAL, 'Error 503 - Service Temporarily Unavailable: The server is not ready to handle the request.'), 32 | 504: (Color.CRITICAL, 'Error 504 - Gateway Timeout: The server is acting as a gateway or proxy and did not receive a timely response from the upstream server.'), 33 | 520: (Color.CRITICAL, 'Error 520 - Web Server Returns an Unknown Error: The server has returned an unknown error.'), 34 | 521: (Color.CRITICAL, 'Error 521 - Web Server Is Down: The server is not responding to Cloudflare requests.'), 35 | 522: (Color.CRITICAL, 'Error 522 - Connection Timed Out: Cloudflare was able to complete a TCP connection to the origin server, but the origin server did not reply with an HTTP response.'), 36 | 523: (Color.CRITICAL, 'Error 523 - Origin Is Unreachable: Cloudflare could not reach the origin server.'), 37 | 524: (Color.CRITICAL, 'Error 524 - A Timeout Occurred: Cloudflare was able to complete a TCP connection to the origin server, but the origin server did not reply with an HTTP response.') 38 | } 39 | 40 | def dec_handleHTTPExceptions(func, requests): 41 | @wraps(func) 42 | def wrapper(*args, **kwargs): 43 | try: 44 | return func(*args, **kwargs) 45 | except requests.exceptions.HTTPError as http_err: 46 | cFormatter.print(Color.CRITICAL, f'HTTP error occurred: {http_err}') 47 | if isinstance(args[0], requests.Response) and args[0].status_code in statusMessages: 48 | color, message = statusMessages[args[0].status_code] 49 | cFormatter.print(color, message, isLogging=True) 50 | else: 51 | cFormatter.print(Color.CRITICAL, 'Unexpected HTTP error occurred.', isLogging=True) 52 | except requests.exceptions.RequestException as req_err: 53 | cFormatter.print(Color.CRITICAL, f'Request error occurred: {req_err}') 54 | except Exception as e: 55 | cFormatter.print(Color.CRITICAL, f'Other error occurred: {e}') 56 | return wrapper 57 | -------------------------------------------------------------------------------- /src/modules/handler/inputHandler.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 25.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | from modules.handler import OperationCancel, OperationSoftCancel 9 | from enum import Enum 10 | from prompt_toolkit import prompt 11 | from prompt_toolkit.completion import WordCompleter 12 | from utilities import cFormatter, Color 13 | from typing import Optional 14 | 15 | 16 | @staticmethod 17 | def fh_getChoiceInput(promptMesage: str, choices: dict, renderMenu: bool = False, zeroCancel: bool=False, softCancel:bool = False) -> str: 18 | """ 19 | Args: 20 | - promptMesage (str): The prompt message to display. 21 | - choices (dict): The dictionary containing choice options. 22 | - renderMenu (bool): If True, render the menu with line breaks for readability. 23 | - zeroCancel (bool): If True, allow raise cancellation with '0' interrupting the operation and save. 24 | - softCancel (bool): If True, allow soft cancellation with '0' interrupting the operation but allow saving. 25 | 26 | Helper method to get a validated choice input from the user. 27 | 28 | Raises: 29 | - OperationCancel() 30 | - OperationSoftCancel() 31 | - ValueError() 32 | 33 | Returns: 34 | - str: The validated choice key. 35 | - or any Raise depending on setup. 36 | """ 37 | if renderMenu: 38 | actions = "\n".join([f'{idx + 1}: {desc}' for idx, desc in enumerate(choices.values())]) 39 | fullPrompt = f'{promptMesage}\n{actions}\nSelect a option (0: Cancel): ' 40 | else: 41 | actions = " | ".join([f'{idx + 1}: {desc}' for idx, desc in enumerate(choices.values())]) 42 | if zeroCancel or softCancel: 43 | fullPrompt = f'{promptMesage} (0: Cancel | {actions}): ' 44 | else: 45 | fullPrompt = f'{promptMesage} ({actions}): ' 46 | 47 | while True: 48 | userInput = input(fullPrompt).strip() 49 | if userInput.lower() == 'exit' or userInput.lower() == 'cancel' or userInput == '': 50 | raise OperationCancel() 51 | if userInput == '0': 52 | if zeroCancel: 53 | raise OperationCancel() 54 | if softCancel: 55 | raise OperationSoftCancel() 56 | 57 | # If no cancel or skip is requested 58 | if userInput.isdigit(): 59 | idx = int(userInput) - 1 60 | if 0 <= idx < len(choices): 61 | return list(choices.keys())[idx] 62 | 63 | print(f'{userInput}') 64 | 65 | @staticmethod 66 | def fh_getIntegerInput(promptMessage: str, minBound: int, maxBound: int, zeroCancel: bool=False, softCancel: bool=False, allowSkip: bool=False) -> int: 67 | """ 68 | Args: 69 | - prompt (str): The prompt message to display. 70 | - minBound (int): The minimum valid value. 71 | - maxBound (int): The maximum valid value. 72 | - zeroCancel (bool): If True, allow raise cancellation with '0' interrupting the operation and save. 73 | - softCancel (bool): If True, allow soft cancellation with '0' interrupting the operation but allow saving. 74 | - allowSkip (bool): If True, returns 'skip' 75 | Helper method to get a validated integer input from the user. 76 | 77 | 78 | Raises: 79 | - OperationCancel() 80 | - OperationSoftCancel() 81 | - ValueError() 82 | 83 | Returns: 84 | - int: The validated integer input. 85 | - or any Raise depending on setup. 86 | """ 87 | if zeroCancel: 88 | minBound = 0 89 | fullPrompt = f'{promptMessage} (0: Cancel | 1 - {maxBound} | "skip"): ' if allowSkip else f'{promptMessage} (0: Cancel | 1 - {maxBound}): ' 90 | if softCancel: 91 | minBound = 0 92 | fullPrompt = f'{promptMessage} (0: Save & Cancel | 1 - {maxBound} | "skip"): ' if allowSkip else f'{promptMessage} (0: Save & Cancel | 1 - {maxBound}): ' 93 | else: 94 | fullPrompt = f'{promptMessage} ({minBound} - {maxBound}): ' 95 | 96 | while True: 97 | userInput = input(fullPrompt).strip() 98 | if userInput.lower() == 'exit' or userInput.lower() == 'cancel' or userInput == '' or userInput == ' ' or userInput is None: 99 | raise OperationCancel() 100 | if userInput == '0': 101 | if zeroCancel: 102 | raise OperationCancel() 103 | elif softCancel: 104 | raise OperationSoftCancel() 105 | if allowSkip and userInput.lower() == 'skip': 106 | return 'skip' 107 | 108 | # If no cancel or skip is requested 109 | if userInput.isdigit(): 110 | value = int(userInput) 111 | if minBound <= value <= maxBound: 112 | return str(value) 113 | 114 | cFormatter.print(Color.INFO, f'Invalid input: "{userInput}" - must be between {minBound} - {maxBound}') 115 | 116 | @staticmethod 117 | def fh_getCompleterInput(promptMessage: str, choices: dict, zeroCancel: bool = False, softCancel: bool = False, allowSkip: bool = False) -> str: 118 | """ 119 | Args: 120 | - prompt_message (str): The prompt message to display. 121 | - choices (dict): A dictionary mapping input choices to their corresponding values. 122 | - zeroCancel (bool): If True, allow raise cancellation with '0' interrupting the operation and save. 123 | - softCancel (bool): If True, allow soft cancellation with '0' interrupting the operation but allow saving. 124 | 125 | Helper method to get input from the user with auto-completion support. 126 | 127 | Raises: 128 | - OperationSoftCancel() 129 | - OperationCancel() 130 | - ValueError() 131 | 132 | Returns: 133 | - str: The value corresponding to the validated input choice, or raises OperationCancel if the user cancels. 134 | - or any Raise depending on setup. 135 | """ 136 | fullPrompt = f'{promptMessage}: ' 137 | if zeroCancel or softCancel: 138 | fullPrompt = f'{promptMessage} (0: Cancel): ' 139 | 140 | # Create a WordCompleter from the keys of choices dictionary 141 | completer = WordCompleter(choices.keys(), ignore_case=True) 142 | 143 | while True: 144 | try: 145 | userInput = prompt(fullPrompt, completer=completer).strip() # Ensure prompt is the correct callable 146 | 147 | if userInput.lower() == 'exit' or userInput.lower() == 'cancel' or userInput == '': 148 | raise OperationCancel() 149 | if userInput == '0': 150 | if softCancel: 151 | raise OperationSoftCancel() 152 | if zeroCancel: 153 | raise OperationCancel() 154 | if allowSkip and userInput.lower() == 'skip': 155 | return 'skip' 156 | 157 | ## Validate the input 158 | if userInput in choices: 159 | return choices[userInput] 160 | 161 | # Ensure inputValue is a string 162 | inputValue = str(userInput).strip().lower() 163 | enumMember: Optional[Enum] = None 164 | if inputValue.isdigit(): 165 | # Input is an ID 166 | enumMember = next((member for member in choices.values() if isinstance(member, Enum) and member.value == int(inputValue))) 167 | else: 168 | # Input is a name 169 | enumMember = next((member for member in choices.values() if isinstance(member, Enum) and member.name() == inputValue)) 170 | 171 | if enumMember is not None: 172 | return enumMember 173 | # only except that here, this indicates invalid input for choicecompleter 174 | except StopIteration: 175 | cFormatter.print(Color.INFO, 'Invalid input.') 176 | -------------------------------------------------------------------------------- /src/modules/handler/operationResponseHandling.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 25.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | from utilities import Color 9 | from json import JSONDecodeError 10 | from modules.config import debugEnableTraceback 11 | from utilities import fh_appendMessageBuffer 12 | 13 | def dec_handleOperationExceptions(func): 14 | def wrapper(*args, **kwargs): 15 | try: 16 | return func(*args, **kwargs) 17 | 18 | except OperationSuccessful as os: 19 | funcName = func.__name__ 20 | customMessage = os.args[0] if os.args else "" 21 | fh_appendMessageBuffer(Color.DEBUG, f'Operation {funcName} finished. {customMessage}') 22 | 23 | except OperationError as oe: 24 | fh_appendMessageBuffer(Color.DEBUG, str(oe), isLogging=True) 25 | 26 | except OperationCancel as oc: 27 | fh_appendMessageBuffer(Color.DEBUG, f'{str(oc)}') # need \n cause it breaks on new lines 28 | 29 | except OperationSoftCancel as sc: 30 | funcName = func.__name__ 31 | customMessage = sc.args[0] if sc.args else "" 32 | fh_appendMessageBuffer(Color.DEBUG, f'Soft-cancelling {funcName}. {customMessage}') 33 | 34 | except KeyboardInterrupt: 35 | fh_appendMessageBuffer(Color.DEBUG, 'Keyboard-interrupt detected.') 36 | 37 | except JSONDecodeError as jde: 38 | funcName = func.__name__ 39 | customMessage = f'JSON decoding error in function {funcName}: {jde}' 40 | fh_appendMessageBuffer(Color.CRITICAL, customMessage, isLogging=True) 41 | 42 | except IOError as ioe: 43 | funcName = func.__name__ 44 | customMessage = f'{funcName}: {ioe}' 45 | fh_appendMessageBuffer(Color.CRITICAL, f'Error loading data: {customMessage}', isLogging=True) 46 | 47 | except Exception as e: 48 | funcName = func.__name__ 49 | customMessage = f'Error in function {funcName}: {e}' 50 | fh_appendMessageBuffer(Color.CRITICAL, customMessage, isLogging=True) 51 | # This should forward any exception not handled to our main stack 52 | if debugEnableTraceback: 53 | raise Exception() 54 | return wrapper 55 | 56 | # ============================================== 57 | # = Custom Exception for Operation Cancelling. = 58 | # = Will be catched by our main routine. = 59 | # ============================================== 60 | class OperationCancel(Exception): 61 | 62 | def __init__(self, message: str = None): 63 | if message: 64 | self.message = message 65 | else: 66 | self.message = 'Operation canceled.' 67 | super().__init__(self.message) 68 | 69 | # ============================================== 70 | # = Custom Exception for Operation Feedback = 71 | # = Will be catched by our main routine. = 72 | # ============================================== 73 | class OperationSuccessful(Exception): 74 | def __init__(self, message: str = None): 75 | if message: 76 | self.message = message 77 | else: 78 | self.message = 'Operation succesful.' 79 | super().__init__(self.message) 80 | 81 | # ============================================== 82 | # = Custom Exception for Operation Errors . = 83 | # = Will be catched by our main routine. = 84 | # ============================================== 85 | class OperationError(Exception): 86 | def __init__(self, originalTraceback: Exception = None, message: str = None): 87 | self.original_exception = originalTraceback 88 | if message: 89 | self.message = message 90 | elif originalTraceback: 91 | self.message = f'Operation encountered an error: {str(originalTraceback)}' 92 | else: 93 | self.message = 'Operation encountered an error.' 94 | super().__init__(self.message) 95 | 96 | # ============================================================== 97 | # = Custom Exception for Propagating messages to main routine. = 98 | # = Will be catched by our main routine. = 99 | # ============================================================== 100 | class PropagateResponse(Exception): 101 | def __init__(self, message: str = None): 102 | if message: 103 | self.message = message 104 | else: 105 | self.message = '' 106 | super().__init__(self.message) 107 | 108 | # ====================================================================================== 109 | # = Custom Exception for Operation Softcancelling. Doesnt cancel the function raising. = 110 | # = Will be catched by our main routine. = 111 | # ====================================================================================== 112 | class OperationSoftCancel(Exception): 113 | def __init__(self, message=""): 114 | super().__init__(message) -------------------------------------------------------------------------------- /src/modules/requestsLogic.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: https://github.com/claudiunderthehood 5 | # Date of release: 13.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | """ 9 | This script provides functionality for handling HTTP requests, including error handling and login logic. 10 | 11 | Features: 12 | - Sends HTTP POST requests to a specified login URL. 13 | - Handles various HTTP response status codes and logs corresponding messages. 14 | - Generates random user agent headers for requests. 15 | - Implements rate limiting to prevent excessive requests. 16 | 17 | Modules: 18 | - requests: Sends HTTP requests and handles responses. 19 | - random: Generates random integers for implementing rate limiting and adding delays. 20 | - typing: Provides support for type hints. 21 | - time.sleep: Introduces delays between requests to simulate human behavior. 22 | - utilities.limiter.Limiter: Limits the frequency of requests to avoid rate limiting issues. 23 | - utilities.cFormatter: Formats console output for displaying error and debug messages. 24 | - pyuseragents: Generates random user agent strings for diverse HTTP requests. 25 | - string: Provides character manipulation functions for generating random session IDs. 26 | 27 | Workflow: 28 | 1. Define error handling for various HTTP response status codes. 29 | 2. Generate random user agent headers for HTTP requests. 30 | 3. Implement rate limiting to prevent excessive requests. 31 | 4. Send HTTP POST request to the login URL with provided credentials. 32 | 5. Log login status and HTTP response details upon successful or failed login attempts. 33 | 34 | Usage: 35 | - Initialize an instance of requestsLogic with username and password. 36 | - Call login() method to attempt login and retrieve login status. 37 | 38 | Output examples: 39 | - Displays formatted error messages for various HTTP status codes. 40 | - Logs successful login with HTTP status code, response URL, and headers. 41 | 42 | Modules/Librarys used and for what purpose exactly in each function at the end of the docstring: 43 | - requests: Sends HTTP POST requests to login URL and handles server responses. 44 | - random: Generates random integers for rate limiting and adding delays. 45 | - typing: Provides type hints for function parameters and return types. 46 | - time.sleep: Delays execution to simulate natural behavior during HTTP requests. 47 | - utilities.limiter.Limiter: Implements rate limiting to prevent excessive login attempts. 48 | - utilities.cFormatter: Formats console output for displaying debug and error messages during login process. 49 | - pyuseragents: Generates diverse user agent strings to mimic different browsers and operating systems. 50 | - string: Provides character manipulation functions for generating random session IDs. 51 | """ 52 | 53 | import requests 54 | import random 55 | from typing import Dict, Optional 56 | from time import sleep 57 | from utilities import Limiter, cFormatter, Color 58 | import pyuseragents 59 | from user_agents import parse 60 | import string 61 | from modules.config import useCaCert 62 | limiter = Limiter() 63 | 64 | 65 | def fh_handleErrorResponse(response: requests.Response) -> Dict[str, str]: 66 | """ 67 | Handle error responses from the server. 68 | 69 | Args: 70 | response (requests.Response): The HTTP response object. 71 | 72 | Returns: 73 | dict: Empty dictionary. 74 | 75 | This method handles various HTTP response status codes and prints corresponding 76 | messages using the cFormatter class. It covers common client and server error 77 | codes, information from cloudflare docs. 78 | 79 | Example: 80 | >>> response = requests.get("https://example.com") 81 | >>> fh_handleErrorResponse(response) 82 | 'Response 404 - Not Found: The server can not find the requested resource.' 83 | 84 | Modules/Librarys used and for what purpose exactly in each function: 85 | - requests: Handles HTTP response objects to log error messages based on status codes. 86 | - utilities.cFormatter: Formats console output for displaying error messages with color coding. 87 | """ 88 | 89 | if response.status_code == 200: 90 | cFormatter.print(Color.BRIGHT_GREEN, 'Response 200 - That seemed to have worked!') 91 | cFormatter.print(Color.BRIGHT_GREEN, 'If it doesn\'t apply in-game, refresh without cache or try a private tab!') 92 | else: 93 | cFormatter.print(Color.CRITICAL, f'Response {response.status_code} - {response.reason}: {response.text}', isLogging=True) 94 | 95 | return {} 96 | 97 | class HeaderGenerator: 98 | """ 99 | Generates random user agent headers for HTTP requests. 100 | 101 | This class generates random user agent strings using pyuseragents and parses them 102 | using pyuseragents library to extract browser and operating system information. 103 | 104 | :arguments: 105 | - isAuthHeader (bool): Whether to generate authentication headers. 106 | 107 | :params: 108 | - browserFamily: Browser family extracted from the user agent string. 109 | - browserVersion: Browser version extracted from the user agent string. 110 | - osFamily: Operating system family extracted from the user agent string. 111 | - osVersion: Operating system version extracted from the user agent string. 112 | - isMobile: Boolean indicating if the user agent represents a mobile device. 113 | 114 | Usage: 115 | Generate user agent headers: 116 | >>> headers = HeaderGenerator.generateHeaders() 117 | 118 | Output examples: 119 | - User agent headers with randomly generated browser and operating system information. 120 | 121 | Modules/Librarys used and for what purpose exactly in each function: 122 | - pyuseragents: Generates diverse user agent strings to mimic different browsers and operating systems. 123 | """ 124 | @classmethod 125 | def fh_generateHeaders(cls, isAuthHeader: bool = False) -> Dict[str, str]: 126 | userAgentString = pyuseragents.random() 127 | userAgent = parse(userAgentString) 128 | 129 | browserFamily = userAgent.browser.family 130 | browserVersion = userAgent.browser.version_string 131 | osFamily = userAgent.os.family 132 | osVersion = userAgent.os.version_string 133 | isMobile = userAgent.is_mobile 134 | 135 | headers = { 136 | "Accept": "application/x-www-form-urlencoded", 137 | "Content-Type": "application/x-www-form-urlencoded", 138 | "Origin": "https://pokerogue.net", 139 | "Referer": "https://pokerogue.net/", 140 | "Sec-CH-UA-Mobile": "?1" if isMobile else "?0", 141 | "Sec-Fetch-Dest": "empty", 142 | "Sec-Fetch-Mode": "cors", 143 | "Sec-Fetch-Site": "same-site", 144 | "User-Agent": userAgentString, 145 | } 146 | 147 | # Define the optional headers 148 | optionalHeader = { 149 | "Sec-CH-UA": f'"{browserFamily}";v="{browserVersion}"', 150 | "Sec-CH-UA-Platform": osFamily, 151 | "Sec-CH-UA-Platform-Version": osVersion, 152 | } 153 | 154 | # Randomly decide to add some or all of the optional headers 155 | for header, value in optionalHeader.items(): 156 | if random.choice([True, False]): 157 | headers[header] = value 158 | 159 | return headers 160 | 161 | class requestsLogic: 162 | """ 163 | Handles HTTP requests for logging in to a specified URL. 164 | 165 | This class initializes a session, generates random user agent headers using HeaderGenerator, 166 | implements rate limiting with Limiter, and handles various HTTP response status codes using 167 | fh_handleErrorResponse. 168 | 169 | :arguments: 170 | - username (str): The username for logging in. 171 | - password (str): The password for logging in. 172 | 173 | :params: 174 | - token (Optional[str]): Authentication token retrieved after successful login. 175 | - sessionId (Optional[str]): Randomly generated session ID. 176 | - session (requests.Session): Session object for managing HTTP requests. 177 | 178 | Usage: 179 | Initialize requestsLogic instance with username and password: 180 | >>> login = requestsLogic('user', 'pass') 181 | 182 | Attempt login using HTTP POST request: 183 | >>> success = login.login() 184 | >>> print(success) 185 | 186 | Output examples: 187 | - Logs successful login with HTTP status code, response URL, and headers. 188 | - Displays formatted error messages for various HTTP status codes. 189 | 190 | Modules/Librarys used and for what purpose exactly in each function: 191 | - requests: Sends HTTP POST requests and manages session for logging in. 192 | - random: Generates random integers for implementing rate limiting and adding delays. 193 | - typing: Provides type hints for function parameters and return types. 194 | - time.sleep: Delays execution to simulate natural behavior during HTTP requests. 195 | - utilities.limiter.Limiter: Limits the frequency of HTTP requests to avoid rate limiting issues. 196 | - utilities.cFormatter: Formats console output for displaying debug and error messages during login process. 197 | - pyuseragents: Generates diverse user agent strings to mimic different browsers and operating systems. 198 | - user_agents.parse: Extracts browser and operating system details from user agent strings. 199 | - string: Provides character manipulation functions for generating random session IDs. 200 | """ 201 | 202 | LOGIN_URL = 'https://api.pokerogue.net/account/login' 203 | 204 | def __init__(self, username: str, password: str) -> None: 205 | """ 206 | Initialize requestsLogic with username and password. 207 | 208 | Args: 209 | username (str): The username for logging in. 210 | password (str): The password for logging in. 211 | 212 | Example: 213 | >>> login = requestsLogic('user', 'pass') 214 | """ 215 | self.username = username 216 | self.password = password 217 | self.token: Optional[str] = None 218 | self.sessionId: Optional[str] = None 219 | self.session = requests.Session() 220 | 221 | def calcSessionId(self) -> str: 222 | """ 223 | Calculate a randomly generated session ID. 224 | 225 | Returns: 226 | str: Randomly generated session ID. 227 | 228 | Usage: 229 | Generate a session ID: 230 | >>> session_id = self.calcSessionId() 231 | """ 232 | characters = string.ascii_letters + string.digits 233 | result = [] 234 | for _ in range(32): 235 | randomIndex = random.randint(0, len(characters) - 1) 236 | result.append(characters[randomIndex]) 237 | 238 | return ''.join(result) 239 | 240 | @limiter.lockout 241 | def login(self) -> bool: 242 | """ 243 | Attempt login using HTTP POST request and handle responses. 244 | 245 | Returns: 246 | bool: True if login is successful, False otherwise. 247 | 248 | Usage: 249 | Attempt login and check success: 250 | >>> success = self.login() 251 | >>> print(success) 252 | """ 253 | data = {'username': self.username, 'password': self.password} 254 | try: 255 | headers = HeaderGenerator.fh_generateHeaders() 256 | cFormatter.print(Color.DEBUG, 'Adding delay to appear more natural to the server. Please stand by...') 257 | cFormatter.print(Color.DEBUG, '(If it takes longer than 5 Seconds its not on us.)') 258 | response = self.session.post(self.LOGIN_URL, headers=headers, data=data, verify=useCaCert) 259 | del data, self.username, self.password 260 | sleep(random.randint(3, 5)) 261 | response.raise_for_status() 262 | 263 | loginResponse = response.json() 264 | self.token = loginResponse.get('token') 265 | cFormatter.fh_printSeperators(30, '-') 266 | self.sessionId = self.calcSessionId() 267 | cFormatter.print(Color.GREEN, 'Login successful.') 268 | formattedStatusCode = Color.BRIGHT_GREEN if response.status_code == 200 else Color.BRIGHT_RED 269 | cFormatter.print(formattedStatusCode, f'HTTP Status Code: {response.status_code}') 270 | cFormatter.print(Color.CYAN, f'Response URL: {response.request.url}', isLogging=True) 271 | filteredHeaders = {key: value for key, value in response.headers.items() if key != 'Report-To'} 272 | cFormatter.print(Color.CYAN, f'Response Headers: {filteredHeaders}', isLogging=True) 273 | cFormatter.fh_printSeperators(30, '-') 274 | return True 275 | 276 | except requests.RequestException: 277 | fh_handleErrorResponse(response) 278 | return False 279 | -------------------------------------------------------------------------------- /src/modules/seleniumLogic.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: https://github.com/claudiunderthehood 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | """ 9 | This script provides a Selenium-based login process for pyRogue, enabling automated login 10 | and retrieval of session ID, token, and headers from a specified website. 11 | 12 | Features: 13 | - Automates login using Selenium with username and password. 14 | - Retrieves session ID and authentication token from the logged responses. 15 | - Supports handling of browser performance logs to extract relevant data. 16 | 17 | Modules: 18 | - selenium.webdriver: Provides browser automation capabilities for interacting with web pages. 19 | - selenium.webdriver.common.by: Defines methods for locating elements in the web page. 20 | - selenium.webdriver.common.keys: Provides keys like RETURN for simulating user inputs. 21 | - selenium.webdriver.support.ui: Implements WebDriverWait for waiting until certain conditions are met. 22 | - selenium.webdriver.support.expected_conditions: Defines expected conditions for WebDriverWait. 23 | - selenium.common.exceptions: Handles exceptions that may occur during browser interactions. 24 | - json: Provides methods for parsing JSON data received from the web server. 25 | - time: Offers time-related functions, used here for adding a randomized wait time. 26 | - typing: Supports type hints for Python functions and variables. 27 | - utilities.CustomLogger: Handles custom logging settings to control log outputs. 28 | - random: Generates random integers for adding variability in the login process. 29 | 30 | Workflow: 31 | 1. Initialize the SeleniumLogic instance with username, password, and optional timeout. 32 | 2. Use the logic() method to perform automated login and retrieve session ID, token, and headers. 33 | 3. Handle browser performance logs to extract necessary data for authentication. 34 | 35 | Usage Example: 36 | >>> seleniumLogic = SeleniumLogic(username='yourUsername', password='yourPassword', timeout=120) 37 | >>> sessionId, token, driver = seleniumLogic.logic() 38 | >>> print(f'Session ID: {sessionId}') 39 | >>> print(f'Token: {token}') 40 | >>> # driver can be further used for additional operations if needed 41 | 42 | Expected Output Example: 43 | >> Session ID: abc123clientSessionId 44 | >> Token: abc123token 45 | >> # Additional headers: {'Content-Type': 'application/json', 'User-Agent': '...'} 46 | """ 47 | 48 | from selenium import webdriver 49 | from selenium.webdriver.common.by import By 50 | from selenium.webdriver.common.keys import Keys 51 | from selenium.webdriver.support.ui import WebDriverWait 52 | from selenium.webdriver.support import expected_conditions as EC 53 | from selenium.common.exceptions import TimeoutException 54 | import json 55 | import time 56 | from typing import Optional, Tuple, Dict, Any 57 | from utilities import CustomLogger 58 | import random 59 | from modules.config import useCaCert 60 | 61 | class SeleniumLogic: 62 | """ 63 | Handles the Selenium-based login process for pyRogue. 64 | 65 | Attributes: 66 | username (str): The username for login. 67 | password (str): The password for login. 68 | timeout (int): The timeout duration for the login process. 69 | useScripts (Optional[bool]): Specifies if additional scripts are used during login. 70 | """ 71 | 72 | def __init__(self, username: str, password: str, timeout: int = 120, useScripts: Optional[bool] = None) -> None: 73 | """ 74 | Initializes the SeleniumLogic instance. 75 | 76 | Args: 77 | username (str): The username for login. 78 | password (str): The password for login. 79 | timeout (int): The timeout duration for the login process. 80 | useScripts (Optional[bool]): Specifies if additional scripts are used during login. 81 | """ 82 | self.timeout = timeout 83 | self.username = username 84 | self.password = password 85 | self.useScripts = useScripts 86 | 87 | def _processBrowserLogs(self, entry: Dict[str, Any]) -> Dict[str, Any]: 88 | """ 89 | Processes a single browser log entry to extract the relevant response data. 90 | 91 | Args: 92 | entry (Dict[str, Any]): A log entry from the browser. 93 | 94 | Returns: 95 | Dict[str, Any]: The processed response data. 96 | """ 97 | response = json.loads(entry["message"])["message"] 98 | return response 99 | 100 | def logic(self) -> Tuple[Optional[str], Optional[str], Optional[webdriver.Chrome]]: 101 | """ 102 | Handles the login logic using Selenium and retrieves the session ID, token, and headers. 103 | 104 | Returns: 105 | Tuple[Optional[str], Optional[str], Optional[webdriver.Chrome]]: 106 | The session ID, token, and WebDriver instance if available, otherwise None. 107 | """ 108 | # Deactivate logging because selenium clutters it extremely 109 | CustomLogger.fh_deactivateLogging() 110 | 111 | # Set Browser options 112 | options = webdriver.ChromeOptions() 113 | options.set_capability('goog:loggingPrefs', {'performance': 'ALL'}) # All performance logs 114 | options.add_argument('--disable-blink-features=AutomationControlled') # Avoid detection 115 | options.add_argument('--no-sandbox') # Overcome limited resource problems 116 | options.add_argument('--disable-dev-shm-usage') # Overcome limited resource problems 117 | options.add_argument('--disable-infobars') # Disable infobars 118 | options.add_argument('--enable-javascript') # enable javascript explicitly 119 | if useCaCert: 120 | options.add_argument(f'--ca-certificate={useCaCert}') 121 | 122 | driver = webdriver.Chrome(options=options) 123 | url = 'https://www.pokerogue.net/' 124 | driver.get(url) 125 | 126 | sessionID = None 127 | token = None 128 | 129 | try: 130 | # Wait for the username field to be visible and input the username 131 | usernameInput = WebDriverWait(driver, self.timeout).until( 132 | EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[type="text"]')) 133 | ) 134 | usernameInput.send_keys(self.username) 135 | 136 | # Wait for the password field to be visible and input the password 137 | passwordInput = WebDriverWait(driver, self.timeout).until( 138 | EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[type="password"]')) 139 | ) 140 | passwordInput.send_keys(self.password) 141 | 142 | # Send RETURN key 143 | passwordInput.send_keys(Keys.RETURN) 144 | 145 | print('Waiting for login data...') 146 | time.sleep(random.randint(8,12)) # Fixed wait time to ensure data is there 147 | 148 | # Process the browser log 149 | browserLogs = driver.get_log('performance') 150 | events = [self._processBrowserLogs(entry) for entry in browserLogs] 151 | 152 | # Extract session data such as sessionId, auth-token or headers etc 153 | for event in events: 154 | # Extract the clientSessionId 155 | if 'response' in event["params"]: 156 | response = event["params"]["response"] 157 | if 'url' in response: 158 | url = response["url"] 159 | if 'clientSessionId' in url: 160 | sessionID = url.split('clientSessionId=')[1] 161 | # Extract the authorization token 162 | if 'method' in event and event["method"] == 'Network.responseReceived': 163 | response = event["params"]["response"] 164 | if response["url"] == 'https://api.pokerogue.net/account/login': 165 | requestId = event["params"]["requestId"] 166 | result = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId}) 167 | responseBody = result.get('body', '') 168 | if responseBody: 169 | tokenData = json.loads(responseBody) 170 | token = tokenData.get('token') 171 | 172 | except TimeoutException as e: 173 | print(f'Timeout occurred: {e}') 174 | 175 | finally: 176 | CustomLogger.fh_reactivateLogging() 177 | # If we are not using login method 3 we should close the driver already 178 | if not self.useScripts: 179 | driver.close() 180 | 181 | del self.username, self.password 182 | 183 | return sessionID, token, driver -------------------------------------------------------------------------------- /src/offlineSaveConverter/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AES Encryption/Decryption 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 |

AES Encryption/Decryption

17 |

The Advanced Encryption Standard.

18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/offlineSaveConverter/js/script.js: -------------------------------------------------------------------------------- 1 | window.onload = function() { 2 | document.getElementById("decryptBtn").addEventListener('click', function() { 3 | const fileInput = document.getElementById("file"); 4 | const file = fileInput.files[0]; 5 | 6 | if (!file) { 7 | alert("Please select a file."); 8 | return; 9 | } 10 | 11 | const reader = new FileReader(); 12 | reader.onload = function(event) { 13 | const fileContent = event.target.result; 14 | 15 | try { 16 | const decrypted = CryptoJS.AES.decrypt(fileContent, "x0i2O7WRiANTqPmZ"); 17 | const plaintext = decrypted.toString(CryptoJS.enc.Utf8); 18 | 19 | const jsonContent = JSON.parse(plaintext); 20 | 21 | const nullCheckbox = document.getElementById("nullCheckbox"); 22 | if (nullCheckbox.checked) { 23 | for (const key in jsonContent.starterData) { 24 | if (jsonContent.starterData.hasOwnProperty(key)) { 25 | jsonContent.starterData[key]["$m"] = null; 26 | } 27 | } 28 | } 29 | 30 | const binaryCheckbox = document.getElementById("binaryCheckbox"); 31 | if (binaryCheckbox.checked) { 32 | for (const key in jsonContent.dexData) { 33 | if (jsonContent.dexData.hasOwnProperty(key)) { 34 | jsonContent.dexData[key]["$sa"] = (jsonContent.dexData[key]["$sa"]).toString(2); 35 | jsonContent.dexData[key]["$ca"] = (jsonContent.dexData[key]["$ca"]).toString(2); 36 | jsonContent.dexData[key]["$na"] = (jsonContent.dexData[key]["$na"]).toString(2); 37 | } 38 | } 39 | } 40 | 41 | const blob = new Blob([JSON.stringify(jsonContent, null, 2)], { type: "application/json" }); 42 | 43 | const filename = file.name.startsWith('data') ? 'data_Guest.json' : (file.name.startsWith('sessionData') ? 'sessionData_Guest.json' : 'decrypted_data.json'); 44 | 45 | const downloadLink = document.createElement("a"); 46 | downloadLink.href = window.URL.createObjectURL(blob); 47 | downloadLink.download = filename; 48 | downloadLink.click(); 49 | } catch (e) { 50 | alert("Error: Failed to decrypt or parse JSON."); 51 | } 52 | }; 53 | 54 | reader.readAsText(file); 55 | }); 56 | 57 | document.getElementById("encryptBtn").addEventListener('click', function() { 58 | const fileInput = document.getElementById("file"); 59 | const file = fileInput.files[0]; 60 | 61 | if (!file) { 62 | alert("Please select a file."); 63 | return; 64 | } 65 | 66 | const reader = new FileReader(); 67 | reader.onload = function(event) { 68 | const fileContent = event.target.result; 69 | 70 | try { 71 | 72 | const ciphertext = CryptoJS.AES.encrypt(CryptoJS.enc.Latin1.parse(fileContent), "x0i2O7WRiANTqPmZ").toString(); 73 | 74 | const blob = new Blob([ciphertext], { type: "application/octet-stream" }); 75 | 76 | const extension = file.name.endsWith('.json') ? 'prsv' : 'json'; 77 | const filename = file.name.replace(/\.[^/.]+$/, `.${extension}`); 78 | 79 | const downloadLink = document.createElement("a"); 80 | downloadLink.href = window.URL.createObjectURL(blob); 81 | downloadLink.download = filename; 82 | downloadLink.click(); 83 | } catch (e) { 84 | alert("Error: Failed to encrypt."); 85 | } 86 | }; 87 | 88 | // Read the file as binary data 89 | reader.readAsBinaryString(file); 90 | }); 91 | }; -------------------------------------------------------------------------------- /src/offlineSaveConverter/readme.md: -------------------------------------------------------------------------------- 1 | # Pretty self explanatory, use to convert offline save files. 2 | 3 | From PRSV -> .json (Decrypt) 4 | From .json -> PRSV (Encrypt) -------------------------------------------------------------------------------- /src/requirements.txt: -------------------------------------------------------------------------------- 1 | altgraph==0.17.4 2 | attrs==23.2.0 3 | Brotli==1.1.0 4 | certifi==2024.7.4 5 | cffi==1.16.0 6 | charset-normalizer==3.3.2 7 | colorama==0.4.6 8 | h11==0.14.0 9 | idna==3.7 10 | outcome==1.3.0.post0 11 | packaging==24.1 12 | pefile==2023.2.7 13 | prompt_toolkit==3.0.46 14 | pycparser==2.22 15 | pyinstaller==6.8.0 16 | pyinstaller-hooks-contrib==2024.7 17 | PySocks==1.7.1 18 | pyuseragents==1.0.5 19 | pywin32-ctypes==0.2.2 20 | requests==2.32.3 21 | selenium==4.21.0 22 | setuptools==70.1.0 23 | sniffio==1.3.1 24 | sortedcontainers==2.4.0 25 | trio==0.25.1 26 | trio-websocket==0.11.1 27 | typing_extensions==4.12.1 28 | ua-parser==0.18.0 29 | urllib3==2.2.2 30 | user-agents==2.2.0 31 | wcwidth==0.2.13 32 | wsproto==1.2.0 33 | zstandard==0.22.0 34 | -------------------------------------------------------------------------------- /src/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | from .cFormatter import cFormatter, Color, format 2 | from .logger import CustomLogger, CustomFilter 3 | from .enumLoader import EnumLoader 4 | from .generator import Vouchers, Generator, Nature, NatureSlot, NoPassive 5 | from .limiter import Limiter 6 | from .propagateMessage import messageBuffer, fh_appendMessageBuffer, fh_clearMessageBuffer, fh_printMessageBuffer, fh_redundantMesage 7 | from . import eggLogic 8 | 9 | 10 | __all__ = [ 11 | 'cFormatter', 'Color', 'CustomLogger', 'CustomFilter', 'format', 12 | 'Vouchers', 'Generator', 'Nature', 'NatureSlot', 'NoPassive', 13 | 'Limiter', 'EnumLoader', 'eggLogic', 14 | 'messageBuffer', 'fh_appendMessageBuffer', 'fh_clearMessageBuffer', 'fh_printMessageBuffer', 'fh_redundantMesage' 15 | ] -------------------------------------------------------------------------------- /src/utilities/cFormatter.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | """ 9 | This module provides a custom logging formatter and various utility functions for enhanced console output. 10 | It includes: 11 | - An enumeration for ANSI color codes to allow colored logging output. 12 | - A custom logging formatter (cFormatter) that supports colored console output and other formatting utilities. 13 | - Functions for printing colored text, separators, and formatted text lines. 14 | - A function for initializing and displaying a menu with numbered choices. 15 | 16 | Modules: 17 | - colorama: Provides ANSI escape sequences for colored terminal text. 18 | - enum: Allows the creation of enumerations, a set of symbolic names bound to unique, constant values. 19 | - logging: Provides a flexible framework for emitting log messages from Python programs. 20 | - shutil: Includes high-level file operations such as copying and removal. 21 | - typing: Provides support for type hints, enabling optional type checking. 22 | - re: Provides support for regular expressions, allowing pattern matching in strings. 23 | 24 | Workflow: 25 | 1. Define the Color enum for ANSI color codes. 26 | 2. Define the cFormatter class for custom logging formatting. 27 | 3. Implement static methods in cFormatter for printing colored text, separators, and formatted lines. 28 | 4. Implement a method for initializing and displaying a menu with numbered choices. 29 | """ 30 | 31 | from colorama import Fore, Style 32 | # Provides ANSI escape sequences for colored terminal text, used for coloring console output. 33 | 34 | from enum import Enum 35 | # Allows the creation of enumerations, used here for defining color codes. 36 | 37 | import logging 38 | # Provides a flexible framework for emitting log messages, used for custom logging formatting. 39 | 40 | import shutil 41 | # Includes high-level file operations, used here for getting terminal width. 42 | 43 | from typing import Optional, List, Tuple, Union 44 | # Provides support for type hints, used for optional type checking and clarity. 45 | 46 | import re 47 | # Provides support for regular expressions, used for stripping ANSI color codes from text. 48 | 49 | @staticmethod 50 | def format(entry, color=Fore.YELLOW): 51 | return f'{color}{entry}{Style.RESET_ALL}' 52 | 53 | class Color(Enum): 54 | """ 55 | Enum defining ANSI color codes for console output. 56 | 57 | Attributes: 58 | > These also trigger the corresponding logging level. 59 | CRITICAL (str): Bright red color for critical messages. 60 | DEBUG (str): Bright blue color for debug messages. 61 | ERROR (str): Red color for error messages. 62 | WARNING (str): Yellow color for warning messages. 63 | INFO (str): Bright light yellow color for informational messages. 64 | 65 | BLACK (str): Black color. 66 | RED (str): Red color. 67 | GREEN (str): Green color. 68 | YELLOW (str): Yellow color. 69 | BLUE (str): Blue color. 70 | MAGENTA (str): Magenta color. 71 | CYAN (str): Cyan color. 72 | WHITE (str): White color. 73 | BRIGHT_BLACK (str): Bright black color. 74 | BRIGHT_RED (str): Bright red color. 75 | BRIGHT_GREEN (str): Bright green color. 76 | BRIGHT_YELLOW (str): Bright yellow color. 77 | BRIGHT_BLUE (str): Bright blue color. 78 | BRIGHT_MAGENTA (str): Bright magenta color. 79 | BRIGHT_CYAN (str): Bright cyan color. 80 | BRIGHT_WHITE (str): Bright white color. 81 | """ 82 | CRITICAL = Style.BRIGHT + Fore.RED 83 | DEBUG = Style.BRIGHT + Fore.BLUE 84 | ERROR = Fore.RED 85 | WARNING = Fore.YELLOW 86 | INFO = Style.BRIGHT + Fore.LIGHTYELLOW_EX 87 | 88 | BLACK = Fore.BLACK 89 | RED = Fore.RED 90 | GREEN = Fore.GREEN 91 | YELLOW = Fore.YELLOW 92 | BLUE = Fore.BLUE 93 | MAGENTA = Fore.MAGENTA 94 | CYAN = Fore.CYAN 95 | WHITE = Fore.WHITE 96 | BRIGHT_BLACK = Style.BRIGHT + Fore.BLACK 97 | BRIGHT_RED = Style.BRIGHT + Fore.RED 98 | BRIGHT_GREEN = Style.BRIGHT + Fore.GREEN 99 | BRIGHT_YELLOW = Style.BRIGHT + Fore.YELLOW 100 | BRIGHT_BLUE = Style.BRIGHT + Fore.BLUE 101 | BRIGHT_MAGENTA = Style.BRIGHT + Fore.MAGENTA 102 | BRIGHT_CYAN = Style.BRIGHT + Fore.CYAN 103 | BRIGHT_WHITE = Style.BRIGHT + Fore.WHITE 104 | 105 | class cFormatter(logging.Formatter): 106 | """ 107 | A custom formatter for logging with colored console output. 108 | """ 109 | LOG_LEVELS = { 110 | logging.CRITICAL: Color.CRITICAL, 111 | logging.DEBUG: Color.DEBUG, 112 | logging.ERROR: Color.ERROR, 113 | logging.WARNING: Color.WARNING, 114 | logging.INFO: Color.INFO, 115 | } 116 | 117 | @staticmethod 118 | def print(color: Color, text: str, isLogging: bool = False) -> None: 119 | """ 120 | Logs the text to the console with specified color and optionally to a file. 121 | 122 | Args: 123 | color (Color): The color to use for formatting the text. 124 | text (str): The text to log. 125 | isLogging (bool, optional): Specifies whether the text is for logging. Defaults to False. 126 | 127 | Usage Example: 128 | cFormatter.print(Color.INFO, 'This is an informational message', isLogging=True) 129 | cFormatter.print(Color.DEBUG, 'This is a debug message') 130 | 131 | Example Output: 132 | [LIGHTYELLOW_EX]This is an informational message[RESET] 133 | [BLUE]This is a debug message[RESET] 134 | 135 | Modules/Librarys used: 136 | - logging: Used to log messages. 137 | - colorama: Used to apply color to text. 138 | """ 139 | logger = logging.getLogger("root") 140 | 141 | if isLogging: 142 | # Determine the logging level based on color 143 | logLevel = logging.INFO 144 | for level, col in cFormatter.LOG_LEVELS.items(): 145 | if col == color: 146 | logLevel = level 147 | break 148 | logger.log(logLevel, text) 149 | 150 | # Format text with ANSI color codes and print to console 151 | colorCode = color.value 152 | formatted_text = f'{colorCode}{text}{Style.RESET_ALL}' 153 | print(formatted_text) 154 | 155 | @staticmethod 156 | def fh_printSeperators(numSeperator: Optional[int] = None, separator: str = '-', color: Optional[Color] = None) -> None: 157 | """ 158 | Prints separators with the specified color. 159 | 160 | Args: 161 | numSeperator (int, optional): The number of separator characters to print. If None, uses terminal width. Defaults to None. 162 | separator (str, optional): The character to use for separators. Defaults to '-'. 163 | color (Color, optional): The color to use for formatting separators. Defaults to None. 164 | 165 | Usage Example: 166 | cFormatter.fh_printSeparators(10, '-', Color.GREEN) 167 | cFormatter.fh_printSeparators(separator='-', color=Color.GREEN) 168 | 169 | Example Output: 170 | [GREEN]----------[RESET] 171 | [GREEN]---------------------------------------------[RESET] 172 | 173 | Modules/Librarys used: 174 | - shutil: Used to get the terminal width. 175 | - colorama: Used to apply color to text. 176 | """ 177 | if numSeperator is None: 178 | terminalWidth = shutil.get_terminal_size().columns 179 | numSeperator = terminalWidth 180 | 181 | colorCode = color.value if color else '' 182 | formattedSeperator = f'{colorCode}{separator * numSeperator}{Style.RESET_ALL}' 183 | print(formattedSeperator) 184 | 185 | @staticmethod 186 | def fh_stripColorCodes(text: str) -> str: 187 | """ 188 | Strips ANSI color codes from the text for accurate length calculations. 189 | 190 | Args: 191 | text (str): The text from which to strip ANSI color codes. 192 | 193 | Returns: 194 | str: The text without ANSI color codes. 195 | 196 | Usage Example: 197 | strippedText = cFormatter.fh_stripColorCodes('[GREEN]Text[RESET]') 198 | print(strippedText) 199 | 200 | Example Output: 201 | Text 202 | 203 | Modules/Librarys used: 204 | - re: Used to strip ANSI color codes from text. 205 | """ 206 | ansiEscape = re.compile(r'\x1b\[.*?m') 207 | return ansiEscape.sub('', text) 208 | 209 | @staticmethod 210 | def fh_lineFill(line: str, helperText: str = '', length: int = 55, fill_char: str = ' ', truncate: bool = False) -> str: 211 | """ 212 | Args: 213 | line (str): The main text line to format. 214 | helperText (str, optional): Additional text to append. Defaults to ''. 215 | length (int, optional): The total length of the formatted line. Defaults to 55. 216 | fillChar (str, optional): The character used for filling empty space. Defaults to ' '. 217 | truncate (bool, optional): Whether to truncate the line if it exceeds the specified length. Defaults to False. 218 | 219 | Formats a line of text to a fixed length by adding fill characters. 220 | 221 | Returns: 222 | str: The formatted line of text. 223 | 224 | Usage Example: 225 | formatedLine = cFormatter.fh_lineFill('Main text', 'Helper text', 80, '-') 226 | print(formattedLine) 227 | 228 | Example Output: 229 | Main text-----------------------------------Helper text 230 | 231 | Modules/Librarys used: 232 | - re: Used to strip ANSI color codes from text. 233 | """ 234 | strippedLine = cFormatter.fh_stripColorCodes(line) 235 | strippedHelperText = cFormatter.fh_stripColorCodes(helperText) 236 | 237 | totalLength = len(strippedLine) + len(strippedHelperText) 238 | 239 | if truncate and totalLength > length: 240 | truncated_length = length - len(strippedLine) - 3 # 3 characters for "..." 241 | line = line[:truncated_length] + '...' 242 | strippedLine = cFormatter.fh_stripColorCodes(line) 243 | totalLength = len(strippedLine) + len(strippedHelperText) 244 | 245 | fillLength = length - totalLength 246 | fill = fill_char * fillLength 247 | return f'{Style.RESET_ALL}{line}{fill}{helperText}' 248 | 249 | @staticmethod 250 | def fh_centerText(text: str, length: int = 55, fillChar: str = ' ') -> str: 251 | """ 252 | Args: 253 | text (str): The text to center. 254 | length (int, optional): The total length of the centered text. Defaults to 55. 255 | fillChar (str, optional): The character used for filling empty space. Defaults to ' '. 256 | 257 | Centers a text within a given length, filling with the specified character. 258 | 259 | Returns: 260 | str: The centered text. 261 | 262 | Usage Example: 263 | centeredText = cFormatter.fh_centerText('Centered Text', 80, '-') 264 | print(centeredText) 265 | 266 | Example Output: 267 | --------------Centered Text--------------- 268 | 269 | Modules/Librarys used: 270 | - re: Used to strip ANSI color codes from text. 271 | """ 272 | strippedText = cFormatter.fh_stripColorCodes(text) 273 | totalLength = len(strippedText) 274 | if totalLength >= length: 275 | return text[:length] 276 | 277 | fillLength = length - totalLength 278 | frontFill = fillChar * (fillLength // 2) 279 | backFill = fillChar * (fillLength - (fillLength // 2)) 280 | if fillChar == '>': 281 | backFill = '<' * (fillLength - (fillLength // 2)) 282 | 283 | 284 | return f'{frontFill}{text}{backFill}' 285 | 286 | @staticmethod 287 | def m_initializeMenu(term: List[Union[str, Tuple[str, str, Optional[str]], Tuple[str, callable]]], length: Optional[int] = 55) -> List[Tuple[int, callable]]: 288 | """ 289 | Args: 290 | term (List[Union[str, Tuple[str, str, Optional[str]], Tuple[str, callable]]]): A list containing tuples and strings representing menu items. 291 | 292 | Initializes and prints a menu based on the provided term list. 293 | 294 | Returns: 295 | List[Tuple[int, callable]]: A list of tuples containing valid numbered choices and their associated functions. 296 | 297 | Usage Example: 298 | term = [ 299 | (title, 'title'), 300 | (('Option 1', 'Description for option 1'), function1), 301 | (('Option 2', ''), function2), 302 | ('Helper text', 'helper'), 303 | ('Helper text', 'category'), 304 | ] 305 | validChoices = cFormatter.m_initializeMenu(term) 306 | 307 | Example Output: 308 | * --------------------- pyRogue ---------------------- * 309 | 1: Option 1 Description for option 1 310 | 2: Option 2 311 | * ----------------------- Helper text ----------------------- * 312 | 313 | Returns [(1, function1), (2, function2)] 314 | 315 | Modules/Librarys used: 316 | - colorama: Used to apply color to text. 317 | """ 318 | validChoices = [] 319 | actualIndex = 1 320 | for item in term: 321 | if isinstance(item, tuple): 322 | if item[1] == 'helper': 323 | print(Fore.GREEN + '* ' + cFormatter.fh_centerText(f' {item[0]} ', length, '-') + f' {Fore.GREEN}*' + Style.RESET_ALL) 324 | elif item[1] == 'title': 325 | print(Fore.GREEN + '* ' + cFormatter.fh_centerText(f' {item[0]} ', length, '*') + f' {Fore.GREEN}*' + Style.RESET_ALL) 326 | elif item[1] == 'category': 327 | print(Fore.LIGHTYELLOW_EX + '* ' + cFormatter.fh_centerText(f' {item[0]} ', length, '>') + ' *' + Style.RESET_ALL) 328 | else: 329 | text, func = item 330 | line = f'{actualIndex}: {text[0]}' 331 | formatted_line = cFormatter.fh_lineFill(line, text[1], length, ' ', True) 332 | print(Fore.GREEN + '* ' + formatted_line + f' {Fore.GREEN}*' + Style.RESET_ALL) 333 | validChoices.append((actualIndex, func)) 334 | actualIndex += 1 335 | else: 336 | print(Fore.YELLOW + '* ' + cFormatter.fh_centerText(item, length, '*') + ' *' + Style.RESET_ALL) 337 | 338 | return validChoices -------------------------------------------------------------------------------- /src/utilities/eggLogic.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Authors 5 | # Date of release: 13.06.2024 6 | # Last Edited: 28.06.2024 7 | # Based on: https://github.com/pagefaultgames/pokerogue/ 8 | 9 | """ 10 | Source Code from https://github.com/pagefaultgames/pokerogue/ multiple files 11 | Tier and Source Type Initialization: 12 | using eggOptions.tier to determine the _tier of the egg. If not provided, it falls back to Overrides.EGG_TIER_OVERRIDE or rolls a random tier using this.rollEggTier(). 13 | _sourceType is set to eggOptions.sourceType or undefined. 14 | 15 | Pulled Eggs: 16 | If eggOptions.pulled is true, you check for eggOptions.scene to potentially override the _tier using this.checkForPityTierOverrides(). 17 | 18 | ID Generation: 19 | _id is generated using eggOptions.id if provided or by calling Utils.randInt(EGG_SEED, EGG_SEED * this._tier). 20 | 21 | Timestamp and Hatch Waves: 22 | _timestamp defaults to the current time if not provided in eggOptions. 23 | _hatchWaves is determined by eggOptions.hatchWaves or defaults to a tier-specific default using this.getEggTierDefaultHatchWaves(). 24 | 25 | Shiny, Variant, Species, and Hidden Ability: 26 | _isShiny is set based on eggOptions.isShiny, Overrides.EGG_SHINY_OVERRIDE, or randomly rolled. 27 | _variantTier is set similarly for variants. 28 | _species is determined by eggOptions.species or randomly rolled using this.rollSpecies(). 29 | _overrideHiddenAbility is set to eggOptions.overrideHiddenAbility or defaults to false. 30 | 31 | Species-Specific Handling: 32 | If eggOptions.species is provided, it overrides _tier and _hatchWaves. If the species has no variants, _variantTier is set to VariantTier.COMMON. 33 | 34 | Egg Move Index: 35 | _eggMoveIndex defaults to a random value using this.rollEggMoveIndex() unless specified in eggOptions. 36 | 37 | Pulled Egg Actions: 38 | If eggOptions.pulled is true, you increase pull statistics and add the egg to game data using this.increasePullStatistic() and this.addEggToGameData(). 39 | 40 | constructor(eggOptions?: IEggOptions) { 41 | //if (eggOptions.tier && eggOptions.species) throw Error("Error egg can't have species and tier as option. only choose one of them.") 42 | 43 | this._tier = eggOptions.tier ?? (Overrides.EGG_TIER_OVERRIDE ?? this.rollEggTier()); 44 | this._sourceType = eggOptions.sourceType ?? undefined; 45 | // If egg was pulled, check if egg pity needs to override the egg tier 46 | if (eggOptions.pulled) { 47 | // Needs this._tier and this._sourceType to work 48 | this.checkForPityTierOverrides(eggOptions.scene); 49 | } 50 | 51 | this._id = eggOptions.id ?? Utils.randInt(EGG_SEED, EGG_SEED * this._tier); 52 | 53 | this._sourceType = eggOptions.sourceType ?? undefined; 54 | this._hatchWaves = eggOptions.hatchWaves ?? this.getEggTierDefaultHatchWaves(); 55 | this._timestamp = eggOptions.timestamp ?? new Date().getTime(); 56 | 57 | // First roll shiny and variant so we can filter if species with an variant exist 58 | this._isShiny = eggOptions.isShiny ?? (Overrides.EGG_SHINY_OVERRIDE || this.rollShiny()); 59 | this._variantTier = eggOptions.variantTier ?? (Overrides.EGG_VARIANT_OVERRIDE ?? this.rollVariant()); 60 | this._species = eggOptions.species ?? this.rollSpecies(eggOptions.scene); 61 | 62 | this._overrideHiddenAbility = eggOptions.overrideHiddenAbility ?? false; 63 | 64 | // Override egg tier and hatchwaves if species was given 65 | if (eggOptions.species) { 66 | this._tier = this.getEggTierFromSpeciesStarterValue(); 67 | this._hatchWaves = eggOptions.hatchWaves ?? this.getEggTierDefaultHatchWaves(); 68 | // If species has no variant, set variantTier to common. This needs to 69 | // be done because species with no variants get filtered at rollSpecies but since the 70 | // species is set the check never happens 71 | if (!getPokemonSpecies(this.species).hasVariants()) { 72 | this._variantTier = VariantTier.COMMON; 73 | } 74 | } 75 | // Needs this._tier so it needs to be generated afer the tier override if bought from same species 76 | this._eggMoveIndex = eggOptions.eggMoveIndex ?? this.rollEggMoveIndex(); 77 | if (eggOptions.pulled) { 78 | this.increasePullStatistic(eggOptions.scene); 79 | this.addEggToGameData(eggOptions.scene); 80 | } 81 | } 82 | 83 | 84 | export const EGG_SEED = 1073741824; 85 | 86 | // Rates for specific random properties in 1/x 87 | const DEFAULT_SHINY_RATE = 128; 88 | const GACHA_SHINY_UP_SHINY_RATE = 64; 89 | const SAME_SPECIES_EGG_SHINY_RATE = 32; 90 | const SAME_SPECIES_EGG_HA_RATE = 16; 91 | const MANAPHY_EGG_MANAPHY_RATE = 8; 92 | 93 | // 1/x for legendary eggs, 1/x*2 for epic eggs, 1/x*4 for rare eggs, and 1/x*8 for common eggs 94 | const DEFAULT_RARE_EGGMOVE_RATE = 6; 95 | const SAME_SPECIES_EGG_RARE_EGGMOVE_RATE = 3; 96 | const GACHA_MOVE_UP_RARE_EGGMOVE_RATE = 3; 97 | 98 | 99 | /** Egg options to override egg properties */ 100 | export interface IEggOptions { 101 | /** Id. Used to check if egg type will be manaphy (id % 204 === 0) */ 102 | id?: number; 103 | /** Timestamp when this egg got created */ 104 | timestamp?: number; 105 | /** Defines if the egg got pulled from a gacha or not. If true, egg pity and pull statistics will be applyed. 106 | * Egg will be automaticly added to the game data. 107 | * NEEDS scene eggOption to work. 108 | */ 109 | pulled?: boolean; 110 | /** Defines where the egg comes from. Applies specific modifiers. 111 | * Will also define the text displayed in the egg list. 112 | */ 113 | sourceType?: EggSourceType; 114 | /** Needs to be defined if eggOption pulled is defined or if no species or isShiny is degined since this will be needed to generate them. */ 115 | export enum EggSourceType { 116 | GACHA_MOVE, 117 | GACHA_LEGENDARY, 118 | GACHA_SHINY, 119 | SAME_SPECIES_EGG, 120 | EVENT 121 | } 122 | scene?: BattleScene; 123 | /** Sets the tier of the egg. Only species of this tier can be hatched from this egg. 124 | * Tier will be overriden if species eggOption is set. 125 | */ 126 | tier?: EggTier; 127 | /** Sets how many waves it will take till this egg hatches. */ 128 | hatchWaves?: number; 129 | /** Sets the exact species that will hatch from this egg. 130 | * Needs scene eggOption if not provided. 131 | */ 132 | species?: Species; 133 | /** Defines if the hatched pokemon will be a shiny. */ 134 | isShiny?: boolean; 135 | /** Defines the variant of the pokemon that will hatch from this egg. If no variantTier is given the normal variant rates will apply. */ 136 | variantTier?: VariantTier; 137 | /** Defines which egg move will be unlocked. 3 = rare egg move. */ 138 | eggMoveIndex?: number; 139 | /** Defines if the egg will hatch with the hidden ability of this species. 140 | * If no hidden ability exist, a random one will get choosen. 141 | */ 142 | overrideHiddenAbility?: boolean 143 | } 144 | """ 145 | 146 | import random 147 | import time 148 | from typing import List, Tuple, Dict, Optional 149 | 150 | # Constant from game source code 151 | EGG_SEED: int = 1073741824 152 | GACHA_TYPES: List[str] = ['MoveGacha', 'LegendaryGacha', 'ShinyGacha', 'SAME_SPECIES_EGG', 'EVENT'] 153 | EGG_TIERS: List[str] = ['Common', 'Rare', 'Epic', 'Legendary', 'Manaphy'] 154 | 155 | def getIDBoundarys(tier: int) -> Tuple[int, int]: 156 | """ 157 | Get the ID boundaries for a given tier. 158 | 159 | Args: 160 | tier (int): The tier index. 161 | 162 | Returns: 163 | Tuple[int, int]: A tuple containing the start and end IDs. 164 | 165 | Example: 166 | start, end = getIDBoundarys(2) 167 | print(start, end) # Output: 2147483648 3221225471 168 | """ 169 | # Calculate the start and end IDs for the given tier 170 | start: int = tier * EGG_SEED 171 | end: int = (tier + 1) * EGG_SEED - 1 172 | return max(start, 255), end 173 | 174 | def generateRandomID(start: int, end: int, manaphy: bool = False) -> int: 175 | """ 176 | Generate a random ID within the given range. 177 | 178 | Args: 179 | start (int): The start of the ID range. 180 | end (int): The end of the ID range. 181 | manaphy (bool): Whether the ID is for a Manaphy egg. 182 | 183 | Returns: 184 | int: The random ID. 185 | 186 | Example: 187 | random_id = generateRandomID(0, 1073741823) 188 | print(random_id) # Output: 564738291 (example) 189 | """ 190 | if manaphy: 191 | # Generate a random ID that is divisible by 204 within the specified range based on tier 192 | return random.randrange(start // 204 * 204, (end // 204 + 1) * 204, 204) 193 | 194 | # Generate a regular random ID within the specified range 195 | result: int = random.randint(start, end) 196 | 197 | if result % 204 == 0: 198 | result -= 1 199 | 200 | return max(result, 1) 201 | 202 | def __getRandomSpeciesForShiny(tier: int, eggTypesData) -> Optional[int]: 203 | speciesMatch = [] 204 | for member in eggTypesData: 205 | species = member.value 206 | if species["isEgg"] is not None: 207 | # If the tier is 6, match by name substrings 208 | if tier == 6: 209 | if any(substring in species['name'].lower() for substring in ["alola_", "galar_", "hisui_", "paldea_"]): 210 | speciesMatch.append(member) 211 | print(f"Matched species: {species['name']} with index {member.name}") 212 | elif tier == 7: 213 | paradoxIDs = [984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 1005, 1006, 1009, 1010, 1020, 1021, 1022, 1023] 214 | if paradoxIDs and int(member.name) in paradoxIDs: 215 | speciesMatch.append(member) 216 | print(f"Matched species: {species['name']} with index {member.name}") 217 | # For other tiers, match by eggType 218 | elif species["isEgg"]["eggType"] == tier: 219 | speciesMatch.append(member) 220 | #print(f"Matched species: {species['name']} with index {member.name}") 221 | 222 | if not speciesMatch: 223 | # No matching species found 224 | return None 225 | 226 | rnd = random.choice(speciesMatch) 227 | print(f"Randomly chosen species: {rnd.value['name']} with index {rnd.name}") 228 | return rnd.name, rnd.value["isEgg"]["eggType"] 229 | 230 | def constructEggs(tier: int, gachaType: int, hatchWaveCount: int, eggAmount: int, eggTypesData, isShiny: bool = False, variantTier: int = 0) -> List[Dict[str, int]]: 231 | """ 232 | Generate eggs with the given properties. 233 | 234 | Args: 235 | tier (int): The tier of the eggs. 236 | gachaType (int): The gacha type. 237 | hatchWaveCount (int): The number of hatch waves. 238 | eggAmount (int): The number of eggs to generate. 239 | isShiny (bool): Whether the egg is shiny. Defaults to False. 240 | variantTier (int): The variant tier for shiny eggs. Defaults to 0. 241 | 242 | Returns: 243 | List[Dict[str, int]]: A list of generated eggs, each represented as a dictionary with egg properties. 244 | 245 | Example: 246 | eggs = constructEggs(1, 2, 3, 10, True, 1) 247 | print(eggs) 248 | # Output: [{'id': 123456789, 'gachaType': 2, 'hatchWaves': 3, 'timestamp': 1625247123456, 'tier': 0, 'isShiny': True, 'variantTier': 1}, ...] 249 | """ 250 | isManaphy: bool = tier == 4 251 | start, end = getIDBoundarys(0 if isManaphy else tier) 252 | 253 | eggs: List[Dict[str, int]] = [] 254 | for _ in range(eggAmount): 255 | eggID: int = generateRandomID(start, end, isManaphy) 256 | timestamp: int = int(time.time() * 1000) 257 | 258 | egg: Dict[str, int] = { 259 | 'id': eggID, 260 | 'gachaType': gachaType, 261 | 'hatchWaves': int(hatchWaveCount), 262 | 'timestamp': timestamp, 263 | } 264 | 265 | shinyRoll = random.randint(1, 64) 266 | if isShiny or shinyRoll == 1: 267 | egg["isShiny"] = True 268 | egg["variantTier"] = int(variantTier-1) if isShiny else 0 269 | egg["sourceType"] = 1 270 | 271 | # Find a random species with matching eggType 272 | speciesID, speciesEggType = __getRandomSpeciesForShiny(tier+1, eggTypesData) 273 | if speciesID is not None: 274 | egg["species"] = int(speciesID) 275 | egg["tier"] = int(speciesEggType)-1 276 | print(f'EggType: {speciesEggType}') 277 | 278 | else: 279 | egg["isShiny"] = False 280 | egg["variantTier"] = 0 281 | egg["sourceType"] = gachaType 282 | egg["tier"] = tier 283 | 284 | 285 | eggs.append(egg) 286 | 287 | return eggs -------------------------------------------------------------------------------- /src/utilities/enumLoader.py: -------------------------------------------------------------------------------- 1 | # Authors: https://github.com/JulianStiebler https://github.com/claudiunderthehood 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Authors 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | # Based on: https://github.com/pagefaultgames/pokerogue/ 8 | 9 | """ 10 | This script provides functionalities to load data from JSON files and convert them into Enums. 11 | It includes the capability to handle Pokemon IDs, biomes, moves, natures, vouchers, and nature slots. 12 | 13 | Modules: 14 | - utilities: Custom module for colored printing and logging functionalities (cFormatter and Color). 15 | - modules: Contains configuration settings (config). 16 | - json: Provides functionalities to work with JSON data. 17 | - enum: Provides support for enumerations, a set of symbolic names bound to unique, constant values. 18 | 19 | Workflow: 20 | 1. Initialize the EnumLoader class. 21 | 2. Load data from JSON files located in a specified directory. 22 | 3. Convert loaded data to Enums. 23 | 4. Return the created Enums. 24 | """ 25 | 26 | from utilities import cFormatter, Color 27 | # Custom module for colored printing and logging functionalities. 28 | 29 | from modules import config 30 | # Contains configuration settings, specifically for directory paths. 31 | 32 | import json 33 | # Provides functionalities to work with JSON data for reading and writing. 34 | 35 | from enum import Enum 36 | # Provides support for enumerations, a set of symbolic names bound to unique, constant values. 37 | 38 | from typing import Optional, Tuple, Dict 39 | # Provides type hints for better code clarity and type checking. 40 | 41 | class EnumLoader: 42 | def __init__(self) -> None: 43 | """ 44 | Initialize the EnumLoader object. 45 | 46 | Attributes: 47 | starterNameByID (Optional[Dict[str, int]]): Dictionary for starter IDs by name. 48 | biomesByID (Optional[Dict[str, int]]): Dictionary for biomes by ID. 49 | movesByID (Optional[Dict[str, int]]): Dictionary for moves by ID. 50 | natureData (Optional[Dict[str, int]]): Dictionary for natures data. 51 | voucherData (Optional[Dict[str, int]]): Dictionary for vouchers data. 52 | natureDataSlots (Optional[Dict[str, int]]): Dictionary for nature slot data. 53 | noPassiveIDs (Optional[Dict[str, int]]): Dictionary for no passive IDs. 54 | hasFormIDs (Optional[Dict[str, int]]): Dictionary for IDs that have forms. 55 | speciesNameByID (Optional[Dict[str, int]]): Dictionary for species names by ID. 56 | achievementsData (Optional[Dict[str, int]]): Dictionary for achievements data. 57 | """ 58 | self.starterNameByID: Optional[Dict[str, int]] = None 59 | self.biomesByID: Optional[Dict[str, int]] = None 60 | self.movesByID: Optional[Dict[str, int]] = None 61 | self.natureData: Optional[Dict[str, int]] = None 62 | self.voucherData: Optional[Dict[str, int]] = None 63 | self.natureDataSlots: Optional[Dict[str, int]] = None 64 | self.noPassiveIDs: Optional[Dict[str, int]] = None 65 | self.hasFormIDs: Optional[Dict[str, int]] = None 66 | self.speciesNameByID: Optional[Dict[str, int]] = None 67 | self.achievementsData: Optional[Dict[str, int]] = None 68 | self.eggTypesData: Optional[Dict[str, int]] = None 69 | 70 | def __f_loadData(self) -> None: 71 | """ 72 | Load data from JSON files located in the directory specified by config.dataDirectory. 73 | 74 | Raises: 75 | Exception: If there is an error loading the data files. 76 | 77 | Example: 78 | loader = EnumLoader() 79 | loader.__f_loadData() 80 | """ 81 | try: 82 | dataDir: str = config.dataDirectory 83 | 84 | with open(f'{dataDir}/starter.json') as f: 85 | self.starterNameByID: Dict[str, int] = json.load(f) 86 | 87 | with open(f'{dataDir}/biomes.json') as f: 88 | self.biomesByID: Dict[str, int] = json.load(f) 89 | 90 | with open(f'{dataDir}/moves.json') as f: 91 | self.movesByID: Dict[str, int] = json.load(f) 92 | 93 | with open(f'{dataDir}/natures.json') as f: 94 | self.natureData: Dict[str, int] = json.load(f) 95 | 96 | with open(f'{dataDir}/vouchers.json') as f: 97 | self.voucherData: Dict[str, int] = json.load(f) 98 | 99 | with open(f'{dataDir}/natureSlot.json') as f: 100 | self.natureDataSlots: Dict[str, int] = json.load(f) 101 | 102 | with open(f'{dataDir}/achievements.json') as f: 103 | self.achievementsData: Dict[str, int] = json.load(f) 104 | 105 | with open(f'{dataDir}/species.json') as f: 106 | self.speciesNameByID: Dict[str, int] = json.load(f) 107 | 108 | with open(f'{dataDir}/noPassive.json') as f: 109 | self.noPassiveIDs: Dict[str, int] = json.load(f) 110 | 111 | with open(f'{dataDir}/hasForms.json') as f: 112 | self.hasFormIDs: Dict[str, int] = json.load(f) 113 | 114 | with open(f'{dataDir}/eggTypes.json') as f: 115 | self.eggTypesData: Dict[str, int] = json.load(f) 116 | 117 | except Exception as e: 118 | cFormatter.print(Color.CRITICAL, f'Error in enumLoader.__f_loadData(). {e}', isLogging=True) 119 | 120 | def __f_createENUMFromDict(self, dataDict: Dict[str, int], enumName: str) -> Enum: 121 | """ 122 | Create an Enum from a dictionary. 123 | 124 | Args: 125 | dataDict (Dict[str, int]): The dictionary to convert to an Enum. 126 | enumName (str): The name of the Enum. 127 | 128 | Returns: 129 | Enum: The created Enum. 130 | 131 | Example: 132 | loader = EnumLoader() 133 | speciesEnum = loader.__f_createENUMFromDict({'PIKACHU': 25}, 'SpeciesEnum') 134 | """ 135 | enumClass: Enum = Enum(enumName, {key: value for key, value in dataDict.items()}) 136 | return enumClass 137 | 138 | def f_convertToEnums(self) -> Tuple[Enum, Enum, Enum, Enum, Enum, Enum, Enum, Enum, Enum, Enum]: 139 | """ 140 | Convert loaded data to Enums. 141 | 142 | Returns: 143 | Tuple[Enum, Enum, Enum, Enum, Enum, Enum, Enum, Enum, Enum, Enum]: 144 | A tuple containing the created Enums for starter names, biomes, moves, vouchers, natures, nature slots, 145 | achievements, species names, no passive IDs, and IDs with forms. 146 | 147 | Example: 148 | loader = EnumLoader() 149 | enums = loader.f_convertToEnums() 150 | StarterEnum = enums[0] # Access StarterEnum 151 | """ 152 | self.__f_loadData() 153 | 154 | self.starterNameByID: Dict[str, int] = self.__f_createENUMFromDict(self.starterNameByID["dex"], 'StarterEnum') 155 | self.biomesByID: Dict[str, int] = self.__f_createENUMFromDict(self.biomesByID["biomes"], 'BiomesEnum') 156 | self.movesByID: Dict[str, int] = self.__f_createENUMFromDict(self.movesByID["moves"], 'MovesEnum') 157 | self.voucherData: Dict[str, int] = self.__f_createENUMFromDict(self.voucherData["vouchers"], 'VouchersEnum') 158 | self.natureData: Dict[str, int] = self.__f_createENUMFromDict(self.natureData["natures"], 'NaturesEnum') 159 | self.natureDataSlots: Dict[str, int] = self.__f_createENUMFromDict(self.natureDataSlots["natureSlot"], 'NaturesSlotEnum') 160 | self.achievementsData: Dict[str, int] = self.__f_createENUMFromDict(self.achievementsData["achvUnlocks"], 'AchievementsEnum') 161 | self.speciesNameByID: Dict[str, int] = self.__f_createENUMFromDict(self.speciesNameByID["dex"], 'PokemonEnum') 162 | self.noPassiveIDs: Dict[str, int] = self.__f_createENUMFromDict(self.noPassiveIDs["noPassive"], 'NoPassiveEnum') 163 | self.hasFormIDs: Dict[str, int] = self.__f_createENUMFromDict(self.hasFormIDs["hasForms"], 'HasFormsEnum') 164 | self.eggTypesData: Dict[str, int] = self.__f_createENUMFromDict(self.eggTypesData["eggTypes"], 'eggtypeEnum') 165 | 166 | 167 | return (self.starterNameByID, self.biomesByID, self.movesByID, self.voucherData, 168 | self.natureData, self.natureDataSlots, self.achievementsData, self.speciesNameByID, 169 | self.noPassiveIDs, self.hasFormIDs, self.eggTypesData) 170 | -------------------------------------------------------------------------------- /src/utilities/limiter.py: -------------------------------------------------------------------------------- 1 | # Authors: https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | """ 9 | This script provides a lockout mechanism to limit the frequency of function executions. It includes functionality to 10 | persistently store the last execution timestamps of functions and prevent re-execution within a specified lockout period. 11 | 12 | Features: 13 | - Limit function execution frequency with a lockout period. 14 | - Persistent storage of execution timestamps. 15 | - Colored output for log messages. 16 | 17 | Modules: 18 | - os: Module for interacting with the operating system. 19 | - json: Module for working with JSON data. 20 | - time: Module for time-related functions. 21 | - functools: Module for higher-order functions. 22 | - utilities.cFormatter: Custom formatter for colored printing and logging. 23 | 24 | Workflow: 25 | 1. Initialize the Limiter class with a lockout period and optional timestamp file path. 26 | 2. Decorate functions with the lockout decorator to enforce execution limits. 27 | 3. Use the decorated functions as usual, with lockout limits applied. 28 | """ 29 | 30 | import os 31 | import json 32 | import time 33 | from functools import wraps 34 | from utilities import cFormatter, Color 35 | from modules.config import timestampFile 36 | 37 | class Limiter: 38 | """ 39 | A class to handle lockout mechanism for functions to limit their execution frequency. 40 | 41 | Attributes: 42 | lockoutPeriod (int): The lockout period in seconds. 43 | 44 | Usage: 45 | Initialize the limiter and decorate functions to limit their execution frequency: 46 | >>> limiter = Limiter(lockoutPeriod=60) 47 | >>> @limiter.lockout 48 | >>> def my_function(): 49 | >>> print("Function executed.") 50 | 51 | Modules: 52 | - os: Module for interacting with the operating system. 53 | - json: Module for working with JSON data. 54 | - time: Module for time-related functions. 55 | - functools: Module for higher-order functions. 56 | - utilities.cFormatter: Custom formatter for colored printing and logging. 57 | """ 58 | 59 | def __init__(self, lockoutPeriod: int = 40) -> None: 60 | """ 61 | Initialize the Limiter object. 62 | 63 | Args: 64 | lockoutPeriod (int): The lockout period in seconds. 65 | timestampFile (str, optional): The file path to store the timestamps. Default is './data/extra.json'. 66 | 67 | Modules: 68 | - os: Provides a way to interact with the operating system, particularly for file and directory operations. 69 | - json: Provides functionalities to work with JSON data for reading and writing timestamps. 70 | """ 71 | 72 | self.lockoutPeriod = lockoutPeriod 73 | self.timestampFile = timestampFile 74 | if not os.path.exists(os.path.dirname(self.timestampFile)): 75 | os.makedirs(os.path.dirname(self.timestampFile)) 76 | if not os.path.exists(self.timestampFile): 77 | with open(self.timestampFile, 'w') as f: 78 | json.dump({}, f) 79 | 80 | def lockout(self, func): 81 | """ 82 | Decorator function to enforce the lockout mechanism on the decorated function. 83 | 84 | Args: 85 | func (function): The function to be decorated. 86 | 87 | Returns: 88 | function: The decorated function. 89 | 90 | Usage: 91 | Decorate a function with the lockout decorator to limit its execution frequency: 92 | >>> limiter = Limiter(lockoutPeriod=60) 93 | >>> @limiter.lockout 94 | >>> def my_function(): 95 | >>> print("Function executed.") 96 | 97 | Modules: 98 | - functools: Provides utilities for higher-order functions, particularly for creating decorators. 99 | - time: Provides time-related functions, particularly for getting the current time. 100 | - utilities.cFormatter: Custom formatter for colored printing and logging. 101 | """ 102 | @wraps(func) 103 | def wrapper(*args, **kwargs): 104 | funcName = func.__name__ 105 | lastExecTime = self._fh_getLastExecTime(funcName) 106 | currentTime = time.time() 107 | if currentTime - lastExecTime < self.lockoutPeriod: 108 | cFormatter.print(Color.RED, f'{funcName} is rate limited. You can only do this every {self.lockoutPeriod} seconds!', isLogging=True) 109 | return None 110 | else: 111 | result = func(*args, **kwargs) 112 | self._fh_updateLastExecTime(funcName, currentTime) 113 | return result 114 | return wrapper 115 | 116 | def _fh_getLastExecTime(self, function: str) -> float: 117 | """ 118 | Get the timestamp of the last execution of a function. 119 | 120 | Args: 121 | func_name (str): The name of the function. 122 | 123 | Returns: 124 | float: The timestamp of the last execution. 125 | 126 | Usage: 127 | Get the last execution time of a function: 128 | >>> lastExecTime = limiter._fh_getLastExecTime('my_function') 129 | 130 | Modules: 131 | - json: Provides functionalities to work with JSON data for reading and writing timestamps. 132 | """ 133 | with open(self.timestampFile, 'r') as f: 134 | timestamps = json.load(f) 135 | return timestamps.get(function, 0) 136 | 137 | def _fh_updateLastExecTime(self, function: str, timestamp: float) -> None: 138 | """ 139 | Update the timestamp of the last execution of a function. 140 | 141 | Args: 142 | func_name (str): The name of the function. 143 | timestamp (float): The timestamp of the last execution. 144 | 145 | Usage: 146 | Update the last execution time of a function: 147 | >>> limiter._fh_updateLastExecTime('my_function', time.time()) 148 | 149 | Modules: 150 | - json: Provides functionalities to work with JSON data for reading and writing timestamps. 151 | """ 152 | with open(self.timestampFile, 'r+') as f: 153 | try: 154 | timestamps = json.load(f) 155 | except json.decoder.JSONDecodeError: 156 | timestamps = {} 157 | timestamps[function] = timestamp 158 | f.seek(0) 159 | json.dump(timestamps, f, indent=4) 160 | f.truncate() 161 | -------------------------------------------------------------------------------- /src/utilities/logger.py: -------------------------------------------------------------------------------- 1 | # Authors: https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 06.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | """ 9 | This script provides a custom logger that logs messages to a weekly rotating log file. It includes functionality to 10 | exclude specific log messages and to temporarily deactivate and reactivate logging. 11 | 12 | Features: 13 | - Weekly rotating log file creation. 14 | - Custom log message filtering. 15 | - Temporary deactivation and reactivation of logging. 16 | 17 | Modules: 18 | - logging: Python's built-in logging module. 19 | - os: Module for interacting with the operating system. 20 | - logging.handlers: Module for logging handler classes. 21 | - datetime: Module for manipulating dates and times. 22 | 23 | Workflow: 24 | 1. Initialize the custom logger with a weekly rotating file handler. 25 | 2. Provide methods to deactivate and reactivate logging. 26 | """ 27 | from modules import config 28 | 29 | import logging 30 | import os 31 | from logging.handlers import TimedRotatingFileHandler 32 | from datetime import datetime 33 | 34 | class CustomFilter(logging.Filter): 35 | """ 36 | Custom filter to exclude log messages containing specific text. 37 | 38 | :param record: The log record to filter. 39 | :type record: logging.LogRecord 40 | :return: Whether the log record should be included. 41 | :rtype: bool 42 | """ 43 | def filter(self, record): 44 | return 'data={"value":' not in record.getMessage() 45 | 46 | class CustomLogger: 47 | """ 48 | A custom logger class that logs messages to a weekly log file. 49 | 50 | This logger initializes a TimedRotatingFileHandler that creates a new log file 51 | every week. It also includes a custom filter to exclude specific log messages. 52 | 53 | Usage: 54 | Initialize the custom logger in your script to start logging: 55 | >>> logger = CustomLogger() 56 | 57 | Temporarily deactivate logging: 58 | >>> CustomLogger.fh_deactivateLogging() 59 | 60 | Reactivate logging: 61 | >>> CustomLogger.fh_reactivateLogging() 62 | 63 | Output examples: 64 | - Log file created at logs/YYYY-WW.log with formatted log messages. 65 | - Log messages filtered based on custom criteria. 66 | 67 | Modules: 68 | - logging: Provides logging capabilities for creating log messages and managing log levels. 69 | - os: Interacts with the operating system for file and directory operations. 70 | - logging.handlers: Provides a handler that rotates log files at specified intervals. 71 | - datetime: Manipulates dates and times for timestamping log files. 72 | """ 73 | def __init__(self): 74 | # Create and configure file handler 75 | logsDirectory = config.logsDirectory 76 | 77 | formatterFile = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 78 | 79 | # Create file handler and set level to DEBUG for file output 80 | logFilename = os.path.join(logsDirectory, f'{datetime.now().strftime("%Y-%W")}.log') 81 | fh = TimedRotatingFileHandler(logFilename, when='W0', backupCount=52) 82 | fh.setLevel(logging.DEBUG) 83 | fh.setFormatter(formatterFile) 84 | 85 | # Add custom filter to file handler 86 | fh.addFilter(CustomFilter()) 87 | 88 | # Add file handler to the root logger 89 | rootLogger = logging.getLogger() 90 | rootLogger.propagate = False 91 | rootLogger.setLevel(logging.DEBUG) # Ensure root logger level is set to DEBUG 92 | if not any(isinstance(handler, TimedRotatingFileHandler) for handler in rootLogger.handlers): 93 | rootLogger.addHandler(fh) 94 | 95 | # Remove default console handler to avoid outputs since we want to display them colored with less information 96 | for handler in rootLogger.handlers: 97 | if isinstance(handler, logging.StreamHandler): 98 | rootLogger.removeHandler(handler) 99 | 100 | @staticmethod 101 | def fh_deactivateLogging(): 102 | """ 103 | Temporarily deactivate logging. 104 | 105 | This method sets the logging level of TimedRotatingFileHandler to NOTSET, 106 | effectively silencing logging output temporarily. 107 | 108 | Usage: 109 | Temporarily deactivate logging: 110 | >>> CustomLogger.deactivate_logging() 111 | """ 112 | rootLogger = logging.getLogger() 113 | for handler in rootLogger.handlers: 114 | if isinstance(handler, TimedRotatingFileHandler): 115 | handler.setLevel(logging.NOTSET) 116 | 117 | @staticmethod 118 | def fh_reactivateLogging(): 119 | """ 120 | Reactivate logging. 121 | 122 | This method sets the logging level of TimedRotatingFileHandler back to DEBUG, 123 | re-enabling logging output. 124 | 125 | Usage: 126 | Reactivate logging: 127 | >>> CustomLogger.reactivate_logging() 128 | """ 129 | rootLogger = logging.getLogger() 130 | for handler in rootLogger.handlers: 131 | if isinstance(handler, TimedRotatingFileHandler): 132 | handler.setLevel(logging.DEBUG) -------------------------------------------------------------------------------- /src/utilities/propagateMessage.py: -------------------------------------------------------------------------------- 1 | # Authors https://github.com/JulianStiebler/ 2 | # Organization: https://github.com/rogueEdit/ 3 | # Repository: https://github.com/rogueEdit/OnlineRogueEditor 4 | # Contributors: None except Author 5 | # Date of release: 25.06.2024 6 | # Last Edited: 28.06.2024 7 | 8 | from utilities import cFormatter, Color 9 | 10 | # Initialize a global message buffer list 11 | messageBuffer = [] 12 | 13 | # Function to clear the message buffer 14 | def fh_clearMessageBuffer(): 15 | global messageBuffer 16 | messageBuffer = [] 17 | 18 | # Function to append messages to the message buffer 19 | def fh_appendMessageBuffer(type, message, isLogging=False): 20 | global messageBuffer 21 | messageBuffer.append((type, message, isLogging)) 22 | 23 | # Function to print messages from the message buffer 24 | def fh_printMessageBuffer(): 25 | global messageBuffer 26 | for color, text, isLogging in messageBuffer: 27 | if isinstance(color, Color): # Check if color is a valid Color enum 28 | cFormatter.fh_centerText(text, length=55, fillChar='>') 29 | cFormatter.print(color, f'{text}', isLogging) 30 | else: 31 | print(text) 32 | messageBuffer = [] # Clear buffer after printing 33 | 34 | def fh_redundantMesage(changedItems, message, target=None, propagate=True): 35 | if target: 36 | changedItems.append(f'{target}: {message}') 37 | cFormatter.print(Color.INFO, f'{target}: {message}') 38 | if propagate: 39 | fh_appendMessageBuffer(Color.INFO, f'{target}: {message}') 40 | else: 41 | changedItems.append(f'{message}') 42 | cFormatter.print(Color.INFO, f'{message}') 43 | if propagate: 44 | fh_appendMessageBuffer(Color.INFO, f'{message}') --------------------------------------------------------------------------------