├── .coveragerc ├── .gitattributes ├── .github ├── CODEOWNERS └── workflows │ ├── master.yml │ ├── pull-requests.yml │ └── tags.yml ├── .gitignore ├── .style.yapf ├── .yapfignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── codecov.yml ├── mypy.ini ├── pyproject.toml ├── setup.cfg ├── src └── pychan │ ├── __init__.py │ ├── __main__.py │ ├── api.py │ ├── logger.py │ ├── models.py │ └── py.typed ├── tests ├── __init__.py ├── html │ ├── pol_archive.html │ ├── pol_catalog.html │ ├── pol_moderator_post.html │ └── pol_thread_posts.html ├── json │ ├── search_results.json │ ├── search_results_unparsable_partial.json │ └── search_results_unparsable_whole.json ├── test_api.py ├── test_api_no_mocks.py └── test_models.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = true 3 | source = pychan 4 | omit = 5 | **/pychan/__init__.py 6 | 7 | [report] 8 | fail_under = 90 9 | show_missing = True 10 | skip_empty = True 11 | exclude_lines = 12 | pragma: no cover 13 | def __repr__ 14 | def __str__ 15 | if __name__ == .__main__.: 16 | 17 | [xml] 18 | output = coverage.xml 19 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # These files will be ignored by GitHub when it computes programming language statistics for this repository 2 | tests/**/*.html linguist-vendored 3 | tests/**/*.json linguist-vendored 4 | 5 | # These files will be normalized on commit (CRLF converted to LF) 6 | * text eol=lf 7 | 8 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @cooperwalbrun 2 | -------------------------------------------------------------------------------- /.github/workflows/master.yml: -------------------------------------------------------------------------------- 1 | name: master 2 | on: 3 | push: 4 | branches: 5 | - master 6 | jobs: 7 | unit-test: 8 | name: Unit Test with Code Coverage Analysis 9 | runs-on: ubuntu-latest 10 | strategy: 11 | max-parallel: 4 12 | matrix: 13 | python-version: ["3.10", "3.11", "3.12"] 14 | steps: 15 | - name: Checkout source code 16 | uses: actions/checkout@v4 17 | - name: Set up Python ${{ matrix.python-version }} 18 | uses: actions/setup-python@v5 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install .[github_actions] 25 | - name: Type-check the source code 26 | run: mypy src 27 | - name: Unit test with code coverage analysis on Python ${{ matrix.python-version }} 28 | run: tox 29 | - name: Upload test coverage report to Codecov 30 | uses: codecov/codecov-action@v4 31 | with: 32 | token: ${{ secrets.CODECOV_TOKEN }} 33 | fail_ci_if_error: true 34 | flags: python${{ matrix.python-version }} 35 | files: coverage.xml 36 | -------------------------------------------------------------------------------- /.github/workflows/pull-requests.yml: -------------------------------------------------------------------------------- 1 | name: Pull Requests 2 | on: 3 | pull_request: 4 | types: [opened, edited, reopened, synchronize] 5 | branches: 6 | - master 7 | jobs: 8 | unit-test: 9 | name: Unit Test with Code Coverage Analysis 10 | runs-on: ubuntu-latest 11 | strategy: 12 | max-parallel: 4 13 | matrix: 14 | python-version: ["3.10", "3.11", "3.12"] 15 | steps: 16 | - name: Checkout source code 17 | uses: actions/checkout@v4 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v5 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | pip install .[github_actions] 26 | - name: Type-check the source code 27 | run: mypy src 28 | - name: Unit test with code coverage analysis on Python ${{ matrix.python-version }} 29 | run: tox 30 | - name: Upload test coverage report to Codecov 31 | uses: codecov/codecov-action@v4 32 | with: 33 | token: ${{ secrets.CODECOV_TOKEN }} 34 | fail_ci_if_error: true 35 | flags: python${{ matrix.python-version }} 36 | files: coverage.xml 37 | -------------------------------------------------------------------------------- /.github/workflows/tags.yml: -------------------------------------------------------------------------------- 1 | name: Tags 2 | on: 3 | push: 4 | tags: 5 | - "v*" 6 | jobs: 7 | upload: 8 | name: Upload to PyPI 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout source code 12 | uses: actions/checkout@v4 13 | - name: Set up Python 3.12 14 | uses: actions/setup-python@v5 15 | with: 16 | python-version: "3.12" 17 | - name: Install dependencies 18 | run: | 19 | python -m pip install --upgrade pip 20 | pip install build 21 | - name: Build distributions 22 | # The following command(s) must produce ready-to-upload artifacts in the "dist" folder 23 | run: python -m build 24 | - name: Upload distributions to PyPI 25 | uses: pypa/gh-action-pypi-publish@release/v1 26 | with: 27 | user: __token__ 28 | password: ${{ secrets.PYPI_API_TOKEN }} 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | 140 | # JetBrains (IntelliJ IDEA, PyCharm, etc) 141 | .idea/ 142 | .idea_modules/ 143 | /out/ 144 | *.iml 145 | *.iws 146 | 147 | # Visual Studio Code 148 | .vscode/ 149 | -------------------------------------------------------------------------------- /.style.yapf: -------------------------------------------------------------------------------- 1 | # See: https://github.com/google/yapf#knobs and https://github.com/google/yapf/blob/master/yapf/yapflib/style.py 2 | [style] 3 | ALLOW_SPLIT_BEFORE_DICT_VALUE = false 4 | BASED_ON_STYLE = pep8 5 | BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = false 6 | COALESCE_BRACKETS = true 7 | COLUMN_LIMIT = 100 8 | DEDENT_CLOSING_BRACKETS = true 9 | JOIN_MULTIPLE_LINES = true 10 | SPACES_AROUND_DICT_DELIMITERS = false 11 | SPLIT_ALL_COMMA_SEPARATED_VALUES = false 12 | SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES = true 13 | SPLIT_BEFORE_DOT = true 14 | SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true 15 | SPLIT_BEFORE_FIRST_ARGUMENT = true 16 | SPLIT_COMPLEX_COMPREHENSION = true 17 | -------------------------------------------------------------------------------- /.yapfignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cooperwalbrun/pychan/d842540b7ebea696ad16da4db6ed060be9aa3bec/.yapfignore -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## Unreleased 9 | 10 | Nothing currently! 11 | 12 | ## v0.9.0 - 2024-07-26 13 | 14 | ### Changed 15 | 16 | * Updated the version constraint of the `pyrate-limiter` dependency from `>=2.8,<3` to `>=3,<4` (by 17 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 18 | 19 | ## v0.8.0 - 2024-03-20 20 | 21 | ### Added 22 | 23 | * Python 3.12 is now an official build target for `pychan` (by 24 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 25 | 26 | ## v0.7.0 - 2023-12-16 27 | 28 | ### Changed 29 | 30 | * All 4chan HTTP operations will now use the `4chan.org` domain (previously, some HTTP operations 31 | used the `4channel.org` domain) (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 32 | 33 | ## v0.6.0 - 2023-04-09 34 | 35 | ### Added 36 | 37 | * The `Thread` and `Post` models each now have a `url` property which contains a complete URL 38 | linking directly to that particular thread or post in 4chan (by 39 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 40 | 41 | ### Fixed 42 | 43 | * The `search()` method will now raise a `ParsingError` when the data returned from 4chan is in an 44 | unexpected format (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 45 | * The `search()` method will no longer induce HTTP 403 errors (thanks to its new Cloudflare-oriented 46 | arguments) (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 47 | 48 | ### Changed 49 | 50 | * Whitespace-only thread titles will now be converted into `None` within the `get_threads()` method 51 | (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 52 | * The `search()` method now expects `user_agent` and `cloudflare_cookies` arguments containing the 53 | `User-Agent` and `Cookie` header data needed to bypass the Cloudflare firewall in front of 4chan's 54 | REST API (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 55 | 56 | ## v0.5.0 - 2023-04-05 57 | 58 | ### Added 59 | 60 | * The `File` model now has an `is_spoiler` field indicating whether the image was a "spoiler" image 61 | (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 62 | 63 | ### Changed 64 | 65 | * The `get_threads()` method no longer iterates through a board's pages; instead, it directly 66 | scrapes threads from the catalog for the given board (by 67 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 68 | 69 | ### Removed 70 | 71 | * Support for Python 3.9 has been removed; `pychan` will now only build for Python 3.10 and 3.11 (by 72 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 73 | 74 | ## v0.4.2 - 2023-04-04 75 | 76 | ### Fixed 77 | 78 | * The `get_boards()` method will no longer induce HTTP 403 errors (by 79 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 80 | 81 | ## v0.4.1 - 2022-11-18 82 | 83 | ### Changed 84 | 85 | * The `FourChan` class will no longer output any warnings when 4chan's pages for a given board have 86 | been exhausted by the `get_threads()` generator (by 87 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 88 | 89 | ## v0.4.0 - 2022-11-16 90 | 91 | ### Added 92 | 93 | * The `FourChan` class now supports the optional exception-oriented arguments 94 | `raise_http_exceptions` and `raise_parsing_exceptions` (by 95 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 96 | * There are now integration tests in the project that will actually connect to 4chan instead of 97 | relying on mocks (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 98 | * Added project configuration for using `mypy` to statically type-check code during development and 99 | in the GitHub Actions pipeline (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 100 | * Implemented proper typing throughout the source code and added a `py.typed` file per PEP 561 (by 101 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 102 | 103 | ### Changed 104 | 105 | * The `Thread` class's `board` field will now always feature the "sanitized" version of the board 106 | (e.g. `a` instead of `/a/`, `/a`, or `a/`) (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 107 | * The `ratelimit` module was replaced by the `pyrate-limiter` module within the internal request 108 | throttler (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 109 | 110 | ## v0.3.5 - 2022-11-08 111 | 112 | ### Added 113 | 114 | * Added support for Python 3.11 to the pipeline and project configuration (by 115 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 116 | 117 | ## v0.3.4 - 2022-10-12 118 | 119 | ### Changed 120 | 121 | * The author email address in the wheel's metadata is now set to a real email address (by 122 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 123 | 124 | ## v0.3.3 - 2022-08-05 125 | 126 | ### Added 127 | 128 | * `pychan` now supports Python 3.9 in addition to Python 3.10+ (by 129 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 130 | 131 | ## v0.3.2 - 2022-08-05 132 | 133 | ### Added 134 | 135 | * The `Post` model now includes replies to the given post in a `replies` field (by 136 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 137 | 138 | ## v0.3.1 - 2022-08-04 139 | 140 | ### Fixed 141 | 142 | * The `get_threads()` method will no longer return duplicate threads, even when waiting long periods 143 | of time between `yield`s (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 144 | 145 | ## v0.3.0 - 2022-07-31 146 | 147 | ### Added 148 | 149 | * Implemented the `get_archived_threads()` method (by 150 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 151 | 152 | ### Changed 153 | 154 | * Changed the `stickied` and `closed` fields on the `Thread` model to `is_stickied` and `is_closed` 155 | (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 156 | 157 | ## v0.2.3 - 2022-07-30 158 | 159 | ### Added 160 | 161 | * The `FourChan`, `LogLevel`, and `PychanLogger` entities can now be imported directly from `pychan` 162 | (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 163 | * Added the `name` and `is_moderator` fields to the `Poster` model (by 164 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 165 | 166 | ### Changed 167 | 168 | * The `poster` field on the `Post` model is no longer optional (by 169 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 170 | 171 | ## v0.2.2 - 2022-07-30 172 | 173 | ### Added 174 | 175 | * The `File` model now includes the file's size and dimensions (by 176 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 177 | * Added more logging to the `FourChan` class (by 178 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 179 | 180 | ### Changed 181 | 182 | * All methods in the `FourChan` class now properly handle "unparsable" boards (by 183 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 184 | 185 | ## v0.2.1 - 2022-07-30 186 | 187 | ### Added 188 | 189 | * The `Post` model now includes the post's timestamp in the `timestamp` field (by 190 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 191 | * The `Thread` model now has `stickied` and `closed` boolean fields (by 192 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 193 | * Created the `Poster` model and updated the `Post` model to use it (by 194 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 195 | 196 | ### Fixed 197 | 198 | * Fixed thread titles being truncated and ellipsized (by 199 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 200 | 201 | ## v0.2.0 - 2022-07-29 202 | 203 | ### Added 204 | 205 | * Implemented the `search()` method, which leverages 4chan's native search functionality internally 206 | (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 207 | * Added docstrings to all user-facing functions (by 208 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 209 | 210 | ### Changed 211 | 212 | * Changed the `get_all_threads_for_board()` method name to `get_threads()` (by 213 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 214 | 215 | ### Removed 216 | 217 | * Removed the opinionated `get_all_threads()` method to simplify the code base and keep its scope 218 | more appropriate for its desired intent (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 219 | 220 | ## v0.1.1 - 2022-07-27 221 | 222 | ### Changed 223 | 224 | * The `File` model's `name` field will no longer ever be `None` (to correspond to 4chan's real 225 | behavior) (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 226 | 227 | ### Fixed 228 | 229 | * Fixed file names not being properly discovered on posts from the `get_posts()` operation (by 230 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 231 | 232 | ## v0.1.0 - 2022-07-27 233 | 234 | ### Added 235 | 236 | * Created the project (by [@cooperwalbrun](https://github.com/cooperwalbrun)) 237 | * Implemented the initial functionality for fetching threads, posts, and boards (by 238 | [@cooperwalbrun](https://github.com/cooperwalbrun)) 239 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to pychan 2 | 3 | 1. [Development Workspace Setup](#development-workspace-setup) 4 | 2. [Dependency Management](#dependency-management) 5 | 1. [Adding New Dependencies](#adding-new-dependencies) 6 | 2. [Updating Dependencies](#updating-dependencies) 7 | 3. [Updating Python in the Virtual Environment](#updating-python-in-the-virtual-environment) 8 | 4. [Unit Testing](#unit-testing) 9 | 5. [Code Policy](#code-policy) 10 | 1. [YAPF](#yapf) 11 | 2. [Typing](#typing) 12 | 3. [Imports](#imports) 13 | 6. [Changelog](#changelog) 14 | 15 | ## Development Workspace Setup 16 | 17 | To start development and testing, ensure you have Python >=3.10 and <4.0 installed, 18 | [activate the virtual environment](https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments) 19 | with something like 20 | 21 | ```bash 22 | $ python -m venv venv 23 | $ source venv/Scripts/activate 24 | ``` 25 | 26 | Then, run one of the following commands in this project's root directory: 27 | 28 | ```bash 29 | pip install -e .[development] # Development and unit testing purposes 30 | pip install -e .[testing] # Unit testing purposes only 31 | ``` 32 | 33 | ## Dependency Management 34 | 35 | ### Adding New Dependencies 36 | 37 | >Before issuing these commands, **ensure that you are in the virtual environment** and that you 38 | >executed the `pip install` command intended for development purposes (see 39 | >[Development Workspace Setup](#development-workspace-setup)). 40 | 41 | 1. Add the package to your environment. 42 | ```bash 43 | pip install $PACKAGE # Adds the package to your virtual environment 44 | ``` 45 | 46 | 2. Test the dependency out (i.e. write your code) to ensure it satisfies your needs and that it 47 | works well with existing dependencies. 48 | 49 | 3. Add a reference to the package in the appropriate place(s). You must do only **one** of the tasks 50 | below. 51 | * If it is a **unit testing-only** dependency, add it under `testing =` in `setup.cfg` and 52 | `deps =` in `tox.ini`. 53 | * If it is a **testing and development** dependency, add it under `development =` in 54 | `setup.cfg`. 55 | * If it is specific to a **GitHub Actions** workflow, add it under `github_actions =` in 56 | `setup.cfg`. 57 | * If it is a **production/runtime** dependency, add it under `install_requires =` in 58 | `setup.cfg`. Unless you know lower versions will work too, specify the version you installed 59 | as a lower bound (e.g. `somemodule>=X.Y.Z`). It is also recommended to specify an upper bound 60 | to avoid situations where a breaking change was introduced in a major version upgrade (e.g. 61 | `somemodule>=X.Y.Z,Before issuing these commands, **ensure that you are in the virtual environment**. 66 | 67 | Simply update the version parameters in `setup.cfg` and issue the install command(s) for this 68 | application (see [Development Workspace Setup](#development-workspace-setup) above). 69 | 70 | ### Updating Python in the Virtual Environment 71 | 72 | After the newer version of Python is installed on your machine, then use `venv`'s built-in 73 | functionality for upgrading Python in a virtual environment. Ensure that you execute this command 74 | from **outside** your virtual environment, otherwise it will not work properly. 75 | 76 | >Note: in this example, we have already updated our system path to point to the newer version of 77 | >Python. 78 | 79 | ```bash 80 | python -m venv --upgrade $YOUR_VENV_DIRECTORY_LOCATION 81 | ``` 82 | 83 | Alternatively, you could delete your `venv` and recreate it, though that will not be as quick as 84 | running the command above. 85 | 86 | ## Unit Testing 87 | 88 | To run the unit tests, **ensure you are in the virtual environment** with development or testing 89 | dependencies installed (see above) if running tests via `pytest`, otherwise ensure you are **not** 90 | in a virtual environment if running tests via `tox`. Then, run the corresponding command in this 91 | project's root directory: 92 | 93 | ```properties 94 | python -m pytest --cov # Run unit tests using your current virtual environment's Python interpreter 95 | tox # Run unit tests using tox (requires that you have the necessary Python interpreters on your machine) 96 | ``` 97 | 98 | ## Code Policy 99 | 100 | ### YAPF 101 | 102 | This project uses [yapf](https://github.com/google/yapf) to handle formatting, and contributions to 103 | its code are expected to be formatted with YAPF (within reason) using the settings in 104 | [.style.yapf](.style.yapf). 105 | 106 | If YAPF is mangling your code in an unmaintainable fashion, you can selectively disable it using the 107 | comments `# yapf: disable` and `# yapf: enable`. Whenever the former appears, the latter must appear 108 | afterwards (this project will not tolerate disabling YAPF for large code blocks and/or entire 109 | files). Disabling YAPF should be done sparingly. 110 | 111 | ### Typing 112 | 113 | In addition to YAPF formatting, code should be appropriately accompanied by type annotations. This 114 | includes: 115 | * Variables and constants in global scope (regardless of whether the variable name is prefixed with 116 | an underscore) 117 | * All method parameters and method return values 118 | * Any declaration that may have a non-obvious, ambiguous, or otherwise complex type signature 119 | 120 | In addition to type annotations, all changes to this project's code are expected to be checked with 121 | [mypy](https://github.com/python/mypy). To run this check, simply execute the `mypy src` command at 122 | the root of this project. 123 | 124 | ### Imports 125 | 126 | Imports should be sorted. Most IDEs support this functionality via keybindings or even via on-save 127 | operations. 128 | 129 | ## Changelog 130 | 131 | This project uses a [CHANGELOG.md](CHANGELOG.md) to track changes. Please update this document along 132 | with your changes when you make a pull request (you can place your changes beneath the `Unreleased` 133 | section near the top). Please also tag your line items with a reference to your GitHub profile. You 134 | should use the formatting that is already in place (see the document for more information). 135 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pychan 2 | 3 | >Update 2025-05-25: this project has been archived and will no longer be maintained, as 4chan 4 | >recently made changes to its firewall infrastructure (in response to the attacks in April 2025) 5 | >which made it more difficult to scrape its content. 6 | 7 | 1. [Overview](#overview) 8 | 2. [Installation](#installation) 9 | 3. [Usage](#usage) 10 | 1. [General Notes](#general-notes) 11 | 2. [Setup](#setup) 12 | 3. [Fetch Board Names](#fetch-board-names) 13 | 4. [Fetch Threads](#fetch-threads) 14 | 5. [Fetch Archived Threads](#fetch-archived-threads) 15 | 6. [Search 4chan](#search-4chan) 16 | 1. [About Cloudflare](#about-cloudflare) 17 | 2. [Search 4chan Code Example](#search-4chan-code-example) 18 | 7. [Fetch Posts for a Specific Thread](#fetch-posts-for-a-specific-thread) 19 | 4. [pychan Models](#pychan-models) 20 | 1. [Threads](#threads) 21 | 2. [Posts](#posts) 22 | 1. [A Note About Replies](#a-note-about-replies) 23 | 3. [Posters](#posters) 24 | 4. [Files](#files) 25 | 5. [Contributing](#contributing) 26 | 27 | ## Overview 28 | 29 | `pychan` is a Python client for interacting with 4chan. 4chan does not have an official API, and 30 | attempts to implement one by third parties have tended to languish, so instead, this library 31 | provides abstractions over interacting with (scraping) 4chan directly. `pychan` is object-oriented 32 | and its implementation is lazy where reasonable (using Python Generators) in order to optimize 33 | performance and minimize superfluous blocking I/O operations. 34 | 35 | ## Installation 36 | 37 | If you have Python >=3.10 and <4.0 installed, `pychan` can be installed from PyPI using 38 | something like 39 | 40 | ```bash 41 | pip install pychan 42 | ``` 43 | 44 | ## Usage 45 | 46 | ### General Notes 47 | 48 | All 4chan interactions are throttled internally by sleeping the executing thread. If you execute 49 | `pychan` in a multithreaded way, you will not get the benefits of this throttling. `pychan` does not 50 | take responsibility for the consequences of excessive HTTP requests in such cases. 51 | 52 | ### Setup 53 | 54 | ```python 55 | from pychan import FourChan, LogLevel, PychanLogger 56 | 57 | # With all defaults (logging disabled, all exceptions raised) 58 | fourchan = FourChan() 59 | 60 | # Tell pychan to gracefully ignore HTTP exceptions, if any, within its internal logic 61 | fourchan = FourChan(raise_http_exceptions=False) 62 | 63 | # Tell pychan to gracefully ignore parsing exceptions, if any, within its internal logic 64 | fourchan = FourChan(raise_parsing_exceptions=False) 65 | 66 | # Configure logging explicitly 67 | logger = PychanLogger(LogLevel.INFO) 68 | fourchan = FourChan(logger=logger) 69 | 70 | # Use all of the above settings at once 71 | logger = PychanLogger(LogLevel.INFO) 72 | fourchan = FourChan(logger=logger, raise_http_exceptions=True, raise_parsing_exceptions=True) 73 | ``` 74 | 75 | The rest of the examples in this `README` assume that you have already created an instance of the 76 | `FourChan` class as shown above. 77 | 78 | ### Fetch Board Names 79 | 80 | This function dynamically fetches boards from 4chan at call time. 81 | 82 | >Note: boards which are not compatible with `pychan` are not returned in this list. 83 | 84 | ```python 85 | boards = fourchan.get_boards() 86 | # Sample return value: 87 | # ['a', 'b', 'c', 'd', 'e', 'g', 'gif', 'h', 'hr', 'k', 'm', 'o', 'p', 'r', 's', 't', 'u', 'v', 'vg', 'vm', 'vmg', 'vr', 'vrpg', 'vst', 'w', 'wg', 'i', 'ic', 'r9k', 's4s', 'vip', 'qa', 'cm', 'hm', 'lgbt', 'y', '3', 'aco', 'adv', 'an', 'bant', 'biz', 'cgl', 'ck', 'co', 'diy', 'fa', 'fit', 'gd', 'hc', 'his', 'int', 'jp', 'lit', 'mlp', 'mu', 'n', 'news', 'out', 'po', 'pol', 'pw', 'qst', 'sci', 'soc', 'sp', 'tg', 'toy', 'trv', 'tv', 'vp', 'vt', 'wsg', 'wsr', 'x', 'xs'] 88 | ``` 89 | 90 | ### Fetch Threads 91 | 92 | ```python 93 | # Iterate over all threads in /b/ 94 | for thread in fourchan.get_threads("b"): 95 | # Do stuff with the thread 96 | print(thread.title) 97 | # You can also iterate over all the posts in the thread 98 | for post in fourchan.get_posts(thread): 99 | # Do stuff with the post - refer to the model documentation in pychan's README for details 100 | print(post.text) 101 | ``` 102 | 103 | ### Fetch Archived Threads 104 | 105 | >Note: some boards do not have an archive (e.g. `/b/`). Such boards will either return an empty list 106 | >or raise an exception depending on how you have configured your `FourChan` instance. 107 | 108 | The threads returned by this function will always have a `title` field containing the text shown in 109 | 4chan's interface under the "Excerpt" column header. This text can be either the thread's real title 110 | or a preview of the original post's text. Passing any of the threads returned by this method to the 111 | `get_posts()` method will automatically correct the `title` field (if necessary) on the thread that 112 | gets attached to the returned posts. See 113 | [Fetch Posts for a Specific Thread](#fetch-posts-for-a-specific-thread) for more details. 114 | 115 | >Technically, `pychan` could address the `title` behavior described above by issuing an additional 116 | >HTTP request for each thread to get its real title, but in the spirit of making the smallest number 117 | >of HTTP requests possible, `pychan` directly uses the excerpt instead. 118 | 119 | ```python 120 | for thread in fourchan.get_archived_threads("pol"): 121 | # Do stuff with the thread 122 | print(thread.title) 123 | # You can also iterate over all the posts in the thread 124 | for post in fourchan.get_posts(thread): 125 | # Do stuff with the post - refer to the model documentation in pychan's README for details 126 | print(post.text) 127 | ``` 128 | 129 | ### Search 4chan 130 | 131 | #### About Cloudflare 132 | 133 | Performing searches against 4chan is much more cumbersome than accessing the rest of 4chan's data. 134 | This is because 4chan has a Cloudflare firewall in front of its REST API, so the only way to get 135 | data back from searches is to supply the HTTP request information needed to bypass Cloudflare's 136 | anti-bot checks. Ultimately, this amounts to passing certain headers along with the HTTP request, 137 | but the challenge comes from actually acquiring such headers. 138 | 139 | It is currently beyond the scope of `pychan` to generate these headers for you, so if you would like 140 | to automate the circumvention of Cloudflare's protections, you may want to look into using a project 141 | like one of the following (this list is alphabetized and not exhaustive): 142 | 143 | * [ultrafunkamsterdam/undetected-chromedriver](https://github.com/ultrafunkamsterdam/undetected-chromedriver) 144 | * [VeNoMouS/cloudscraper](https://github.com/VeNoMouS/cloudscraper) 145 | * [wkeeling/selenium-wire](https://github.com/wkeeling/selenium-wire) 146 | 147 | A manual way to acquire these values is to perform a 4chan search using a web browser and leverage 148 | the browser's Developer Tools to trace the network requests that were made during the search. The 149 | request that contains the Cloudflare values will have been made to `https://find.4chan.org/api` with 150 | some query parameters. Once you have found this request, copy the `User-Agent` and `Cookie` values 151 | that were sent in your request, then pass them to `pychan`'s `search()` method. Be aware that the 152 | Cloudflare cookie(s) have an expiration on them, so this manual workaround will only return results 153 | until Cloudflare invalidates your cookie(s). After that, you will need to acquire new values. 154 | 155 | #### Search 4chan Code Example 156 | 157 | >Note: closed/stickied/archived threads are never returned in search results. 158 | 159 | ```python 160 | # This "threads" variable will contain a Python Generator (not a list) in order to facilitate laziness 161 | threads = fourchan.search( 162 | board="b", 163 | text="ylyl", 164 | user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36", 165 | cloudflare_cookies={ 166 | "cf_clearance": "bm2RICpcDeR4cXoC2nfI_cnZcbAkN4UYpN6c1zzeb8g-1440859602-0-160" 167 | } 168 | ) 169 | for thread in threads: 170 | # The thread object is the same class as the one returned by get_threads() 171 | for post in fourchan.get_posts(thread): 172 | # Do stuff with the post - refer to the model documentation in pychan's README for details 173 | print(post.text) 174 | ``` 175 | 176 | ### Fetch Posts for a Specific Thread 177 | 178 | ```python 179 | from pychan.models import Thread 180 | 181 | # Instantiate a Thread instance with which to query for posts 182 | thread = Thread("int", 168484869) 183 | 184 | # Note: the thread contained within the returned posts will have all applicable metadata (such as 185 | # title and sticky status), regardless of whether you provided such data above - pychan will 186 | # "auto-discover" all metadata and include it in the post models' copy of the thread 187 | posts = fourchan.get_posts(thread) 188 | ``` 189 | 190 | ## pychan Models 191 | 192 | The following tables summarize all the kinds of data that are available on the various models used 193 | by this library. 194 | 195 | Also note that all model classes in `pychan` implement the following methods: 196 | 197 | * `__repr__` 198 | * `__str__` 199 | * `__hash__` 200 | * `__eq__` 201 | * `__iter__` - this is implemented so that the models may be passed to Python's `tuple()` function 202 | * `__copy__` 203 | * `__deepcopy__` 204 | 205 | ### Threads 206 | 207 | The table below corresponds to the `pychan.models.Thread` class. 208 | 209 | | Field | Type | Example Value(s) | 210 | | ----- | ---- | ---------------- | 211 | | `thread.board` | `str` | `"b"`, `"int"` 212 | | `thread.number` | `int` | `882774935`, `168484869` 213 | | `thread.title` | `Optional[str]` | `None`, `"YLYL thread"` 214 | | `thread.is_stickied` | `bool` | `True`, `False` 215 | | `thread.is_closed` | `bool` | `True`, `False` 216 | | `thread.is_archived` | `bool` | `True`, `False` 217 | | `thread.url` | `str` | `"https://boards.4chan.org/a/thread/251097344"` 218 | 219 | ### Posts 220 | 221 | The table below corresponds to the `pychan.models.Post` class. 222 | 223 | | Field | Type | Example Value(s) | 224 | | ----- | ---- | ---------------- | 225 | | `post.thread` | `Thread` | `pychan.models.Thread` 226 | | `post.number` | `int` | `882774935`, `882774974` 227 | | `post.timestamp` | [datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime) | [datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime) 228 | | `post.poster` | `Poster` | `pychan.models.Poster` 229 | | `post.text` | `str` | `">be me\n>be bored\n>write pychan\n>somehow it works"` 230 | | `post.is_original_post` | `bool` | `True`, `False` 231 | | `post.file` | `Optional[File]` | `None`, `pychan.models.File` 232 | | `post.replies` | `list[Post]` | `[]`, `[pychan.models.Post, pychan.models.Post]` 233 | | `post.url` | `str` | `"https://boards.4chan.org/a/thread/251097344#p251097419"` 234 | 235 | #### A Note About Replies 236 | 237 | The `replies` field shown above is purely a convenience feature `pychan` provides for accessing all 238 | posts within a thread which used the `>>` operator to "reply" to the current post. However, it is 239 | not necessary to use the `replies` field to access all available posts in a thread; when you call 240 | the `get_posts()` method, you will still receive all the posts (in the order they were posted) as a 241 | single, flat list. 242 | 243 | ### Posters 244 | 245 | The table below corresponds to the `pychan.models.Poster` class. 246 | 247 | | Field | Type | Example Value(s) | 248 | | ----- | ---- | ---------------- | 249 | | `poster.name` | `str` | `"Anonymous"` 250 | | `poster.is_moderator` | `bool` | `True`, `False` 251 | | `poster.id` | `Optional[str]` | `None`, `"BYagKQXI"` 252 | | `poster.flag` | `Optional[str]` | `None`, `"United States"`, `"Canada"` 253 | 254 | ### Files 255 | 256 | The table below corresponds to the `pychan.models.File` class. 257 | 258 | | Field | Type | Example Value(s) | 259 | | ----- | ---- | ---------------- | 260 | | `file.url` | `str` | `"https://i.4cdn.org/pol/1658892700380132.jpg"` 261 | | `file.name` | `str` | `"wojak.jpg"`, `"i feel alone.jpg"` 262 | | `file.size` | `str` | `"601 KB"` 263 | | `file.dimensions` | `tuple[int, int]` | `(1920, 1080)`, `(800, 600)` 264 | | `file.is_spoiler` | `bool` | `True`, `False` 265 | 266 | ## Contributing 267 | 268 | See [CONTRIBUTING.md](CONTRIBUTING.md) for developer-oriented information. 269 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | require_ci_to_pass: true 3 | 4 | coverage: 5 | precision: 2 6 | round: down 7 | range: "70...100" 8 | status: 9 | patch: 10 | default: 11 | target: 30% 12 | project: 13 | default: 14 | target: 85% 15 | 16 | comment: 17 | layout: "reach,diff,flags,files,footer" 18 | behavior: default 19 | require_changes: false 20 | 21 | ignore: 22 | - "src/pychan/__init__.py" 23 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | warn_return_any = True 3 | warn_unused_configs = True 4 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=46.1.0", "setuptools_scm[toml]>=5", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.setuptools_scm] 6 | # See configuration details in https://github.com/pypa/setuptools_scm 7 | version_scheme = "no-guess-dev" 8 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = pychan 3 | author = cooperwalbrun 4 | author_email = mail@cooperwalbrun.io 5 | description = A Python library for interacting with 4chan in a programmatically-friendly way. 6 | long_description = file:README.md 7 | long_description_content_type = text/markdown 8 | url = https://github.com/cooperwalbrun/pychan 9 | platforms = any 10 | classifiers = 11 | Programming Language :: Python :: 3.10 12 | Programming Language :: Python :: 3.11 13 | Programming Language :: Python :: 3.12 14 | License :: OSI Approved :: GNU General Public License v3 (GPLv3) 15 | Operating System :: OS Independent 16 | 17 | [options] 18 | zip_safe = False 19 | packages = find: 20 | include_package_data = True 21 | package_dir = =src 22 | python_requires = >=3.10,<4 23 | install_requires = 24 | beautifulsoup4>=4.11.1,<5 25 | importlib-metadata 26 | pyrate-limiter>=3,<4 27 | requests>=2.28,<3 28 | types-beautifulsoup4>=4.11,<5 29 | types-requests>=2.28,<3 30 | 31 | [options.packages.find] 32 | where = src 33 | exclude = tests 34 | 35 | [options.extras_require] 36 | testing = 37 | mypy 38 | pytest 39 | pytest-cov 40 | pytest-mock 41 | responses 42 | tox 43 | github_actions = 44 | # Interpolation via %()s works because setuptools uses this: https://docs.python.org/3/library/configparser.html#configparser.BasicInterpolation 45 | %(testing)s 46 | tox-gh-actions 47 | development = 48 | %(testing)s 49 | yapf 50 | 51 | [test] 52 | # The line below tells setuptools whether to install everything listed under options.extras_require when you issue "python setup.py test" 53 | extras = False 54 | 55 | [tool:pytest] 56 | addopts = --cov -p no:warnings 57 | norecursedirs = 58 | dist 59 | build 60 | .tox 61 | testpaths = tests 62 | 63 | [aliases] 64 | dists = sdist bdist_wheel 65 | 66 | [bdist_wheel] 67 | # We do not support functionality on Python versions other than the ones specified in this file 68 | universal = 0 69 | 70 | [devpi:upload] 71 | no-vcs = 1 72 | formats = bdist_wheel 73 | -------------------------------------------------------------------------------- /src/pychan/__init__.py: -------------------------------------------------------------------------------- 1 | from importlib_metadata import PackageNotFoundError, version 2 | 3 | from pychan import api, logger 4 | 5 | try: 6 | __version__ = version(__name__) 7 | except PackageNotFoundError: 8 | __version__ = "unknown" 9 | finally: 10 | del version, PackageNotFoundError 11 | 12 | FourChan = api.FourChan 13 | PychanLogger = logger.PychanLogger 14 | LogLevel = logger.LogLevel 15 | -------------------------------------------------------------------------------- /src/pychan/__main__.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | print("This is a Python-only interface. You should not execute it as a CLI.") 3 | -------------------------------------------------------------------------------- /src/pychan/api.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import json 3 | import re 4 | from datetime import datetime, timezone 5 | from typing import Optional, Generator, TypedDict, cast 6 | from uuid import uuid4 7 | 8 | import requests 9 | from bs4 import BeautifulSoup, Tag 10 | from pyrate_limiter import Limiter, Rate, Duration 11 | from requests import Response 12 | 13 | from pychan.logger import PychanLogger, LogLevel 14 | from pychan.models import File, Poster 15 | from pychan.models import Post, Thread 16 | 17 | # Note: using a max_delay of 2000 below should make it so that this rate limiter will block the 18 | # current thread until the request can be issued again. The reason for this is that using a delay 19 | # greater than the actual throttle (1 second per request) will ensure we always wait long enough for 20 | # the request to be issued. 21 | # See: https://pyratelimiter.readthedocs.io/en/latest/index.html?highlight=wait#rate-limit-delays 22 | _limiter = Limiter(Rate(1, Duration.SECOND), max_delay=2000) 23 | 24 | 25 | def _find_first(selectable_entity: Tag, selector: str) -> Optional[Tag]: 26 | ret = selectable_entity.select(selector) 27 | if ret is not None and len(ret) > 0: 28 | return ret[0] 29 | else: 30 | return None 31 | 32 | 33 | def _get_attribute(tag: Optional[Tag], attribute: str) -> Optional[str]: 34 | # Below, it is imperative that we use hasattr() instead of "x in y" syntax because these do not 35 | # mean the same thing in BeautifulSoup's API (only the former behaves as expected) 36 | if tag is not None and hasattr(tag, attribute): 37 | ret = tag[attribute] 38 | return ret[0] if isinstance(ret, list) else ret 39 | else: 40 | return None 41 | 42 | 43 | def _safe_id_parse(text: Optional[str], *, offset: int) -> Optional[int]: 44 | # This function is meant to parse ID attribute values from 4chan's HTML into numeric values 45 | # containing just the raw ID number. Refer to the unit tests to see expected inputs/outputs. 46 | if text is not None and len(text) > offset: 47 | try: 48 | return int(text[offset:]) 49 | except Exception: 50 | return None 51 | else: 52 | return None 53 | 54 | 55 | def _text(element: Optional[Tag]) -> Optional[str]: 56 | return element.text if element is not None and len(element.text.strip()) > 0 else None 57 | 58 | 59 | def _sanitize_board(board: str) -> str: 60 | return board.lower().replace("/", "").strip() 61 | 62 | 63 | JSONThread = TypedDict( 64 | "JSONThread", { 65 | "sub": Optional[str | bool], "sticky": Optional[int], "closed": Optional[int] 66 | } 67 | ) 68 | JSONCatalog = TypedDict("JSONCatalog", {"threads": dict[str, JSONThread]}) 69 | 70 | 71 | class ParsingError(Exception): 72 | pass 73 | 74 | 75 | class FourChan: 76 | _UNPARSABLE_BOARDS = ["f"] 77 | _POST_TEXT_SELECTOR = "blockquote.postMessage" 78 | _USER_AGENT_HEADER_NAME = "User-Agent" 79 | 80 | def __init__( 81 | self, 82 | *, 83 | logger: Optional[PychanLogger] = None, 84 | raise_http_exceptions: bool = True, 85 | raise_parsing_exceptions: bool = True 86 | ): 87 | """ 88 | 89 | :param logger: The logger instance to read for logging configuration, if any. 90 | :param raise_http_exceptions: Whether internal exceptions related to HTTP errors (e.g. HTTP 91 | 500) should be raised so that users of this FourChan instance 92 | will see them. 93 | :param raise_parsing_exceptions: Whether internal exceptions related to parsing errors (e.g. 94 | due to invalid/unrecognized HTML on HTTP responses) should 95 | be raised so that users of this FourChan instance will see 96 | them. 97 | """ 98 | self._agent = str(uuid4()) 99 | self._logger = logger if logger is not None else PychanLogger(LogLevel.OFF) 100 | self._raise_http_exceptions = raise_http_exceptions 101 | self._raise_parsing_exceptions = raise_parsing_exceptions 102 | 103 | def _parse_error(self, message: str) -> None: 104 | if self._raise_parsing_exceptions: 105 | raise ParsingError(message) 106 | 107 | def _parse_file_from_html(self, post_html_element: Tag) -> Optional[File]: 108 | self._logger.debug(f"Attempting to parse a File out of {post_html_element}...") 109 | file_text = _find_first(post_html_element, ".fileText") 110 | file_anchor = _find_first(post_html_element, ".fileText a") 111 | href = _get_attribute(file_anchor, "href") 112 | if file_text is not None and file_anchor is not None and href is not None: 113 | href = "https:" + href if href.startswith("//") else href 114 | metadata = re.search(r"\((.+), ([0-9]+x[0-9]+)\)", file_text.text) 115 | if metadata is not None and len(metadata.groups()) > 1: 116 | size = metadata.group(1) 117 | dimensions = metadata.group(2).split("x") 118 | return File( 119 | href, 120 | file_anchor.text, 121 | size, (int(dimensions[0]), int(dimensions[1])), 122 | is_spoiler=_find_first(post_html_element, ".imgspoiler") is not None 123 | ) 124 | else: 125 | message = f"No file metadata could not be parsed from {file_text.text}" 126 | self._logger.error(message) 127 | self._parse_error(message) 128 | return None 129 | else: 130 | self._logger.debug(f"No file was discovered in {post_html_element}") 131 | return None 132 | 133 | def _parse_poster_from_html(self, post_html_element: Tag) -> Optional[Poster]: 134 | self._logger.debug(f"Attempting to parse a Poster out of {post_html_element}...") 135 | name = _text(_find_first(post_html_element, ".nameBlock > .name")) 136 | mod = _find_first(post_html_element, ".nameBlock > .id_mod") is not None 137 | uid = _text(_find_first(post_html_element, ".posteruid span")) 138 | flag = _get_attribute(_find_first(post_html_element, ".flag"), "title") 139 | if name is not None: 140 | return Poster(name, mod_indicator=mod, id=uid, flag=flag) 141 | else: 142 | self._logger.debug(f"No poster was discovered in {post_html_element}") 143 | return None 144 | 145 | def _parse_post_from_html(self, thread: Thread, post_html_element: Tag) -> Optional[Post]: 146 | self._logger.debug(f"Attempting to parse a Post out of {post_html_element}...") 147 | timestamp = _get_attribute(_find_first(post_html_element, ".dateTime"), "data-utc") 148 | if timestamp is None: 149 | message = f"No post timestamp was discovered in {post_html_element}" 150 | self._logger.error(message) 151 | self._parse_error(message) 152 | return None 153 | 154 | parsed_timestamp = datetime.fromtimestamp(int(timestamp), timezone.utc) 155 | poster = self._parse_poster_from_html(post_html_element) 156 | if poster is None: 157 | message = f"No poster was discovered in {post_html_element}" 158 | self._logger.error(message) 159 | self._parse_error(message) 160 | return None 161 | 162 | message_tag = _find_first(post_html_element, self._POST_TEXT_SELECTOR) 163 | if message_tag is not None: 164 | line_break_placeholder = str(uuid4()) 165 | # The following approach to preserve HTML line breaks in the final post text is 166 | # based on this: https://stackoverflow.com/a/61423104 167 | for line_break in message_tag.select("br"): 168 | line_break.replaceWith(line_break_placeholder) 169 | text = message_tag.text.replace(line_break_placeholder, "\n") 170 | 171 | id = _safe_id_parse(_get_attribute(message_tag, "id"), offset=1) 172 | op = hasattr(post_html_element, "class") and "op" in post_html_element["class"] 173 | 174 | if id is not None and len(text) > 0: 175 | return Post( 176 | thread, 177 | id, 178 | parsed_timestamp, 179 | poster, 180 | text, 181 | is_original_post=op, 182 | file=self._parse_file_from_html(post_html_element) 183 | ) 184 | else: 185 | return None 186 | else: 187 | message = f"No post text was discovered in {post_html_element}" 188 | self._logger.error(message) 189 | self._parse_error(message) 190 | return None 191 | 192 | def _parse_catalog_json_from_javascript(self, javascript_text: str) -> Optional[JSONCatalog]: 193 | text = javascript_text 194 | result = re.search(r"var\s*catalog\s*=\s*({.+};)", text) 195 | if result is None: 196 | return None 197 | 198 | while result is not None: 199 | candidate = result.group(1).removesuffix(";") 200 | try: 201 | return cast(JSONCatalog, json.loads(candidate)) 202 | except: 203 | text = candidate[:-1] 204 | # We already removed the "var catalog" portion above, so now we just check the JSON 205 | result = re.search(r"({.+};)", text) 206 | 207 | message = ( 208 | f"Unable to parse the catalog JSON out of the following JavaScript: {javascript_text}" 209 | ) 210 | self._logger.error(message) 211 | self._parse_error(message) 212 | return None 213 | 214 | def _is_unparsable_board(self, board: str) -> bool: 215 | if board in self._UNPARSABLE_BOARDS: 216 | self._logger.warn(( 217 | f"Detected that you are trying to interact with an unparsable board: {board}. " 218 | f"To avoid errors and undefined behavior, pychan will not attempt to interact with " 219 | f"this board." 220 | )) 221 | return True 222 | else: 223 | return False 224 | 225 | def _throttle_request(self) -> None: 226 | # The throttling mechanism is defined as a dedicated function like this so that it can be 227 | # mocked in unit tests in a straightforward manner 228 | _limiter.try_acquire("4chan") 229 | return 230 | 231 | def _request_helper( 232 | self, 233 | url: str, 234 | *, 235 | headers: Optional[dict[str, str]] = None, 236 | params: Optional[dict[str, str]] = None 237 | ) -> Optional[Response]: 238 | self._throttle_request() 239 | 240 | h = {} if headers is None else headers 241 | response = requests.get( 242 | url, headers={ 243 | self._USER_AGENT_HEADER_NAME: self._agent, **h 244 | }, params=params 245 | ) 246 | if response.status_code == 200: 247 | return response 248 | else: 249 | self._logger.error(f"Unexpected status code {response.status_code} when fetching {url}") 250 | if self._raise_http_exceptions: 251 | response.raise_for_status() 252 | return None 253 | 254 | def get_boards(self) -> list[str]: 255 | """ 256 | Fetches all the boards within 4chan. 257 | 258 | :return: The board names (without slashes in their names) currently available on 4chan. 259 | """ 260 | 261 | ret = [] 262 | self._logger.info("Fetching all boards from 4chan...") 263 | 264 | # Below, we just choose a random 4chan page which includes the header/footer containing the 265 | # list of boards 266 | response = self._request_helper("https://boards.4chan.org/pol/catalog") 267 | if response is not None: 268 | soup = BeautifulSoup(response.text, "html.parser") 269 | board_list = _find_first(soup, ".boardList") 270 | if board_list is not None: 271 | for anchor in board_list.select("a"): 272 | board = anchor.text 273 | if board not in self._UNPARSABLE_BOARDS: 274 | ret.append(board) 275 | 276 | self._logger.info(f"Fetched {len(ret)} board(s) from 4chan") 277 | return ret 278 | 279 | def get_threads(self, board: str) -> list[Thread]: 280 | """ 281 | Fetches all threads from a given board's catalog. 282 | 283 | :param board: The board name to fetch threads for. You may include slashes. Examples: "/b/", 284 | "b", "vg/", "/vg" 285 | :return: A list of threads currently in the board. 286 | """ 287 | sanitized_board = _sanitize_board(board) 288 | if self._is_unparsable_board(sanitized_board): 289 | return [] 290 | 291 | self._logger.info(f"Fetching threads for board /{sanitized_board}/...") 292 | 293 | response = self._request_helper(f"https://boards.4chan.org/{sanitized_board}/catalog") 294 | if response is not None: 295 | soup = BeautifulSoup(response.text, "html.parser") 296 | for script in soup.select('script[type="text/javascript"]'): 297 | json_data = self._parse_catalog_json_from_javascript(script.text) 298 | if json_data is not None and "threads" in json_data and \ 299 | isinstance(json_data["threads"], dict): 300 | ret = [] 301 | for id, thread in json_data["threads"].items(): 302 | parsed_id = _safe_id_parse(id, offset=0) 303 | if parsed_id is not None: 304 | title = thread.get("sub") 305 | if isinstance(title, bool): 306 | # The title will only be a boolean if no title exists (False) 307 | title = None 308 | title = title if title is not None and len(title.strip()) > 0 else None 309 | ret.append( 310 | Thread( 311 | sanitized_board, 312 | parsed_id, 313 | title=title, 314 | is_stickied=thread.get("sticky") == 1, 315 | is_closed=thread.get("closed") == 1, 316 | is_archived=False 317 | ) 318 | ) 319 | 320 | if len(ret) > 0: 321 | return ret 322 | message = ( 323 | f"No thread data could be parsed out of the HTML for the catalog page of the board " 324 | f"/{sanitized_board}/" 325 | ) 326 | self._logger.error(message) 327 | self._parse_error(message) 328 | return [] 329 | 330 | def get_archived_threads(self, board: str) -> list[Thread]: 331 | """ 332 | Fetches archived threads for a specific board. The titles of the returned threads will be 333 | the "excerpt" shown in 4chan, which could be either the thread's real title or a preview of 334 | the original post's text. 335 | 336 | :param board: The board name to fetch threads for. You may include slashes. Examples: "/b/", 337 | "b", "vg/", "/vg" 338 | :return: The list of threads currently in the archive. 339 | """ 340 | sanitized_board = _sanitize_board(board) 341 | if self._is_unparsable_board(sanitized_board): 342 | return [] 343 | 344 | self._logger.info(f"Fetching archived threads for board /{sanitized_board}/...") 345 | 346 | response = self._request_helper(f"https://boards.4chan.org/{sanitized_board}/archive") 347 | ret = [] 348 | if response is not None: 349 | soup = BeautifulSoup(response.text, "html.parser") 350 | for table_row in soup.select("#arc-list tbody tr"): 351 | id = _text(_find_first(table_row, "td")) 352 | if id is not None: 353 | ret.append( 354 | Thread( 355 | sanitized_board, 356 | int(id), 357 | title=_text(_find_first(table_row, ".teaser-col")), 358 | is_stickied=False, 359 | is_closed=False, 360 | is_archived=True 361 | ) 362 | ) 363 | 364 | return ret 365 | 366 | def get_posts(self, thread: Thread) -> list[Post]: 367 | """ 368 | Fetches all the posts (includes the original post and all replies) within a thread. 369 | 370 | :param thread: The thread from which to fetch posts. 371 | :return: The list of posts currently in the thread. If there are no replies on the thread, 372 | the returned list can be expected to have a single element (the original post). 373 | """ 374 | t = copy.deepcopy(thread) 375 | t.board = _sanitize_board(t.board) 376 | 377 | if self._is_unparsable_board(t.board): 378 | return [] 379 | 380 | self._logger.info(f"Fetching posts for {t}...") 381 | 382 | response = self._request_helper( 383 | "https://boards.4chan.org/{}/thread/{}/".format(t.board, t.number) 384 | ) 385 | if response is None: 386 | return [] 387 | 388 | soup = BeautifulSoup(response.text, "html.parser") 389 | ret: list[Post] = [] 390 | for post in soup.select(".post"): 391 | p = self._parse_post_from_html(t, post) 392 | if p is not None: 393 | for quote_link in post.select(f"{self._POST_TEXT_SELECTOR} a.quotelink"): 394 | href = _get_attribute(quote_link, "href") 395 | if href is not None and href.startswith("#p"): 396 | # The #p check in the href above also guards against the situation where 397 | # a post is quote-linking to a post in a different thread, which is 398 | # currently beyond the scope of this function's implementation 399 | quoted_post_number = _safe_id_parse(href, offset=len("#p")) 400 | for ret_post in ret: 401 | if ret_post.number == quoted_post_number and \ 402 | not any([r.number == p.number for r in ret_post.replies]): 403 | ret_post.replies.append(p) 404 | break 405 | 406 | if p.is_original_post: 407 | t.title = _text(_find_first(post, ".desktop .subject")) 408 | t.is_stickied = _find_first(post, ".desktop .stickyIcon") is not None 409 | t.is_closed = _find_first(post, ".desktop .closedIcon") is not None 410 | t.is_archived = _find_first(post, ".desktop .archivedIcon") is not None 411 | p.thread = t 412 | 413 | ret.append(p) 414 | 415 | return ret 416 | 417 | def search(self, *, board: str, text: str, user_agent: str, 418 | cloudflare_cookies: dict[str, str]) -> Generator[Thread, None, None]: 419 | """ 420 | Executes a given text query in a given board. This method leverages 4chan's native search 421 | functionality. 422 | 423 | :param board: The board within which to perform the search. You may include slashes. 424 | Examples: "/b/", "b", "vg/", "/vg" 425 | :param text: The text against which to search. 426 | :param user_agent: The User-Agent header value to use in the HTTP request. If this value is 427 | not the same as the one that is "associated" with the provided 428 | cloudflare_cookies, you will receive HTTP 403 errors. 429 | :param cloudflare_cookies: A dictionary mapping cookie names to their values, where these 430 | cookies are appropriate for bypassing the Cloudflare checks in 431 | front of the 4chan API. If this value is not the same one that is 432 | "associated" with the provided user_agent, you will receive HTTP 433 | 403 errors. 434 | :return: A Generator which yields threads one at a time until every thread in the search 435 | results has been returned. 436 | """ 437 | sanitized_board = _sanitize_board(board) 438 | if self._is_unparsable_board(sanitized_board): 439 | return 440 | 441 | query = text.strip() 442 | 443 | def get(o: int) -> Optional[Response]: 444 | cookie = "; ".join([f"{k}={v}" for k, v in cloudflare_cookies.items()]) 445 | return self._request_helper( 446 | "https://find.4chan.org/api", 447 | headers={ 448 | "Accept": "application/json", 449 | "Origin": "https://boards.4chan.org", 450 | "Referer": "https://boards.4chan.org/", 451 | self._USER_AGENT_HEADER_NAME: user_agent, 452 | "Cookie": cookie 453 | }, 454 | params={ 455 | "o": str(o), "q": query, "b": sanitized_board 456 | } 457 | ) 458 | 459 | seen_thread_numbers = set() 460 | 461 | offset = 0 462 | new_this_iteration = True 463 | while new_this_iteration: 464 | new_this_iteration = False 465 | 466 | self._logger.info(( 467 | f"Searching offset {offset} for threads in board /{sanitized_board}/ matching text " 468 | f'"{text}"...' 469 | )) 470 | 471 | response = get(offset) 472 | offset += 10 473 | 474 | if response is not None: 475 | threads = response.json().get("threads", []) 476 | if isinstance(threads, list): 477 | for t in threads: 478 | try: 479 | number = t.get("thread", "") 480 | posts = t.get("posts", []) 481 | if len(number) > 1 and len(posts) > 0: 482 | title = posts[0].get("sub", "") 483 | title = title if len(title.strip()) > 0 else None 484 | thread = Thread( 485 | t.get("board", sanitized_board), 486 | int(number[1:]), 487 | title=title, 488 | # Closed/stickied/archived threads are not returned in search results 489 | is_stickied=False, 490 | is_closed=False, 491 | is_archived=False 492 | ) 493 | if thread.number not in seen_thread_numbers: 494 | new_this_iteration = True 495 | seen_thread_numbers.add(thread.number) 496 | yield thread 497 | else: 498 | self._logger.debug( 499 | f"Skipping a duplicate thread in the search results: {thread}" 500 | ) 501 | except Exception as e: 502 | self._parse_error(str(e)) 503 | else: 504 | self._parse_error( 505 | f'Detected an unexpected structure in the "threads" JSON field: {threads}' 506 | ) 507 | -------------------------------------------------------------------------------- /src/pychan/logger.py: -------------------------------------------------------------------------------- 1 | from enum import IntEnum 2 | 3 | 4 | class LogLevel(IntEnum): 5 | DEBUG = 0, 6 | INFO = 1, 7 | WARN = 2, 8 | ERROR = 3, 9 | OFF = 4 10 | 11 | 12 | class PychanLogger: 13 | _RED = u"\u001b[31m" 14 | _GREEN = u"\u001b[32m" 15 | _YELLOW = u"\u001b[33m" 16 | _RESET = u"\u001b[0m" 17 | 18 | def __init__(self, level: LogLevel = LogLevel.OFF, *, colorized: bool = True): 19 | self._log_level = level 20 | self._colorized = colorized 21 | 22 | def _red(self, text: str) -> str: 23 | return self._RED + text + self._RESET if self._colorized else text 24 | 25 | def _green(self, text: str) -> str: 26 | return self._GREEN + text + self._RESET if self._colorized else text 27 | 28 | def _yellow(self, text: str) -> str: 29 | return self._YELLOW + text + self._RESET if self._colorized else text 30 | 31 | def debug(self, message: str) -> None: 32 | if self._log_level <= LogLevel.DEBUG: 33 | print(self._green("[pychan] " + message)) 34 | 35 | def info(self, message: str) -> None: 36 | if self._log_level <= LogLevel.INFO: 37 | print("[pychan] " + message) 38 | 39 | def warn(self, message: str) -> None: 40 | if self._log_level <= LogLevel.WARN: 41 | print(self._yellow("[pychan] " + message)) 42 | 43 | def error(self, message: str) -> None: 44 | if self._log_level <= LogLevel.ERROR: 45 | print(self._red("[pychan] " + message)) 46 | -------------------------------------------------------------------------------- /src/pychan/models.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from datetime import datetime 3 | from typing import Any, Optional, Generator 4 | 5 | 6 | class Thread: 7 | def __init__( 8 | self, 9 | board: str, 10 | number: int, 11 | *, 12 | title: Optional[str] = None, 13 | is_stickied: bool = False, 14 | is_closed: bool = False, 15 | is_archived: bool = False 16 | ): 17 | self.board = board 18 | self.number = number 19 | self.title = title 20 | self.is_stickied = is_stickied 21 | self.is_closed = is_closed 22 | self.is_archived = is_archived 23 | 24 | @property 25 | def url(self) -> str: 26 | return f"https://boards.4chan.org/{self.board}/thread/{self.number}" 27 | 28 | def __repr__(self) -> str: 29 | return f"Thread({self.url})" 30 | 31 | def __str__(self) -> str: 32 | return repr(self) 33 | 34 | def __hash__(self) -> int: 35 | return hash((self.board, self.number)) 36 | 37 | def __eq__(self, other: Any) -> bool: 38 | if isinstance(other, Thread): 39 | return self.board == other.board and self.number == other.number 40 | else: 41 | return False 42 | 43 | def __iter__(self) -> Generator[Any, None, None]: 44 | # We implement __iter__ so this class can be serialized as a tuple 45 | for field in [self.board, 46 | self.number, 47 | self.title, 48 | self.is_stickied, 49 | self.is_closed, 50 | self.is_archived]: 51 | yield field 52 | 53 | def __copy__(self): 54 | return Thread( 55 | self.board, 56 | self.number, 57 | title=self.title, 58 | is_stickied=self.is_stickied, 59 | is_closed=self.is_closed, 60 | is_archived=self.is_archived 61 | ) 62 | 63 | def __deepcopy__(self, memo: dict[Any, Any]): 64 | return Thread( 65 | copy.deepcopy(self.board, memo), 66 | self.number, 67 | title=copy.deepcopy(self.title, memo), 68 | is_stickied=self.is_stickied, 69 | is_closed=self.is_closed, 70 | is_archived=self.is_archived 71 | ) 72 | 73 | 74 | class File: 75 | def __init__( 76 | self, url: str, name: str, size: str, dimensions: tuple[int, int], *, is_spoiler: bool 77 | ): 78 | self.url = url 79 | self.name = name 80 | self.size = size 81 | self.dimensions = dimensions 82 | self.is_spoiler = is_spoiler 83 | 84 | def __repr__(self) -> str: 85 | return f"File({self.url})" 86 | 87 | def __str__(self) -> str: 88 | return repr(self) 89 | 90 | def __hash__(self) -> int: 91 | return hash(self.url) 92 | 93 | def __eq__(self, other: Any) -> bool: 94 | if isinstance(other, File): 95 | return self.url == other.url 96 | else: 97 | return False 98 | 99 | def __iter__(self) -> Generator[Any, None, None]: 100 | # We implement __iter__ so this class can be serialized as a tuple 101 | for field in [self.url, self.name, self.size, self.dimensions, self.is_spoiler]: 102 | yield field 103 | 104 | def __copy__(self): 105 | return File(self.url, self.name, self.size, self.dimensions, is_spoiler=self.is_spoiler) 106 | 107 | def __deepcopy__(self, memo: dict[Any, Any]): 108 | return File( 109 | copy.deepcopy(self.url, memo), 110 | copy.deepcopy(self.name, memo), 111 | copy.deepcopy(self.size, memo), 112 | copy.deepcopy(self.dimensions, memo), 113 | is_spoiler=self.is_spoiler 114 | ) 115 | 116 | 117 | class Poster: 118 | def __init__( 119 | self, 120 | name: str, 121 | *, 122 | mod_indicator: bool = False, 123 | id: Optional[str] = None, 124 | flag: Optional[str] = None 125 | ): 126 | self.name = name 127 | self._mod_indicator = mod_indicator 128 | self.id = id 129 | self.flag = flag 130 | 131 | @property 132 | def is_moderator(self) -> bool: 133 | return self._mod_indicator or self.name != "Anonymous" 134 | 135 | def __repr__(self) -> str: 136 | return "Poster(name={}, is_moderator={}, id={}, flag={})".format( 137 | self.name, self.is_moderator, self.id, self.flag 138 | ) 139 | 140 | def __str__(self) -> str: 141 | return repr(self) 142 | 143 | def __hash__(self) -> int: 144 | return hash(self.id) 145 | 146 | def __eq__(self, other: Any) -> bool: 147 | if isinstance(other, Poster): 148 | return self.name == other.name and self.id == other.id 149 | else: 150 | return False 151 | 152 | def __iter__(self) -> Generator[Any, None, None]: 153 | # We implement __iter__ so this class can be serialized as a tuple 154 | for field in [self.name, self._mod_indicator, self.id, self.flag]: 155 | yield field 156 | 157 | def __copy__(self): 158 | return Poster(self.name, mod_indicator=self._mod_indicator, id=self.id, flag=self.flag) 159 | 160 | def __deepcopy__(self, memo: dict[Any, Any]): 161 | return Poster( 162 | copy.deepcopy(self.name, memo), 163 | mod_indicator=self._mod_indicator, 164 | id=copy.deepcopy(self.id, memo), 165 | flag=copy.deepcopy(self.flag, memo) 166 | ) 167 | 168 | 169 | class Post: 170 | def __init__( 171 | self, 172 | thread: Thread, 173 | number: int, 174 | timestamp: datetime, 175 | poster: Poster, 176 | text: str, 177 | *, 178 | is_original_post: bool = False, 179 | file: Optional[File] = None, 180 | replies: Optional[list] = None 181 | ): 182 | self.thread = thread 183 | self.number = number 184 | self.timestamp = timestamp 185 | self.poster = poster 186 | self.text = text 187 | self.is_original_post = is_original_post 188 | self.file = file 189 | self.replies: list[Post] = replies if replies is not None else [] 190 | 191 | @property 192 | def url(self) -> str: 193 | return "https://boards.4chan.org/{}".format( 194 | f"{self.thread.board}/thread/{self.thread.number}#p{self.number}" 195 | ) 196 | 197 | def __repr__(self) -> str: 198 | return f"Post({self.url})" 199 | 200 | def __str__(self) -> str: 201 | return repr(self) 202 | 203 | def __hash__(self) -> int: 204 | return hash((self.number, self.thread.number)) 205 | 206 | def __eq__(self, other: Any) -> bool: 207 | if isinstance(other, Post): 208 | return self.number == other.number and self.thread == other.thread 209 | else: 210 | return False 211 | 212 | def __iter__(self) -> Generator[Any, None, None]: 213 | # We implement __iter__ so this class can be serialized as a tuple 214 | fields = list(self.thread) + [self.number, self.timestamp] + \ 215 | list(self.poster) + \ 216 | [ 217 | self.text, 218 | self.is_original_post, 219 | None if self.file is None else self.file.url, 220 | None if self.file is None else self.file.name, 221 | None if self.file is None else self.file.size, 222 | None if self.file is None else self.file.dimensions, 223 | len(self.replies) 224 | ] 225 | for field in fields: 226 | yield field 227 | 228 | def __copy__(self): 229 | return Post( 230 | self.thread, 231 | self.number, 232 | self.timestamp, 233 | self.poster, 234 | self.text, 235 | is_original_post=self.is_original_post, 236 | file=self.file, 237 | replies=self.replies 238 | ) 239 | 240 | def __deepcopy__(self, memo: dict[Any, Any]): 241 | return Post( 242 | copy.deepcopy(self.thread, memo), 243 | self.number, 244 | copy.deepcopy(self.timestamp, memo), 245 | copy.deepcopy(self.poster, memo), 246 | copy.deepcopy(self.text, memo), 247 | is_original_post=self.is_original_post, 248 | file=copy.deepcopy(self.file, memo), 249 | replies=copy.deepcopy(self.replies, memo) 250 | ) 251 | -------------------------------------------------------------------------------- /src/pychan/py.typed: -------------------------------------------------------------------------------- 1 | # This is a marker file for PEP 561. This package uses inline types instead of depending on the 2 | # existence of a third-party stub module. 3 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cooperwalbrun/pychan/d842540b7ebea696ad16da4db6ed060be9aa3bec/tests/__init__.py -------------------------------------------------------------------------------- /tests/html/pol_moderator_post.html: -------------------------------------------------------------------------------- 1 | /pol/ - Check the catalog before posting a new thread!Rep - Politically Incorrect - 4chan
[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / r / s / t / u / v / vg / vm / vmg / vr / vrpg / vst / w / wg] [i / ic] [r9k / s4s / vip / qa] [cm / hm / lgbt / y] [3 / aco / adv / an / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / pw / qst / sci / soc / sp / tg / toy / trv / tv / vp / vt / wsg / wsr / x / xs] [Settings] [Search] [Mobile] [Home]
/pol/ - Politically Incorrect


Thread closed.
You may not reply at this time.




File: check catalog.jpg (44 KB, 452x343)
44 KB
44 KB JPG

Check the catalog before posting a new thread!

Reply to existing threads about a topic instead of starting a new one. New users who do not abide by this principle will be temporarily blocked from creating threads. Mods will delete obvious duplicate threads and spam without notice. Don't bitch because your twitter screencap thread got deleted; there are probably other threads about it. Go look!




Delete Post: [File Only] Style:
All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
2 | -------------------------------------------------------------------------------- /tests/html/pol_thread_posts.html: -------------------------------------------------------------------------------- 1 | /pol/ - No.1 Hitler movie in Germany? - Politically Incorrect - 4chan
[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / r / s / t / u / v / vg / vm / vmg / vr / vrpg / vst / w / wg] [i / ic] [r9k / s4s / vip / qa] [cm / hm / lgbt / y] [3 / aco / adv / an / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / pw / qst / sci / soc / sp / tg / toy / trv / tv / vp / vt / wsg / wsr / x / xs] [Settings] [Search] [Mobile] [Home]
/pol/ - Politically Incorrect

Name
Options
Comment
Verification
4chan Pass users can bypass this verification. [Learn More] [Login]
Flag
File
  • Please read the Rules and FAQ before posting.
  • There are 4 posters in this thread.

08/21/20New boards added: /vrpg/, /vmg/, /vst/ and /vm/
05/04/17New trial board added: /bant/ - International/Random
10/04/16New board for 4chan Pass users: /vip/ - Very Important Posts
[Hide] [Show All]


Janitor applications are now closed. Thank you to everyone who applied!




File: hitler miss kromier.jpg (106 KB, 800x600)
106 KB
106 KB JPG
Apparently this movie smashed German box office records, and all the dialogue is ..NOT.. scripted.
>>
>>388462123
>>388462123
>>388462123
what movie?
>>
>>388462123
Funny movie but there was agenda with this film
>>
>>389829992 →
Look who's back.



Delete Post: [File Only] Style:
All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
2 | -------------------------------------------------------------------------------- /tests/json/search_results.json: -------------------------------------------------------------------------------- 1 | {"query": "democrat", "board": "news", "nhits": 529, "offset": "0", "threads": [{"board": "news", "thread": "t1077597", "posts": [{"no": 1077597, "now": "07/29/22(Fri)18:28:13", "name": "Anonymous", "sub": "Democrat corruption and grooming.", "capcode": "none", "com": "Two elected democeat officials, one a supreme court justice, the other was a chairman of the Democrat party, are sentenced for felony crimes of corruption and bribery.
The democrat party chairman is also currently charged with additional, unrelated crimes and awaiting another trial: two counts of Predatory Sexual Assault Against a Child, First Degree Rape and other charges.
https://www.nbcnewyork.com/news/local/crime-and-courts/ny-judge-democratic-power-broker-sentenced-for-bribery-scheme/3801152/
https://ag.ny.gov/press-release/2022/attorney-general-james-announces-sentencing-former-new-york-state-supreme-court
Attorney General James Announces Sentencing of Former New York State Supreme Court Justice and Former Chairman of Erie County Democratic Committee for Corruption
Former New York State Supreme Court Justice John Michalek Accepted Bribes
from Former Erie County Power Broker and Democratic Committee Chairman Steven Pigeon

NEW YORK – New York Attorney General Letitia James today announced the sentencing of Erie County power broker and former Chairman of the Erie County Democratic Committee, G. Steven Pigeon, 61, and former New York State Supreme Court Justice, John A. Michalek, 71, for their roles in a bribery scheme that influenced judicial decisions and official appointments. The Honorable Judge Donald F. Cerio, Jr. sentenced Michalek to one year and four months in jail and a $5,000 fine. Pigeon was sentenced to one year in jail to run concurrent to his federal four-month sentence and a $5,000 fine.

“New Yorkers put their trust in judges and public servants to serve the interests of the people, not make a mockery of our institutions for personal financial gain,” said Attorney General James.", "filename": "1657570966967", "ext": ".jpg", "w": 1080, "h": 1331, "tn_w": 202, "tn_h": 250, "tim": 1659119293375123, "time": 1659119293, "md5": "tapBxOrkojJmY0nAzIlH0Q==", "fsize": 258851}, {"no": 1077686, "now": "07/29/22(Fri)23:55:25", "name": "Anonymous", "capcode": "none", "com": ">>1077685
I'm just curious what you think about the juxtaposition - whereas Democrats seem perfectly happy to abandon their own when they get caught (i.e. Al Franken) yet Republicans have a habit of circling the wagons and protecting their own whenever one of them gets caught (i.e. Matt Gaetz, Trump, Jim Jordan). I don't see any Democrats rushing out to protect this guy so how is this not the polar opposite of what Republicans do? Lets not forget the entire Republican party is in crisis mode right now trying to cover up for the dozens of its members that actively worked with Trump to overturn a legal election and stay in power. Where is this comparable hive of Democrat corruption?", "tim": 1659138925530288, "time": 1659138925, "resto": 1077597}, {"no": 1077707, "now": "07/30/22(Sat)01:26:23", "name": "Anonymous", "capcode": "none", "com": ">>1077706
>Literal Olympic level mental gymnastics AF.
Engage with my points. Trump routinely pardoned his own friends after they'd been convicted of crimes. Trump and the Republicans came out and cried "witch hunt" any time any of their own had been found guilty of a crime. Give me an example of Joe Biden pardoning his friends or of Democrats calling criminal investigations of their own party members "witch hunts" being perpetrated by the "fake news media". Give me an example instead of just mumbling "mental gymnastics" and giving yourself a gold star.

>Democrats sure as fuck call everything "fake news" and "Russian" and protect their own using their propaganda outlets up until whenever the hell it is they are found to be guilty of their crimes.
You have to be trolling me. Trump and the Republicans are the ones who invented the term fake news. Its amazing that you're projecting and coping so hard you're trying to blame your dear leader's own catchphrases on Democrats. Give me some sort of Democrat crime or corruption that Democrats have blamed on Russian misinformation in the last 6 months. I'd love to see an example of this.", "tim": 1659144383136144, "time": 1659144383, "resto": 1077597}, {"no": 1077710, "now": "07/30/22(Sat)01:33:01", "name": "Anonymous", "capcode": "none", "com": ">>1077707
>Give me some sort of Democrat crime or corruption that Democrats have blamed on Russian misinformation in the last 6 months.
>In the last 6 months
I have plenty over 6 months.
Sadly, it's somewhat uncommon people get arrested, charged, and convicted In crimes within 6 months so I may have trouble meeting your artificially high bar you set waaaay up there", "tim": 1659144781030683, "time": 1659144781, "resto": 1077597}, {"no": 1077711, "now": "07/30/22(Sat)01:36:10", "name": "Anonymous", "capcode": "none", "com": ">>1077709
>No. Democrats call everything negative toward them Russian or fake news up until and sometimes after the person is convicted.
Again, its so hilarious you're trying to project the "fake news" mantra onto Democrats. Daddy Trump invented that and no amount of historical revision is going to zap that out of the brains of anyone who was alive in 2016. Secondly, give me an example of a prominent Democrat recently calling a conviction of one of its party members a witch hunt or Russian. You said it happens so clearly you can just shoot me a link to something you recall.

>I'm not engaging with a "whatabout trump" bullshit argument.
The conversation is about how Democrats treat convicted criminals in their own party versus how Republicans treat convicted criminals in their own party. A republican president pardoned several of his own friends after they'd been convicted of crimes and now the Republican party is covering for dozens of its own members who are being investigated for trying to overturn an election. Give me an equivalent of Democrats doing this.

None of this is a whatboutism. This is the subject of the conversation and you can't engage with it because you know you don't have an argument.", "tim": 1659144970905787, "time": 1659144970, "resto": 1077597}, {"no": 1077713, "now": "07/30/22(Sat)01:37:23", "name": "Anonymous", "capcode": "none", "com": ">>1077709
NTA but they keep calling it that because it's been proven to be Russian-made fake news. Now why do you think the Russians hate the democrat party so much to do that?", "tim": 1659145043014562, "time": 1659145043, "resto": 1077597}, {"no": 1077714, "now": "07/30/22(Sat)01:37:53", "name": "Anonymous", "capcode": "none", "com": ">>1077710
>I have plenty over 6 months.
Then list a few

>Sadly, it's somewhat uncommon people get arrested, charged, and convicted In crimes within 6 months so I may have trouble meeting your artificially high bar you set waaaay up there
Give me a few convictions in the last six months then. Also, this is not an artificial bar. This is the bar that Republicans have set. Trump and the Republicans called the convictions of Manafort and Stone witch hunts by a corrupt Democrat government. Trump then pardoned both of them even after they'd been found guilty by a court of law. Give me a story of Democrats calling a conviction of one of their party members a witch hunt by a corrupt Republican government.", "tim": 1659145073050273, "time": 1659145073, "resto": 1077597}, {"no": 1077726, "now": "07/30/22(Sat)01:57:58", "name": "Anonymous", "capcode": "none", "com": ">>1077721
>This conversation is about how Republicans act versus how Democrats act.
No, this conversation is about yet another Democrat party chairman being corrupt, accepting bribes, and diddling children and your only defense is "whatabout trump", who is an idiot and an asshole, but hasn't been arrested yet for any of these things, much less convicted", "tim": 1659146278757547, "time": 1659146278, "resto": 1077597}, {"no": 1077733, "now": "07/30/22(Sat)02:13:49", "name": "Anonymous", "capcode": "none", "com": ">>1077726
>No, this conversation is about yet another Democrat party chairman being corrupt, accepting bribes, and diddling children
So I can tell we've reached the point in the conversation where you realize you don't have an argument so you're not going to engage with any of my points.

>your only defense is "whatabout trump", who is an idiot and an asshole, but hasn't been arrested yet for any of these things, much less convicted
You've actually struck right to the heart of my argument. If Trump is an idiot and an asshole than what does that say about the Republican party who covered for him, enabled him and stood idly by while he pardoned several prominent Republican politicians and personal friends who had been convicted of crimes? This conversation is highlighting the difference between Democrats, who pretty routinely abandon their own once they get caught by the law and Republicans who have spent the past 6 years systematically defending and covering for every single corrupt member of their party. Trump set the precedent and Republicans supported it. I don't want to hear a defense of Trump. I want to hear a defense of those Republicans. Again, I realize you don't have an argument so I accept whatever shitpost you make next that completely ignores all of the points I made as your concession.", "tim": 1659147229687356, "time": 1659147229, "resto": 1077597}]}, {"board": "news", "thread": "t1077143", "posts": [{"no": 1077143, "now": "07/27/22(Wed)14:07:24", "name": "Anonymous", "sub": "In Reality, All The Actual Groomers Are Republicans", "capcode": "none", "com": "https://www.businessinsider.com/matt-gaetz-20-gop-voting-against-anti-sex-trafficking-bill-2022-7

The Frederick Douglass Trafficking Victims Prevention and Protection Reauthorization Act of 2022 was approved in the House for reauthorization with a massive majority of 401 votes to 20.

The act combats human trafficking — particularly sex trafficking — through severe penalties for perpetrators and support services for victims.

It first came into law as the Victims of Trafficking and Violence Protection Act of 2000, when it passed the House and Senate with almost no opposition, and has been reauthorized multiple times without significant challenge.

Gaetz has been under federal investigation since 2020 over the question of whether he had sex with a minor, and whether he paid for her to cross state lines, as The New York Times first reported. Paying for a minor to travel interstate for sex would count as sex-trafficking.

Gaetz has not been charged with anything and has consistently denied any wrongdoing.

A former associate, Joel Greenberg — whom Gaetz once called his "wingman"— has pleaded guilty to six charges, including sex trafficking a minor, Politico reported. Greenberg's sentencing has been delayed in order to cooperate with the investigation into Gaetz, per the outlet.

Gaetz did not immediately respond to Insider's query about the vote, made outside normal US working hours, about why he voted no.

In comments to Insider on Wednesday in response to a quip by a Mike Pence aide about the matter, a Gaetz spokesperson described the idea that he had engaged in sex-trafficking as a "debunked conspiracy theory."

Gaetz did not speak in a 40-minute debate on the day of the vote.", "filename": "ezgif-5-33b507731c", "ext": ".jpg", "w": 1180, "h": 842, "tn_w": 250, "tn_h": 178, "tim": 1658930844332982, "time": 1658930844, "md5": "7rojjwmsbrsoHOTlafdK/g==", "fsize": 169819}, {"no": 1077689, "now": "07/30/22(Sat)00:11:54", "name": "Anonymous", "capcode": "none", "com": ">>1077687
>That is the important part, they kept it to themselves. Now they are advocating for letting drag queens have access to children for storytime and some even want to push for pedophiles (MAPS, Minor Attracted Persons) as a protected legitimate sexual orientation. This is not okay.
I think this is the root of the issue - you're clearly worrying about things that aren't real. Firstly, nobody is "pushing" for drag queens to have "access" to children. Drag queens tell stories to children at public libraries and if you don't want to take your child then don't. Secondly, there's not a single Democrat politician who has pushed for pedophiles to be a protected sexual orientation. You're describing a position that nobody outside of a handful of schizophrenic people on Twitter hold. I think you use these made up examples to post hoc justify your disgust with gay people. The examples you're using of reasons you hate gay people isn't representative of 99.9% of gay people.

>I'm saying that the minority needs to learn to assimilate into society instead of being so vocal, ridiculous and demanding that society changes to adapt to them and their needs.
And I'm saying that if society followed your logic we'd still be in the dark ages. Several centuries ago it was only a small minority of people who thought that slavery was a bad thing. If we all followed your worldview then we'd still be shitting in the streets because only a small minority of scientists back then believed that germs existed. Your way of life is untennable.

>I'm open to free thought but I'm not open to being told to shut up just because I upset some random faggot.
Nobody's telling you to shut up. What people are telling you is that you don't have the right to solely dictate what does and doesn't get assimilated into society. The only reason you're here right now is because, at some point, a minority of people pushed their views to the point that it became accepted into larger society.", "tim": 1659139914457418, "time": 1659139914, "resto": 1077143}, {"no": 1077692, "now": "07/30/22(Sat)00:42:05", "name": "Anonymous", "capcode": "none", "com": ">>1077689
>>1077689
> nobody is "pushing" for drag queens to have "access" to children
Then how did these people even get there in the first place? There are people that want drag queens to be doing this. It's either the drag queens themselves or someone contacting them.
>Secondly, there's not a single Democrat politician who has pushed for pedophiles to be a protected sexual orientation.
So Senator Scott Weiner from California introducing SB-145 which will make it less likely for grown men to be put on predator lists for having sex with a minor isn't a push for pedophilia?
> If we all followed your worldview then we'd still be shitting in the streets because only a small minority of scientists back then believed that germs existed
And those scientists proved that germs are real and everyone realized they were silly for ostracizing them. With gays, we all know that they're comprised of a lot of degenerates in that community. How are you going to look at something like this and say "Yes, these people are well adjusted members of society, this should be allowed in all aspects of our lives: https://twitter.com/libsoftiktok/status/1553149757085716480
>What people are telling you is that you don't have the right to solely dictate what does and doesn't get assimilated into society.
I never said that solely I get to decide, what I'm saying is that a small very vocal group of gays shouldn't be trying to revamp society as a whole to accommodate for fetishists and degenerates. There are times when society should get revamped and go through revolution because it actually is the better thing to do. Look at modern day China. They're on the brink of collapse and I support it because the CCP is beyond corrupt. It was also a good thing that slavery got revamped because it is a terrible thing to do to people. But revamping society so gays can parade around dancing in the streets naked in full view of children is just detestable and beyond retarded.", "tim": 1659141725182931, "time": 1659141725, "resto": 1077143}]}]} 2 | -------------------------------------------------------------------------------- /tests/json/search_results_unparsable_partial.json: -------------------------------------------------------------------------------- 1 | {"query": "democrat", "board": "news", "nhits": 529, "offset": "0", "threads": [{"board": "news", "thread": "something intentionally invalid", "posts": [{"no": 1077597, "now": "07/29/22(Fri)18:28:13", "name": "Anonymous", "sub": "Democrat corruption and grooming.", "capcode": "none", "com": "Two elected democeat officials, one a supreme court justice, the other was a chairman of the Democrat party, are sentenced for felony crimes of corruption and bribery.
The democrat party chairman is also currently charged with additional, unrelated crimes and awaiting another trial: two counts of Predatory Sexual Assault Against a Child, First Degree Rape and other charges.
https://www.nbcnewyork.com/news/local/crime-and-courts/ny-judge-democratic-power-broker-sentenced-for-bribery-scheme/3801152/
https://ag.ny.gov/press-release/2022/attorney-general-james-announces-sentencing-former-new-york-state-supreme-court
Attorney General James Announces Sentencing of Former New York State Supreme Court Justice and Former Chairman of Erie County Democratic Committee for Corruption
Former New York State Supreme Court Justice John Michalek Accepted Bribes
from Former Erie County Power Broker and Democratic Committee Chairman Steven Pigeon

NEW YORK – New York Attorney General Letitia James today announced the sentencing of Erie County power broker and former Chairman of the Erie County Democratic Committee, G. Steven Pigeon, 61, and former New York State Supreme Court Justice, John A. Michalek, 71, for their roles in a bribery scheme that influenced judicial decisions and official appointments. The Honorable Judge Donald F. Cerio, Jr. sentenced Michalek to one year and four months in jail and a $5,000 fine. Pigeon was sentenced to one year in jail to run concurrent to his federal four-month sentence and a $5,000 fine.

“New Yorkers put their trust in judges and public servants to serve the interests of the people, not make a mockery of our institutions for personal financial gain,” said Attorney General James.", "filename": "1657570966967", "ext": ".jpg", "w": 1080, "h": 1331, "tn_w": 202, "tn_h": 250, "tim": 1659119293375123, "time": 1659119293, "md5": "tapBxOrkojJmY0nAzIlH0Q==", "fsize": 258851}, {"no": 1077686, "now": "07/29/22(Fri)23:55:25", "name": "Anonymous", "capcode": "none", "com": ">>1077685
I'm just curious what you think about the juxtaposition - whereas Democrats seem perfectly happy to abandon their own when they get caught (i.e. Al Franken) yet Republicans have a habit of circling the wagons and protecting their own whenever one of them gets caught (i.e. Matt Gaetz, Trump, Jim Jordan). I don't see any Democrats rushing out to protect this guy so how is this not the polar opposite of what Republicans do? Lets not forget the entire Republican party is in crisis mode right now trying to cover up for the dozens of its members that actively worked with Trump to overturn a legal election and stay in power. Where is this comparable hive of Democrat corruption?", "tim": 1659138925530288, "time": 1659138925, "resto": 1077597}, {"no": 1077707, "now": "07/30/22(Sat)01:26:23", "name": "Anonymous", "capcode": "none", "com": ">>1077706
>Literal Olympic level mental gymnastics AF.
Engage with my points. Trump routinely pardoned his own friends after they'd been convicted of crimes. Trump and the Republicans came out and cried "witch hunt" any time any of their own had been found guilty of a crime. Give me an example of Joe Biden pardoning his friends or of Democrats calling criminal investigations of their own party members "witch hunts" being perpetrated by the "fake news media". Give me an example instead of just mumbling "mental gymnastics" and giving yourself a gold star.

>Democrats sure as fuck call everything "fake news" and "Russian" and protect their own using their propaganda outlets up until whenever the hell it is they are found to be guilty of their crimes.
You have to be trolling me. Trump and the Republicans are the ones who invented the term fake news. Its amazing that you're projecting and coping so hard you're trying to blame your dear leader's own catchphrases on Democrats. Give me some sort of Democrat crime or corruption that Democrats have blamed on Russian misinformation in the last 6 months. I'd love to see an example of this.", "tim": 1659144383136144, "time": 1659144383, "resto": 1077597}, {"no": 1077710, "now": "07/30/22(Sat)01:33:01", "name": "Anonymous", "capcode": "none", "com": ">>1077707
>Give me some sort of Democrat crime or corruption that Democrats have blamed on Russian misinformation in the last 6 months.
>In the last 6 months
I have plenty over 6 months.
Sadly, it's somewhat uncommon people get arrested, charged, and convicted In crimes within 6 months so I may have trouble meeting your artificially high bar you set waaaay up there", "tim": 1659144781030683, "time": 1659144781, "resto": 1077597}, {"no": 1077711, "now": "07/30/22(Sat)01:36:10", "name": "Anonymous", "capcode": "none", "com": ">>1077709
>No. Democrats call everything negative toward them Russian or fake news up until and sometimes after the person is convicted.
Again, its so hilarious you're trying to project the "fake news" mantra onto Democrats. Daddy Trump invented that and no amount of historical revision is going to zap that out of the brains of anyone who was alive in 2016. Secondly, give me an example of a prominent Democrat recently calling a conviction of one of its party members a witch hunt or Russian. You said it happens so clearly you can just shoot me a link to something you recall.

>I'm not engaging with a "whatabout trump" bullshit argument.
The conversation is about how Democrats treat convicted criminals in their own party versus how Republicans treat convicted criminals in their own party. A republican president pardoned several of his own friends after they'd been convicted of crimes and now the Republican party is covering for dozens of its own members who are being investigated for trying to overturn an election. Give me an equivalent of Democrats doing this.

None of this is a whatboutism. This is the subject of the conversation and you can't engage with it because you know you don't have an argument.", "tim": 1659144970905787, "time": 1659144970, "resto": 1077597}, {"no": 1077713, "now": "07/30/22(Sat)01:37:23", "name": "Anonymous", "capcode": "none", "com": ">>1077709
NTA but they keep calling it that because it's been proven to be Russian-made fake news. Now why do you think the Russians hate the democrat party so much to do that?", "tim": 1659145043014562, "time": 1659145043, "resto": 1077597}, {"no": 1077714, "now": "07/30/22(Sat)01:37:53", "name": "Anonymous", "capcode": "none", "com": ">>1077710
>I have plenty over 6 months.
Then list a few

>Sadly, it's somewhat uncommon people get arrested, charged, and convicted In crimes within 6 months so I may have trouble meeting your artificially high bar you set waaaay up there
Give me a few convictions in the last six months then. Also, this is not an artificial bar. This is the bar that Republicans have set. Trump and the Republicans called the convictions of Manafort and Stone witch hunts by a corrupt Democrat government. Trump then pardoned both of them even after they'd been found guilty by a court of law. Give me a story of Democrats calling a conviction of one of their party members a witch hunt by a corrupt Republican government.", "tim": 1659145073050273, "time": 1659145073, "resto": 1077597}, {"no": 1077726, "now": "07/30/22(Sat)01:57:58", "name": "Anonymous", "capcode": "none", "com": ">>1077721
>This conversation is about how Republicans act versus how Democrats act.
No, this conversation is about yet another Democrat party chairman being corrupt, accepting bribes, and diddling children and your only defense is "whatabout trump", who is an idiot and an asshole, but hasn't been arrested yet for any of these things, much less convicted", "tim": 1659146278757547, "time": 1659146278, "resto": 1077597}, {"no": 1077733, "now": "07/30/22(Sat)02:13:49", "name": "Anonymous", "capcode": "none", "com": ">>1077726
>No, this conversation is about yet another Democrat party chairman being corrupt, accepting bribes, and diddling children
So I can tell we've reached the point in the conversation where you realize you don't have an argument so you're not going to engage with any of my points.

>your only defense is "whatabout trump", who is an idiot and an asshole, but hasn't been arrested yet for any of these things, much less convicted
You've actually struck right to the heart of my argument. If Trump is an idiot and an asshole than what does that say about the Republican party who covered for him, enabled him and stood idly by while he pardoned several prominent Republican politicians and personal friends who had been convicted of crimes? This conversation is highlighting the difference between Democrats, who pretty routinely abandon their own once they get caught by the law and Republicans who have spent the past 6 years systematically defending and covering for every single corrupt member of their party. Trump set the precedent and Republicans supported it. I don't want to hear a defense of Trump. I want to hear a defense of those Republicans. Again, I realize you don't have an argument so I accept whatever shitpost you make next that completely ignores all of the points I made as your concession.", "tim": 1659147229687356, "time": 1659147229, "resto": 1077597}]}, {"board": "news", "thread": "t1077143", "posts": [{"no": 1077143, "now": "07/27/22(Wed)14:07:24", "name": "Anonymous", "sub": "In Reality, All The Actual Groomers Are Republicans", "capcode": "none", "com": "https://www.businessinsider.com/matt-gaetz-20-gop-voting-against-anti-sex-trafficking-bill-2022-7

The Frederick Douglass Trafficking Victims Prevention and Protection Reauthorization Act of 2022 was approved in the House for reauthorization with a massive majority of 401 votes to 20.

The act combats human trafficking — particularly sex trafficking — through severe penalties for perpetrators and support services for victims.

It first came into law as the Victims of Trafficking and Violence Protection Act of 2000, when it passed the House and Senate with almost no opposition, and has been reauthorized multiple times without significant challenge.

Gaetz has been under federal investigation since 2020 over the question of whether he had sex with a minor, and whether he paid for her to cross state lines, as The New York Times first reported. Paying for a minor to travel interstate for sex would count as sex-trafficking.

Gaetz has not been charged with anything and has consistently denied any wrongdoing.

A former associate, Joel Greenberg — whom Gaetz once called his "wingman"— has pleaded guilty to six charges, including sex trafficking a minor, Politico reported. Greenberg's sentencing has been delayed in order to cooperate with the investigation into Gaetz, per the outlet.

Gaetz did not immediately respond to Insider's query about the vote, made outside normal US working hours, about why he voted no.

In comments to Insider on Wednesday in response to a quip by a Mike Pence aide about the matter, a Gaetz spokesperson described the idea that he had engaged in sex-trafficking as a "debunked conspiracy theory."

Gaetz did not speak in a 40-minute debate on the day of the vote.", "filename": "ezgif-5-33b507731c", "ext": ".jpg", "w": 1180, "h": 842, "tn_w": 250, "tn_h": 178, "tim": 1658930844332982, "time": 1658930844, "md5": "7rojjwmsbrsoHOTlafdK/g==", "fsize": 169819}, {"no": 1077689, "now": "07/30/22(Sat)00:11:54", "name": "Anonymous", "capcode": "none", "com": ">>1077687
>That is the important part, they kept it to themselves. Now they are advocating for letting drag queens have access to children for storytime and some even want to push for pedophiles (MAPS, Minor Attracted Persons) as a protected legitimate sexual orientation. This is not okay.
I think this is the root of the issue - you're clearly worrying about things that aren't real. Firstly, nobody is "pushing" for drag queens to have "access" to children. Drag queens tell stories to children at public libraries and if you don't want to take your child then don't. Secondly, there's not a single Democrat politician who has pushed for pedophiles to be a protected sexual orientation. You're describing a position that nobody outside of a handful of schizophrenic people on Twitter hold. I think you use these made up examples to post hoc justify your disgust with gay people. The examples you're using of reasons you hate gay people isn't representative of 99.9% of gay people.

>I'm saying that the minority needs to learn to assimilate into society instead of being so vocal, ridiculous and demanding that society changes to adapt to them and their needs.
And I'm saying that if society followed your logic we'd still be in the dark ages. Several centuries ago it was only a small minority of people who thought that slavery was a bad thing. If we all followed your worldview then we'd still be shitting in the streets because only a small minority of scientists back then believed that germs existed. Your way of life is untennable.

>I'm open to free thought but I'm not open to being told to shut up just because I upset some random faggot.
Nobody's telling you to shut up. What people are telling you is that you don't have the right to solely dictate what does and doesn't get assimilated into society. The only reason you're here right now is because, at some point, a minority of people pushed their views to the point that it became accepted into larger society.", "tim": 1659139914457418, "time": 1659139914, "resto": 1077143}, {"no": 1077692, "now": "07/30/22(Sat)00:42:05", "name": "Anonymous", "capcode": "none", "com": ">>1077689
>>1077689
> nobody is "pushing" for drag queens to have "access" to children
Then how did these people even get there in the first place? There are people that want drag queens to be doing this. It's either the drag queens themselves or someone contacting them.
>Secondly, there's not a single Democrat politician who has pushed for pedophiles to be a protected sexual orientation.
So Senator Scott Weiner from California introducing SB-145 which will make it less likely for grown men to be put on predator lists for having sex with a minor isn't a push for pedophilia?
> If we all followed your worldview then we'd still be shitting in the streets because only a small minority of scientists back then believed that germs existed
And those scientists proved that germs are real and everyone realized they were silly for ostracizing them. With gays, we all know that they're comprised of a lot of degenerates in that community. How are you going to look at something like this and say "Yes, these people are well adjusted members of society, this should be allowed in all aspects of our lives: https://twitter.com/libsoftiktok/status/1553149757085716480
>What people are telling you is that you don't have the right to solely dictate what does and doesn't get assimilated into society.
I never said that solely I get to decide, what I'm saying is that a small very vocal group of gays shouldn't be trying to revamp society as a whole to accommodate for fetishists and degenerates. There are times when society should get revamped and go through revolution because it actually is the better thing to do. Look at modern day China. They're on the brink of collapse and I support it because the CCP is beyond corrupt. It was also a good thing that slavery got revamped because it is a terrible thing to do to people. But revamping society so gays can parade around dancing in the streets naked in full view of children is just detestable and beyond retarded.", "tim": 1659141725182931, "time": 1659141725, "resto": 1077143}]}]} 2 | -------------------------------------------------------------------------------- /tests/json/search_results_unparsable_whole.json: -------------------------------------------------------------------------------- 1 | {"query": "democrat", "board": "news", "nhits": 0, "offset": "0", "threads": {"some arbitrary dictionary": "instead of an array, which is what it is expected"}} 2 | -------------------------------------------------------------------------------- /tests/test_api.py: -------------------------------------------------------------------------------- 1 | import os 2 | from datetime import timezone, datetime 3 | from typing import Callable 4 | from urllib import parse 5 | 6 | import pytest 7 | import responses 8 | from requests import HTTPError 9 | 10 | from pychan import FourChan, LogLevel, PychanLogger 11 | from pychan.api import _safe_id_parse, ParsingError 12 | from pychan.models import Thread, Post, File, Poster 13 | 14 | 15 | @pytest.fixture 16 | def fourchan() -> FourChan: 17 | fourchan = FourChan( 18 | logger=PychanLogger(LogLevel.DEBUG), 19 | raise_http_exceptions=True, 20 | raise_parsing_exceptions=True 21 | ) 22 | fourchan._throttle_request = lambda: None 23 | return fourchan 24 | 25 | 26 | @pytest.fixture 27 | def fourchan_no_raises() -> FourChan: 28 | fourchan = FourChan( 29 | logger=PychanLogger(LogLevel.DEBUG), 30 | raise_http_exceptions=False, 31 | raise_parsing_exceptions=False 32 | ) 33 | fourchan._throttle_request = lambda: None 34 | return fourchan 35 | 36 | 37 | def test_safe_id_parse() -> None: 38 | assert _safe_id_parse(None, offset=1) is None 39 | assert _safe_id_parse("", offset=1) is None 40 | assert _safe_id_parse("t", offset=1) is None 41 | assert _safe_id_parse("test", offset=1) is None 42 | assert _safe_id_parse("t1", offset=1) == 1 43 | 44 | 45 | def test_parse_error(fourchan: FourChan) -> None: 46 | with pytest.raises(ParsingError): 47 | fourchan._parse_error("test") 48 | 49 | 50 | def test_parse_catalog_json_from_javascript(fourchan: FourChan) -> None: 51 | # yapf: disable 52 | tests = { 53 | 'var catalog = {"test": "test"};': {"test": "test"}, 54 | 'var catalog = {"t1": "t1"};var x = {"t2": "t2"};': {"t1": "t1"}, 55 | 'var x = {"t2": "t2"};var catalog = {"t1": "t1"};': {"t1": "t1"}, 56 | 'var catalog = {"te};st": "te};st"};': {"te};st": "te};st"} 57 | } 58 | # yapf: enable 59 | for input, expected_json in tests.items(): 60 | assert fourchan._parse_catalog_json_from_javascript(input) == expected_json 61 | 62 | 63 | @responses.activate 64 | def test_get_boards(fourchan: FourChan) -> None: 65 | with open(f"{os.path.dirname(__file__)}/html/pol_catalog.html", "r", encoding="utf-8") as file: 66 | test_data = file.read() 67 | 68 | responses.add(responses.GET, "https://boards.4chan.org/pol/catalog", status=200, body=test_data) 69 | boards = fourchan.get_boards() 70 | 71 | assert "tv" in boards 72 | assert "b" in boards 73 | assert len(boards) > 20 74 | assert "f" not in boards # Random blacklisted board 75 | 76 | 77 | @responses.activate 78 | def test_get_threads(fourchan: FourChan) -> None: 79 | board = "pol" 80 | 81 | with open(f"{os.path.dirname(__file__)}/html/pol_catalog.html", "r", encoding="utf-8") as file: 82 | test_data = file.read() 83 | 84 | responses.add( 85 | responses.GET, f"https://boards.4chan.org/{board}/catalog", status=200, body=test_data 86 | ) 87 | 88 | expected = [ 89 | Thread( 90 | board, 91 | 124205675, 92 | title="Welcome to /pol/ - Politically Incorrect", 93 | is_stickied=True, 94 | is_closed=True 95 | ), 96 | Thread(board, 259848258, is_stickied=True, is_closed=True), 97 | Thread(board, 422352356, title="Who is “The Market”?"), 98 | Thread(board, 422343879, title="ITS OVER"), 99 | Thread(board, 422321472, title="jewess steals 175 million from chase bank through fraud"), 100 | ] 101 | actual = fourchan.get_threads(board) 102 | assert len(actual) == 202 103 | for i, thread in enumerate(expected): 104 | assert tuple(thread) == tuple(actual[i]) 105 | 106 | 107 | def test_get_thread_unparsable_board(fourchan: FourChan) -> None: 108 | assert len(list(fourchan.get_threads("f"))) == 0 109 | 110 | 111 | def test_get_threads_http_errors(fourchan: FourChan, fourchan_no_raises: FourChan) -> None: 112 | board = "pol" 113 | 114 | @responses.activate 115 | def with_mocks(status: int, function: Callable[[], None]) -> None: 116 | # The method should only attempt to fetch the first page, because the generator should 117 | # terminate once it reaches a page that was not retrievable 118 | responses.add(responses.GET, f"https://boards.4chan.org/{board}/catalog", status=status) 119 | function() 120 | 121 | def helper_without_raises() -> None: 122 | actual = list(fourchan_no_raises.get_threads(board)) 123 | assert len(actual) == 0 124 | responses.assert_call_count(f"https://boards.4chan.org/{board}/catalog", count=1) 125 | 126 | def helper() -> None: 127 | with pytest.raises(HTTPError): 128 | fourchan.get_threads(board) 129 | 130 | with_mocks(403, helper_without_raises) 131 | with_mocks(404, helper_without_raises) 132 | with_mocks(500, helper_without_raises) 133 | with_mocks(403, helper) 134 | with_mocks(404, helper) 135 | with_mocks(500, helper) 136 | 137 | 138 | @responses.activate 139 | def test_get_archived_threads(fourchan: FourChan) -> None: 140 | board = "pol" 141 | 142 | with open(f"{os.path.dirname(__file__)}/html/pol_archive.html", "r", encoding="utf-8") as file: 143 | test_data = file.read() 144 | 145 | responses.add( 146 | responses.GET, f"https://boards.4chan.org/{board}/archive", status=200, body=test_data 147 | ) 148 | 149 | threads = fourchan.get_archived_threads(board) 150 | assert len(threads) == 3000 151 | for thread in threads: 152 | assert thread.title is not None 153 | assert thread.is_archived 154 | 155 | 156 | def test_get_archived_threads_http_errors(fourchan: FourChan, fourchan_no_raises: FourChan) -> None: 157 | board = "pol" 158 | url = f"https://boards.4chan.org/{board}/archive" 159 | 160 | @responses.activate 161 | def with_mocks(status: int, function: Callable[[], None]) -> None: 162 | # The method should only attempt to fetch the first page, because the generator should 163 | # terminate once it reaches a page that was not retrievable 164 | responses.add(responses.GET, url, status=status) 165 | function() 166 | 167 | def helper_no_raises() -> None: 168 | actual = list(fourchan_no_raises.get_archived_threads(board)) 169 | assert len(actual) == 0 170 | responses.assert_call_count(url, count=1) 171 | 172 | def helper() -> None: 173 | with pytest.raises(HTTPError): 174 | fourchan.get_archived_threads(board) 175 | 176 | with_mocks(403, helper_no_raises) 177 | with_mocks(404, helper_no_raises) 178 | with_mocks(500, helper_no_raises) 179 | with_mocks(403, helper) 180 | with_mocks(404, helper) 181 | with_mocks(500, helper) 182 | 183 | 184 | @responses.activate 185 | def test_get_posts(fourchan: FourChan) -> None: 186 | with open(f"{os.path.dirname(__file__)}/html/pol_thread_posts.html", "r", 187 | encoding="utf-8") as file: 188 | test_data = file.read() 189 | 190 | # The two thread objects below should be representations of the same thread where the first is 191 | # the user-specified version of the thread and the latter is the one that pychan automatically 192 | # assembles based on 4chan remote data 193 | thread = Thread("/Pol ", 388462123) 194 | processed_thread = Thread("pol", 388462123, title="No.1 Hitler movie in Germany?") 195 | 196 | responses.add( 197 | responses.GET, 198 | f"https://boards.4chan.org/{processed_thread.board}/thread/{processed_thread.number}/", 199 | status=200, 200 | body=test_data 201 | ) 202 | 203 | reply1 = Post( 204 | processed_thread, 205 | 388462302, 206 | datetime.fromtimestamp(1658892803, timezone.utc), 207 | Poster("Anonymous", id="yzu2QJHE", flag="United States"), 208 | ">>388462123\n>>388462123\n>>388462123\nwhat movie?" 209 | ) 210 | reply2 = Post( 211 | processed_thread, 212 | 388462314, 213 | datetime.fromtimestamp(1658892808, timezone.utc), 214 | Poster("Anonymous", id="xF49FJaT", flag="United States"), 215 | ">>388462123\nFunny movie but there was agenda with this film" 216 | ) 217 | 218 | expected = [ 219 | Post( 220 | processed_thread, 221 | 388462123, 222 | datetime.fromtimestamp(1658892700, timezone.utc), 223 | Poster("Anonymous", id="BYagKQXI", flag="United States"), 224 | "Apparently this movie smashed German box office records, and all the dialogue is ..NOT.. scripted.", 225 | is_original_post=True, 226 | file=File( 227 | "https://i.4cdn.org/pol/1658892700380132.jpg", 228 | "hitler miss kromier.jpg", 229 | "106 KB", (800, 600), 230 | is_spoiler=False 231 | ), 232 | replies=[reply1, reply2] 233 | ), 234 | reply1, 235 | reply2, 236 | Post( 237 | processed_thread, 238 | 388462450, 239 | datetime.fromtimestamp(1658892887, timezone.utc), 240 | Poster("Anonymous", id="e8uCKNk1", flag="Canada"), 241 | ">>389829992 →\nLook who's back." 242 | ) 243 | ] 244 | actual = fourchan.get_posts(thread) 245 | assert len(expected) == len(actual) 246 | for i, post in enumerate(expected): 247 | assert tuple(post) == tuple(actual[i]) 248 | 249 | 250 | @responses.activate 251 | def test_get_post_from_moderator(fourchan: FourChan) -> None: 252 | with open(f"{os.path.dirname(__file__)}/html/pol_moderator_post.html", "r", 253 | encoding="utf-8") as file: 254 | test_data = file.read() 255 | 256 | responses.add( 257 | responses.GET, 258 | f"https://boards.4chan.org/pol/thread/259848258/", 259 | status=200, 260 | body=test_data 261 | ) 262 | 263 | actual = fourchan.get_posts(Thread("pol", 259848258)) 264 | assert len(actual) == 1 265 | assert actual[0].poster.name == "Anonymous" 266 | assert actual[0].poster.is_moderator 267 | 268 | 269 | def test_get_posts_unparsable_board(fourchan: FourChan) -> None: 270 | thread = Thread("f", 0) 271 | assert len(fourchan.get_posts(thread)) == 0 272 | 273 | 274 | def test_get_posts_http_errors(fourchan: FourChan, fourchan_no_raises: FourChan) -> None: 275 | thread = Thread("pol", 388462123, title="No.1 Hitler movie in Germany?") 276 | 277 | @responses.activate 278 | def with_mocks(status: int, function: Callable[[], None]) -> None: 279 | responses.add( 280 | responses.GET, 281 | f"https://boards.4chan.org/{thread.board}/thread/{thread.number}/", 282 | status=status, 283 | ) 284 | function() 285 | 286 | def helper_no_raises() -> None: 287 | actual = list(fourchan_no_raises.get_posts(thread)) 288 | assert len(actual) == 0 289 | 290 | def helper() -> None: 291 | with pytest.raises(HTTPError): 292 | fourchan.get_posts(thread) 293 | 294 | with_mocks(403, helper_no_raises) 295 | with_mocks(404, helper_no_raises) 296 | with_mocks(500, helper_no_raises) 297 | with_mocks(403, helper) 298 | with_mocks(404, helper) 299 | with_mocks(500, helper) 300 | 301 | 302 | def test_search(fourchan_no_raises: FourChan) -> None: 303 | board = "news" 304 | search_text = "democrat" 305 | 306 | @responses.activate 307 | def helper(file_name: str, *, expected_threads: list[Thread]) -> None: 308 | with open(f"{os.path.dirname(__file__)}/json/{file_name}", "r", encoding="utf-8") as file: 309 | test_data = file.read() 310 | 311 | responses.add( 312 | responses.GET, 313 | f"https://find.4chan.org/api?q={parse.quote(search_text)}&b={board}&o=0", 314 | status=200, 315 | body=test_data 316 | ) 317 | responses.add( 318 | # This response terminates the iteration within the generator (the generator halts when 319 | # it encounters a "page" of results which have all already been seen, so we simply mock 320 | # the results on the second "page" as being identical to the results on the first "page" 321 | # above) 322 | responses.GET, 323 | f"https://find.4chan.org/api?q={parse.quote(search_text)}&b={board}&o=10", 324 | status=200, 325 | body=test_data 326 | ) 327 | 328 | actual = list( 329 | fourchan_no_raises.search( 330 | board=board, text=search_text, user_agent="test", cloudflare_cookies={} 331 | ) 332 | ) 333 | assert len(expected_threads) == len(actual) 334 | for i, thread in enumerate(expected_threads): 335 | assert tuple(thread) == tuple(actual[i]) 336 | 337 | helper( 338 | "search_results.json", 339 | expected_threads=[ 340 | Thread(board, 1077597, title="Democrat corruption and grooming."), 341 | Thread(board, 1077143, title="In Reality, All The Actual Groomers Are Republicans") 342 | ] 343 | ) 344 | helper( 345 | "search_results_unparsable_partial.json", 346 | expected_threads=[ 347 | Thread(board, 1077143, title="In Reality, All The Actual Groomers Are Republicans") 348 | ] 349 | ) 350 | helper("search_results_unparsable_whole.json", expected_threads=[]) 351 | 352 | 353 | def test_search_unparsable_board(fourchan: FourChan) -> None: 354 | assert len(list(fourchan.get_threads("f"))) == 0 355 | 356 | 357 | def test_search_http_errors(fourchan: FourChan, fourchan_no_raises: FourChan) -> None: 358 | board = "news" 359 | search_text = "democrat" 360 | 361 | @responses.activate 362 | def with_mocks(status: int, function: Callable[[], None]) -> None: 363 | responses.add( 364 | responses.GET, 365 | f"https://find.4chan.org/api?q={parse.quote(search_text)}&b={board}&o=0", 366 | status=status, 367 | ) 368 | function() 369 | 370 | def helper_no_raises() -> None: 371 | actual = list( 372 | fourchan_no_raises.search( 373 | board=board, text=search_text, user_agent="test", cloudflare_cookies={} 374 | ) 375 | ) 376 | assert len(actual) == 0 377 | 378 | def helper() -> None: 379 | with pytest.raises(HTTPError): 380 | # The call to list() below forces the generator to execute; without it, the actual HTTP 381 | # call never happens 382 | list( 383 | fourchan.search( 384 | board=board, text=search_text, user_agent="test", cloudflare_cookies={} 385 | ) 386 | ) 387 | 388 | with_mocks(403, helper_no_raises) 389 | with_mocks(404, helper_no_raises) 390 | with_mocks(500, helper_no_raises) 391 | with_mocks(403, helper) 392 | with_mocks(404, helper) 393 | with_mocks(500, helper) 394 | -------------------------------------------------------------------------------- /tests/test_api_no_mocks.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | import pytest 4 | 5 | from pychan import FourChan 6 | 7 | 8 | @pytest.fixture 9 | def fourchan() -> FourChan: 10 | # Below, we specify raise_*_exceptions=True because we want to raise all exceptions so that our 11 | # tests fail if anything does not work properly 12 | return FourChan(raise_http_exceptions=True, raise_parsing_exceptions=True) 13 | 14 | 15 | def test_get_boards_no_mocks(fourchan: FourChan) -> None: 16 | boards = fourchan.get_boards() 17 | assert len(boards) > 10 18 | 19 | 20 | def test_get_threads_and_get_posts_no_mocks(fourchan: FourChan) -> None: 21 | # Test fetching threads 22 | threads = fourchan.get_threads("/a") 23 | assert len(threads) > 100 24 | 25 | for thread in threads: 26 | assert thread.number > 0 27 | assert thread.board == "a" 28 | assert not thread.is_archived 29 | if thread.title is not None: 30 | assert len(thread.title) > 0 # Titles should be None instead of "" when empty 31 | 32 | # Test fetching posts using one of the threads from above 33 | posts = fourchan.get_posts(threads[0]) 34 | assert posts[0].is_original_post # There will always be at least 1 post (the original post) 35 | assert posts[0].file is not None # Original posts must always include a file 36 | (file_x, file_y) = posts[0].file.dimensions 37 | assert file_x > 0 38 | assert file_y > 0 39 | for post in posts: 40 | assert post.number > 0 41 | assert post.thread == threads[0] 42 | assert len(post.text) > 0 43 | 44 | 45 | def test_get_archived_threads_no_mocks(fourchan: FourChan) -> None: 46 | threads = fourchan.get_archived_threads("/a/") 47 | assert len(threads) > 100 48 | for thread in threads: 49 | assert thread.number > 0 50 | assert thread.board == "a" 51 | assert thread.is_archived 52 | if thread.title is not None: 53 | assert len(thread.title) > 0 # Titles should be None instead of "" when empty 54 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from datetime import datetime, timezone 3 | 4 | from pychan.models import Thread, Post, File, Poster 5 | 6 | _TIMESTAMP = datetime.fromtimestamp(0, timezone.utc) 7 | 8 | 9 | def test_thread_equality() -> None: 10 | t1 = Thread("b", 1337) 11 | t2 = Thread("b", 1338) 12 | t3 = Thread("int", 1337) 13 | assert t1 == t1 14 | assert t1 != t2 15 | assert t1 != t3 16 | 17 | # Test comparisons with non-Thread data types 18 | poster = Poster("test") 19 | post = Post(t1, 1337, _TIMESTAMP, poster, "test") 20 | file = File("test", "test", "1337 KB", (1920, 1080), is_spoiler=False) 21 | assert t1 != post 22 | assert t1 != file 23 | assert t1 != poster 24 | 25 | 26 | def test_post_equality() -> None: 27 | t1 = Thread("b", 1337) 28 | t2 = Thread("b", 1338) 29 | poster = Poster("test") 30 | p1 = Post(t1, 1337, _TIMESTAMP, poster, "test") 31 | p2 = Post(t1, 1338, _TIMESTAMP, poster, "test") 32 | p3 = Post(t2, 1337, _TIMESTAMP, poster, "test") 33 | assert p1 == p1 34 | assert p1 != p2 35 | assert p1 != p3 36 | 37 | # Test comparisons with non-Post data types 38 | file = File("test", "test", "1337 KB", (1920, 1080), is_spoiler=False) 39 | assert p1 != t1 40 | assert p1 != file 41 | assert p1 != poster 42 | 43 | 44 | def test_file_equality() -> None: 45 | f1 = File("test", "test", "1337 KB", (1920, 1080), is_spoiler=False) 46 | f2 = File("test", "test2", "1337 KB", (1920, 1080), is_spoiler=False) 47 | f3 = File("test2", "test", "1337 KB", (1920, 1080), is_spoiler=False) 48 | f4 = File("test2", "test", "1337 KB", (1920, 1080), is_spoiler=True) 49 | assert f1 == f1 50 | assert f1 == f2 51 | assert f1 != f3 52 | assert f3 == f4 53 | 54 | # Test comparisons with non-File data types 55 | thread = Thread("b", 1337) 56 | poster = Poster("test") 57 | post = Post(thread, 1337, _TIMESTAMP, poster, "test") 58 | assert f1 != thread 59 | assert f1 != post 60 | assert f1 != poster 61 | 62 | 63 | def test_poster_equality() -> None: 64 | p1 = Poster("test") 65 | p2 = Poster("test", flag="test2") 66 | p3 = Poster("test", id="test2") 67 | p4 = Poster("test2") 68 | assert p1 == p1 69 | assert p1 == p2 70 | assert p1 != p3 71 | assert p1 != p4 72 | 73 | # Test comparisons with non-Poster data types 74 | thread = Thread("b", 1337) 75 | post = Post(thread, 1337, _TIMESTAMP, p1, "test") 76 | file = File("test", "test", "1337 KB", (1920, 1080), is_spoiler=False) 77 | assert p1 != thread 78 | assert p1 != post 79 | assert p1 != file 80 | 81 | 82 | def test_poster_properties() -> None: 83 | poster = Poster("test", mod_indicator=False) 84 | assert poster.is_moderator 85 | 86 | poster = Poster("Anonymous", mod_indicator=False) 87 | assert not poster.is_moderator 88 | 89 | poster = Poster("Anonymous", mod_indicator=True) 90 | assert poster.is_moderator 91 | 92 | 93 | def test_serialization() -> None: 94 | file = File("test", "test", "1337 KB", (1920, 1080), is_spoiler=False) 95 | assert tuple(file) == ("test", "test", "1337 KB", (1920, 1080), False) 96 | 97 | poster = Poster("test") 98 | assert tuple(poster) == ("test", False, None, None) 99 | 100 | for text in [None, "test"]: 101 | thread = Thread("b", 1337, title=text) 102 | assert tuple(thread) == ("b", 1337, text, False, False, False) 103 | 104 | post = Post(thread, 1337, _TIMESTAMP, poster, "test") 105 | # yapf: disable 106 | assert tuple(post) == tuple(thread) + ( 107 | 1337, _TIMESTAMP, 108 | poster.name, 109 | poster._mod_indicator, 110 | poster.id, 111 | poster.flag, 112 | "test", 113 | False, 114 | None, 115 | None, 116 | None, 117 | None, 118 | 0 119 | ) 120 | # yapf: enable 121 | 122 | post = Post(thread, 1337, _TIMESTAMP, poster, "test", file=file) 123 | assert tuple(post) == tuple(thread) + ( 124 | 1337, 125 | _TIMESTAMP, 126 | poster.name, 127 | poster._mod_indicator, 128 | poster.id, 129 | poster.flag, 130 | "test", 131 | False, 132 | file.url, 133 | file.name, 134 | file.size, 135 | file.dimensions, 136 | 0 137 | ) 138 | 139 | 140 | def test_copying() -> None: 141 | thread = Thread("b", 1337, title="test") 142 | thread_copy = copy.copy(thread) 143 | thread_deepcopy = copy.deepcopy(thread) 144 | assert thread == thread_copy == thread_deepcopy 145 | assert thread is not thread_copy 146 | assert thread is not thread_deepcopy 147 | 148 | file = File("test", "test", "1337 KB", (1920, 1080), is_spoiler=False) 149 | file_copy = copy.copy(file) 150 | file_deepcopy = copy.deepcopy(file) 151 | assert file == file_copy == file_deepcopy 152 | assert file is not file_copy 153 | assert file is not file_deepcopy 154 | 155 | poster = Poster("test") 156 | poster_copy = copy.copy(poster) 157 | poster_deepcopy = copy.deepcopy(poster) 158 | assert poster == poster_copy == poster_deepcopy 159 | assert poster is not poster_copy 160 | assert poster is not poster_deepcopy 161 | 162 | post = Post(thread, 1337, _TIMESTAMP, poster, "test", file=file) 163 | post_copy = copy.copy(post) 164 | post_deepcopy = copy.deepcopy(post) 165 | assert post == post_copy == post_deepcopy 166 | assert post is not post_copy 167 | assert post is not post_deepcopy 168 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py310,py311,py312 3 | isolated_build = True 4 | 5 | [testenv] 6 | deps = 7 | pytest 8 | pytest-cov 9 | pytest-mock 10 | responses 11 | commands = 12 | pytest --cov --cov-report xml -p no:warnings 13 | 14 | [gh-actions] 15 | python = 16 | 3.10: py310 17 | 3.11: py311 18 | 3.12: py312 19 | --------------------------------------------------------------------------------