diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..e54dfea
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,106 @@
+# inspired by
+# - https://github.com/alexkaratarakis/gitattributes/blob/master/Java.gitattributes
+# - https://github.com/alexkaratarakis/gitattributes/blob/master/Common.gitattributes
+
+# Handle line endings automatically for files detected as text
+# and leave all files detected as binary untouched.
+* text=auto
+
+#
+# The above will handle all files with names NOT matching patterns defined below
+#
+
+# Git files
+.gitattributes text eol=lf
+**/.gitattributes text eol=lf
+.gitignore text eol=lf
+**/.gitignore text eol=lf
+
+
+# Documents
+*.doc binary diff=astextplain
+*.docx binary diff=astextplain
+*.dot binary diff=astextplain
+*.pdf binary diff=astextplain
+*.ppt binary diff=astextplain
+*.pptx binary diff=astextplain
+*.rtf binary diff=astextplain
+*.vsd binary diff=astextplain
+*.vsdx binary diff=astextplain
+*.odt binary diff=odf
+*.ods binary diff=odf
+*.odp binary diff=odf
+*.adoc text
+*.csv text
+*.md text diff=markdown
+*.txt text
+
+
+# Config/Serialisation
+.editorconfig text
+**/.editorconfig text
+*.ini text
+*.properties text
+*.json text
+*.toml text
+*.xml text
+*.yaml text
+*.yml text
+
+
+# Scripts
+*.bat text eol=crlf
+*.cmd text eol=crlf
+*.ps1 text eol=crlf
+*.bash text eol=lf
+*.fish text eol=lf
+*.sh text eol=lf
+*.zsh text eol=lf
+*.lua text
+*.php text
+*.py text
+*.python text
+*.sql text
+
+
+# Archives
+*.7z binary
+*.gz binary
+*.tar binary
+*.tar.gz binary
+*.tgz binary
+*.xz binary
+*.zip binary
+
+
+# Native binaries
+*.dll binary
+*.dylib binary
+*.exe binary
+*.so binary
+
+
+# Images
+*.eps binary
+*.gif binary
+*.ico binary
+*.jpg binary
+*.jpeg binary
+*.png binary
+*.svg text
+*.svgz binary
+*.tif binary
+*.tiff binary
+
+
+# Web
+*.css text diff=css
+*.htm text diff=html
+*.html text diff=html
+*.js text
+
+
+# https://git-scm.com/docs/gitattributes#_export_ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.gitkeep export-ignore
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..360fa80
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,20 @@
+# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
+version: 2
+updates:
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ day: monday
+ time: "17:00"
+ commit-message:
+ prefix: fix
+ prefix-development: chore
+ include: scope
+ labels:
+ - dependencies
+ - package-ecosystem: pip
+ directory: /
+ schedule:
+ interval: weekly
+ time: "17:00"
diff --git a/.github/stale.yml b/.github/stale.yml
new file mode 100644
index 0000000..e7df9f1
--- /dev/null
+++ b/.github/stale.yml
@@ -0,0 +1,24 @@
+# Configuration for probot-stale - https://github.com/probot/stale
+
+# Number of days of inactivity before an issue becomes stale
+daysUntilStale: 60
+
+# Number of days of inactivity before a stale issue is closed
+daysUntilClose: 7
+
+# Issues with these labels will never be considered stale
+exemptLabels:
+ - pinned
+ - security
+
+# Label to use when marking an issue as stale
+staleLabel: wontfix
+
+# Comment to post when marking an issue as stale. Set to `false` to disable
+markComment: >
+ This issue has been automatically marked as stale because it has not had
+ recent activity. It will be closed in 7 days if no further activity occurs.
+ Thank you for your contributions.
+
+# Comment to post when closing a stale issue. Set to `false` to disable
+closeComment: false
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..2638d91
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,130 @@
+# https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-syntax-for-github-actions
+name: Build
+
+on:
+ push:
+ branches:
+ - '**'
+ tags-ignore:
+ - '**'
+ paths-ignore:
+ - '**/*.md'
+ pull_request:
+ workflow_dispatch:
+ # https://github.blog/changelog/2020-07-06-github-actions-manual-triggers-with-workflow_dispatch/
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - macos-latest
+ - ubuntu-latest
+ - windows-latest
+ runs-on: ${{ matrix.os }}
+ steps:
+ - name: Git Checkout
+ uses: actions/checkout@v2 #https://github.com/actions/checkout
+
+ - uses: actions/setup-python@v2
+ with:
+ python-version: "3.10"
+
+ - name: Install python dependencies
+ run: |
+ set -eux
+
+ python --version
+
+ pip install .[dev]
+
+ - name: bandit
+ run: |
+ set -eux
+ bandit -c pyproject.toml --exclude '*/.eggs/*' -r .
+
+ - name: pylint
+ run: |
+ set -eux
+ pip install pylint
+ pylint kleinanzeigen_bot
+
+ - name: pytest
+ run: |
+ set -eux
+ python -m pytest
+
+ - name: run kleinanzeigen_bot
+ run: |
+ echo "
+ login:
+ username: 'john.doe@example.com'
+ password: 'such_a_secret'
+ " > config.yaml
+
+ set -eux
+
+ python -m kleinanzeigen_bot help
+ python -m kleinanzeigen_bot version
+ python -m kleinanzeigen_bot verify
+
+ - name: py2exe
+ if: startsWith(matrix.os, 'windows')
+ run: |
+ python setup.py py2exe
+ ls -l dist
+
+ - name: run kleinanzeigen_bot.exe
+ if: startsWith(matrix.os, 'windows')
+ run: |
+ set -eux
+
+ dist/kleinanzeigen-bot.exe help
+ dist/kleinanzeigen-bot.exe version
+ dist/kleinanzeigen-bot.exe verify
+
+ - name: "Delete previous 'latest' release"
+ if: startsWith(matrix.os, 'windows') && github.ref == 'refs/heads/main'
+ run: |
+ set -eu
+
+ api_base_url="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
+
+ # delete 'latest' github release
+ release_id=$(curl -fsL -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/repos/$GITHUB_REPOSITORY/releases | jq -r '.[] | select(.name == "latest") | .id')
+ if [[ -n $release_id ]]; then
+ echo "Deleting release [$api_base_url/releases/$release_id]..."
+ curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -fsSL -X DELETE "$api_base_url/releases/$release_id"
+ fi
+
+ # delete 'latest' git tag
+ tag_url="$api_base_url/git/refs/tags/latest"
+ if curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -fsLo /dev/null --head "$tag_url"; then
+ echo "Deleting tag [$tag_url]..."
+ curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -fsSL -X DELETE "$tag_url"
+ fi
+
+ - name: "Create 'latest' Release"
+ if: startsWith(matrix.os, 'windows') && github.ref == 'refs/heads/main'
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ set -eux
+
+ # https://hub.github.com/hub-release.1.html
+ hub release create "latest" \
+ --prerelease \
+ --message "latest" \
+ --attach "dist/kleinanzeigen-bot.exe#kleinanzeigen-bot.exe"
+
+ - name: "Delete intermediate build artifacts"
+ uses: geekyeggo/delete-artifact@1-glob-support # https://github.com/GeekyEggo/delete-artifact/
+ with:
+ name: "*"
+ useGlob: true
+ failOnError: false
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b064b98
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,37 @@
+# Local work folder that is not checked in
+_LOCAL/
+
+# kleinanzeigen_bot
+/config.yaml
+/data
+/*.log
+kleinanzeigen_bot/version.py
+
+# python
+__pycache__
+/build
+/dist
+/.eggs
+/*.egg-info
+
+# Eclipse
+/.project
+/.pydevproject
+/.settings/
+**/.*.md.html
+
+# IntelliJ
+/.idea
+/*.iml
+/*.ipr
+/*.iws
+
+# Visual Studio Code
+/.vscode
+
+# OSX
+.DS_Store
+
+# Vim
+*.swo
+*.swp
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..cd6fd97
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,15 @@
+# Contributing
+
+Thanks for your interest in contributing to this project!
+
+We want to make contributing as easy and transparent as possible.
+
+
+## Issues
+
+We use GitHub issues to track bugs and feature requests. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue.
+
+
+## License
+
+By contributing your code, you agree to license your contribution under the [GNU Affero General Public License v3.0 or later](LICENSE.txt).
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..0ad25db
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/README.md b/README.md
index 1655cb7..2ad9638 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,222 @@
# kleinanzeigen-bot
-A command line tool to publish ads on ebay-kleinanzeigen.de
+
+[](https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/actions?query=workflow%3A%22Build%22)
+[](LICENSE.txt)
+[](https://codeclimate.com/github/kleinanzeigen-bot/kleinanzeigen-bot/maintainability)
+
+**Feedback and high-quality pull requests are highly welcome!**
+
+1. [About](#about)
+1. [Installation](#installation)
+1. [Usage](#usage)
+1. [Development Notes](#development)
+1. [License](#license)
+
+## About
+
+**kleinanzeigen-bot** is a console based application to ease publishing of ads to ebay-kleinanzeigen.de.
+
+
+It is a spiritual successor to [AnzeigenOrg/ebayKleinanzeigen](https://github.com/AnzeigenOrg/ebayKleinanzeigen) with the following advantages:
+- supports Microsoft Edge browser (Chromium based)
+- compatible chromedriver is installed automatically
+- better captcha handling
+- config:
+ - use YAML or JSON for config files
+ - one config file per ad
+ - use globbing (wildcards) to select images from local disk
+ - reference categories by name (looked up from [categories.yaml](https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/blob/main/kleinanzeigen_bot/resources/categories.yaml))
+- logging is configurable and colorized
+- provided as self-contained Windows executable [kleinanzeigen-bot.exe](https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/releases/download/latest/kleinanzeigen-bot.exe)
+- source code is pylint checked and uses Python type hints
+- CI builds
+
+
+## Installation
+
+### Installation on Windows using self-containing exe
+
+1. The following components need to be installed:
+ 1. [Chromium](https://www.chromium.org/getting-involved/download-chromium), [Google Chrome](https://www.google.com/chrome/),
+ or Chromium based [Microsoft Edge](https://www.microsoft.com/edge) browser
+
+1. Open a command/terminal window
+1. Download the app using
+ ```
+ curl https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/releases/download/latest/kleinanzeigen-bot.exe -o kleinanzeigen-bot.exe
+ ```
+1. Run the app:
+ ```
+ kleinanzeigen-bot --help
+ ```
+
+### Installation from source
+
+1. The following components need to be installed:
+ 1. [Chromium](https://www.chromium.org/getting-involved/download-chromium), [Google Chrome](https://www.google.com/chrome/),
+ or Chromium based [Microsoft Edge](https://www.microsoft.com/edge) browser
+ 1. [Python](https://www.python.org/) **3.10** or newer
+ 1. [pip](https://pypi.org/project/pip/)
+ 1. [git client](https://git-scm.com/downloads)
+
+1. Open a command/terminal window
+1. Clone the repo using
+ ```
+ git clone https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/
+ ```
+1. Change into the directory:
+ ```
+ cd kleinanzeigen-bot
+ ```
+1. Install the Python dependencies using:
+ ```
+ pip install .
+ ```
+1. Run the app:
+ ```
+ python -m kleinanzeigen_bot --help
+ ```
+
+## Usage
+
+```yaml
+Usage: kleinanzeigen-bot COMMAND [-v|--verbose] [--config=] [--logfile=]
+
+Commands:
+ publish - (re-)publishes ads
+ verify - verifies the configuration files
+ --
+ help - displays this help (default command)
+ version - displays the application version
+```
+
+### Configuration
+
+All configuration files can be in YAML or JSON format.
+
+#### 1) Main configuration
+
+When executing the app it by default looks for a `config.yaml` file in the current directory. If it does not exist it will be created automatically.
+
+The configuration file to be used can also be specified using the `--config ` command line parameter. It must point to a YAML or JSON file.
+Valid file extensions are `.json`, `.yaml` and `.yml`
+
+The following parameters can be configured:
+
+```yaml
+# wild card patterns to select ad configuration files
+# if relative paths are specified, then they are relative to this configuration file
+ad_files:
+ - "my_ads/**/ad_*.json"
+ - "my_ads/**/ad_*.yml"
+ - "my_ads/**/ad_*.yaml"
+
+# default values for ads, can be overwritten in each ad configuration file
+ad_defaults:
+ active: true
+ type: # one of: OFFER, WANTED
+ description:
+ prefix:
+ suffix:
+ price_type: # one of: FIXED, NEGOTIABLE, GIVE_AWAY
+ shipping_type: # one of: PICKUP, SHIPPING, NOT_APPLICABLE
+ contact:
+ name:
+ street:
+ zipcode:
+ phone:
+ republication_interval: # every X days ads should be re-published
+
+# additional name to category ID mappings, see default list at
+# https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/blob/main/kleinanzeigen_bot/resources/categories.yaml
+categories:
+ #Notebooks: 161/27
+ #PCs: 161/228
+
+# browser configuration
+browser:
+ # https://peter.sh/experiments/chromium-command-line-switches/
+ arguments:
+ # https://stackoverflow.com/a/50725918/5116073
+ - --disable-dev-shm-usage
+ - --no-sandbox
+ # --headless
+ # --start-maximized
+ binary_location: # path to custom browser executable, if not specified will be looked up on PATH
+
+# login credentials
+login:
+ username:
+ password:
+
+```
+
+#### 2) Ad configuration
+
+Each ad is described in a separate JSON or YAML file.
+
+Parameter values specified in the `ad_defaults` section of the `config.yaml` file don't need to be specified again in the ad configuration file.
+
+The following parameters can be configured:
+
+```yaml
+active: # true or false
+type: # one of: OFFER, WANTED
+title:
+description: # can be multiline, see syntax here https://yaml-multiline.info/
+
+# built-in category name as specified in https://github.com/kleinanzeigen-bot/kleinanzeigen-bot/blob/main/kleinanzeigen_bot/resources/categories.yaml
+# or custom category name as specified in config.yaml
+# or category ID (e.g. 161/27)
+category: Notebooks
+
+price:
+price_type: # one of: FIXED, NEGOTIABLE, GIVE_AWAY
+
+shipping_type: # one of: PICKUP, SHIPPING, NOT_APPLICABLE
+
+# list of wildcard patterns to select images
+# if relative paths are specified, then they are relative to this ad configuration file
+images:
+ #- laptop_*.jpg
+ #- laptop_*.png
+
+contact:
+ name:
+ street:
+ zipcode:
+ phone:
+
+republication_interval: # every X days the ad should be re-published
+
+id: # set automatically
+created_on: # set automatically
+updated_on: # set automatically
+```
+
+## Development Notes
+
+- Installing dev dependencies: `pip install .[dev]`
+- Running unit tests: `python -m pytest` or `pytest`
+- Running linter: `python -m pylint kleinanzeigen_bot` or `pylint kleinanzeigen_bot`
+- Displaying effective version:`python setup.py --version`
+- Creating Windows executable: `python setup.py py2exe`
+- Application bootstrap works like this:
+ ```python
+ python -m kleinanzeigen_bot
+ |-> executes 'kleinanzeigen_bot/__main__.py'
+ |-> executes main() function of 'kleinanzeigen_bot/__init__.py'
+ |-> executes KleinanzeigenBot().run()
+ ````
+
+
+## License
+
+All files in this repository are released under the [GNU Affero General Public License v3.0 or later](LICENSE.txt).
+
+Individual files contain the following tag instead of the full license text:
+```
+SPDX-License-Identifier: AGPL-3.0-or-later
+```
+
+This enables machine processing of license information based on the SPDX License Identifiers that are available here: https://spdx.org/licenses/.
diff --git a/kleinanzeigen_bot/__init__.py b/kleinanzeigen_bot/__init__.py
new file mode 100644
index 0000000..b20aaed
--- /dev/null
+++ b/kleinanzeigen_bot/__init__.py
@@ -0,0 +1,471 @@
+"""
+Copyright (C) 2022 Sebastian Thomschke and contributors
+SPDX-License-Identifier: AGPL-3.0-or-later
+"""
+import atexit, copy, getopt, glob, json, logging, os, signal, sys, textwrap, time, urllib
+from datetime import datetime
+from logging.handlers import RotatingFileHandler
+from typing import Any, Dict, Final, Iterable
+
+from ruamel.yaml import YAML
+from selenium.common.exceptions import NoSuchElementException
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+
+from . import utils, resources
+from .utils import apply_defaults, ensure, is_frozen, pause, pluralize, safe_get
+from .selenium_mixin import SeleniumMixin
+
+LOG_ROOT:Final[logging.Logger] = logging.getLogger()
+LOG:Final[logging.Logger] = logging.getLogger("kleinanzeigen_bot")
+LOG.setLevel(logging.INFO)
+
+try:
+ from .version import version as VERSION
+except ModuleNotFoundError:
+ VERSION = "unknown"
+
+
+class KleinanzeigenBot(SeleniumMixin):
+
+ def __init__(self):
+ super().__init__()
+
+ self.root_url = "https://www.ebay-kleinanzeigen.de"
+
+ self.config:Dict[str, Any] = {}
+ self.config_file_path = os.path.join(os.getcwd(), "config.yaml")
+
+ self.categories:Dict[str, str] = {}
+
+ self.file_log:logging.FileHandler = None
+ if is_frozen():
+ log_file_basename = os.path.splitext(os.path.basename(sys.executable))[0]
+ else:
+ log_file_basename = self.__module__
+ self.log_file_path = os.path.join(os.getcwd(), f"{log_file_basename}.log")
+
+ self.command = "help"
+
+ def __del__(self):
+ if self.file_log:
+ LOG_ROOT.removeHandler(self.file_log)
+ super().__del__()
+
+ def run(self, args:Iterable[str]) -> None:
+ self.parse_args(args)
+ match self.command:
+ case "help":
+ self.show_help()
+ case "version":
+ print(VERSION)
+ case "verify":
+ self.configure_file_logging()
+ self.load_config()
+ self.load_ads()
+ LOG.info("############################################")
+ LOG.info("No configuration errors found.")
+ LOG.info("############################################")
+ case "publish":
+ self.configure_file_logging()
+ self.load_config()
+ ads = self.load_ads()
+ if len(ads) == 0:
+ LOG.info("############################################")
+ LOG.info("No ads to (re-)publish found.")
+ LOG.info("############################################")
+ else:
+ self.create_webdriver_session()
+ self.login()
+ self.publish_ads(ads)
+ case _:
+ LOG.error("Unknown command: %s", self.command)
+ sys.exit(2)
+
+ def show_help(self) -> None:
+ if is_frozen():
+ exe = sys.argv[0]
+ else:
+ exe = f"python -m {os.path.relpath(os.path.join(__file__, '..'))}"
+
+ print(textwrap.dedent(f"""\
+ Usage: {exe} COMMAND [-v|--verbose] [--config=] [--logfile=]
+
+ Commands:
+ publish - (re-)publishes ads
+ verify - verifies the configuration files
+ --
+ help - displays this help (default command)
+ version - displays the application version
+ """))
+
+ def parse_args(self, args:Iterable[str]) -> None:
+ try:
+ options, arguments = getopt.gnu_getopt(args[1:], "hv", ["help", "verbose", "logfile=", "config="]) # pylint: disable=unused-variable
+ except getopt.error as ex:
+ LOG.error(ex.msg)
+ LOG.error("Use --help to display available options")
+ sys.exit(2)
+
+ for option, value in options:
+ match option:
+ case "-h" | "--help":
+ self.show_help()
+ sys.exit(0)
+ case "--config":
+ self.config_file_path = os.path.abspath(value)
+ case "--logfile":
+ if value:
+ self.log_file_path = os.path.abspath(value)
+ else:
+ self.log_file_path = None
+ case "-v" | "--verbose":
+ LOG.setLevel(logging.DEBUG)
+
+ match len(arguments):
+ case 0:
+ self.command = "help"
+ case 1:
+ self.command = arguments[0]
+ case _:
+ LOG.error("More than one command given: %s", arguments)
+ sys.exit(2)
+
+ def configure_file_logging(self) -> None:
+ if not self.log_file_path:
+ return
+ if self.file_log:
+ return
+
+ LOG.info("Logging to [%s]...", self.log_file_path)
+ self.file_log = RotatingFileHandler(filename = self.log_file_path, maxBytes = 10 * 1024 * 1024, backupCount = 10, encoding = "utf-8")
+ self.file_log.setLevel(logging.DEBUG)
+ self.file_log.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
+ LOG_ROOT.addHandler(self.file_log)
+
+ def load_ads(self, exclude_inactive = True, exclude_undue = True) -> Iterable[Dict[str, Any]]:
+ LOG.info("Searching for ad files...")
+
+ ad_files = set()
+ for file_pattern in self.config["ad_files"]:
+ for ad_file in glob.glob(file_pattern, root_dir = os.getcwd(), recursive = True):
+ ad_files.add(os.path.abspath(ad_file))
+ LOG.info(" -> found %s", pluralize("ad file", ad_files))
+ if not ad_files:
+ return []
+
+ descr_prefix = self.config["ad_defaults"]["description"]["prefix"] or ""
+ descr_suffix = self.config["ad_defaults"]["description"]["suffix"] or ""
+
+ ad_fields = utils.load_dict_from_module(resources, "ad_fields.yaml")
+ ads = []
+ for ad_file in sorted(ad_files):
+
+ ad_cfg_orig = utils.load_dict(ad_file, "ad file")
+ ad_cfg = copy.deepcopy(ad_cfg_orig)
+ apply_defaults(ad_cfg, self.config["ad_defaults"], ignore = lambda k, _: k == "description", override = lambda _, v: v == "")
+ apply_defaults(ad_cfg, ad_fields)
+
+ if exclude_inactive and not ad_cfg["active"]:
+ LOG.info(" -> excluding inactive ad [%s]", ad_file)
+ continue
+
+ if exclude_undue:
+ if ad_cfg["updated_on"]:
+ last_updated_on = datetime.fromisoformat(ad_cfg["updated_on"])
+ elif ad_cfg["created_on"]:
+ last_updated_on = datetime.fromisoformat(ad_cfg["created_on"])
+
+ if last_updated_on:
+ ad_age = datetime.utcnow() - last_updated_on
+ if ad_age.days <= ad_cfg["republication_interval"]:
+ LOG.info(" -> skipping. last published %d days ago. republication is only required every %s days",
+ ad_age.days,
+ ad_cfg["republication_interval"]
+ )
+ continue
+
+ ad_cfg["description"] = descr_prefix + (ad_cfg["description"] or "") + descr_suffix
+
+ # pylint: disable=cell-var-from-loop
+ def assert_one_of(path:str, allowed:Iterable):
+ ensure(safe_get(ad_cfg, *path.split(".")) in allowed, f'-> property [{path}] must be one of: {allowed} @ [{ad_file}]')
+
+ def assert_min_len(path:str, minlen:int):
+ ensure(len(safe_get(ad_cfg, *path.split("."))) >= minlen, f'-> property [{path}] must be at least {minlen} characters long @ [{ad_file}]')
+
+ def assert_has_value(path:str):
+ ensure(safe_get(ad_cfg, *path.split(".")), f'-> property [{path}] not specified @ [{ad_file}]')
+ # pylint: enable=cell-var-from-loop
+
+ assert_one_of("type", ("OFFER", "WANTED"))
+ assert_min_len("title", 10)
+ assert_has_value("description")
+ assert_has_value("price")
+ assert_one_of("price_type", ("FIXED", "NEGOTIABLE", "GIVE_AWAY"))
+ assert_one_of("shipping_type", ("PICKUP", "SHIPPING", "NOT_APPLICABLE"))
+ assert_has_value("contact.name")
+ assert_has_value("republication_interval")
+
+ if ad_cfg["id"]:
+ ad_cfg["id"] = int(ad_cfg["id"])
+
+ if ad_cfg["category"]:
+ ad_cfg["category"] = self.categories.get(ad_cfg["category"], ad_cfg["category"])
+
+ if ad_cfg["images"]:
+ images = set()
+ for image_pattern in ad_cfg["images"]:
+ for image_file in glob.glob(image_pattern, root_dir = os.path.dirname(ad_file), recursive = True):
+ _, image_file_ext = os.path.splitext(image_file)
+ ensure(image_file_ext.lower() in (".gif", ".jpg", ".jpeg", ".png"), f'Unsupported image file type [{image_file}]')
+ if os.path.isabs(image_file):
+ images.add(image_file)
+ else:
+ images.add(os.path.join(os.path.dirname(ad_file), image_file))
+ ensure(images or not ad_cfg["images"], f'No images found for given file patterns {ad_cfg["images"]} at {os.getcwd()}')
+ ad_cfg["images"] = sorted(images)
+
+ ads.append((
+ ad_file,
+ ad_cfg,
+ ad_cfg_orig
+ ))
+
+ LOG.info(" -> loaded %s", pluralize("ad", ads))
+ return ads
+
+ def load_config(self) -> None:
+ config_defaults = utils.load_dict_from_module(resources, "config_defaults.yaml")
+ config = utils.load_dict(self.config_file_path, "config", must_exist = False)
+
+ if config is None:
+ LOG.warning("Config file %s does not exist. Creating it with default values...", self.config_file_path)
+ utils.save_dict(self.config_file_path, config_defaults)
+ config = {}
+
+ self.config = apply_defaults(config, config_defaults)
+
+ self.categories = utils.load_dict_from_module(resources, "categories.yaml", "categories")
+ if self.config["categories"]:
+ self.categories.update(self.config["categories"])
+ LOG.info(" -> found %s", pluralize("category", self.categories))
+
+ ensure(self.config["login"]["username"], f'[login.username] not specified @ [{self.config_file_path}]')
+ ensure(self.config["login"]["password"], f'[login.password] not specified @ [{self.config_file_path}]')
+
+ self.browser_arguments = self.config["browser"]["arguments"]
+ self.browser_binary_location = self.config["browser"]["binary_location"]
+
+ def login(self) -> None:
+ LOG.info("Logging in as [%s]...", self.config["login"]["username"])
+ self.web_open(f'{self.root_url}/m-einloggen.html')
+
+ # accept privacy banner
+ self.web_click(By.ID, 'gdpr-banner-accept')
+
+ self.web_input(By.ID, 'login-email', self.config["login"]["username"])
+ self.web_input(By.ID, 'login-password', self.config["login"]["password"])
+
+ self.handle_captcha_if_present("login-recaptcha", "but DON'T click 'Einloggen'.")
+
+ self.web_click(By.ID, 'login-submit')
+
+ pause(800, 3000)
+
+ def handle_captcha_if_present(self, captcha_element_id:str, msg:str) -> None:
+ try:
+ self.web_click(By.XPATH, f'//*[@id="{captcha_element_id}"]')
+ except NoSuchElementException:
+ return
+
+ LOG.warning("############################################")
+ LOG.warning("# Captcha present! Please solve and close the captcha, %s", msg)
+ LOG.warning("############################################")
+ self.webdriver.switch_to.frame(self.web_find(By.CSS_SELECTOR, f'#{captcha_element_id} iframe'))
+ self.web_await(lambda _: self.webdriver.find_element(By.ID, 'recaptcha-anchor').get_attribute('aria-checked') == "true", timeout = 5 * 60)
+ self.webdriver.switch_to.default_content()
+
+ def delete_ad(self, ad_cfg: Dict[str, Any]) -> bool:
+ LOG.info("Deleting ad '%s' if already present...", ad_cfg["title"])
+
+ self.web_open(f"{self.root_url}/m-meine-anzeigen.html")
+ csrf_token_elem = self.web_find(By.XPATH, '//meta[@name="_csrf"]')
+ csrf_token = csrf_token_elem.get_attribute("content")
+
+ published_ads = json.loads(self.web_request(f"{self.root_url}/m-meine-anzeigen-verwalten.json?sort=DEFAULT")["content"])["ads"]
+
+ for published_ad in published_ads:
+ published_ad_id = int(published_ad.get("id", -1))
+ published_ad_title = published_ad.get("title", "")
+ if ad_cfg["id"] == published_ad_id or ad_cfg["title"] == published_ad_title:
+ LOG.info(" -> deleting %s '%s'...", published_ad_id, published_ad_title)
+ self.web_request(
+ url = f"{self.root_url}/m-anzeigen-loeschen.json?ids={published_ad_id}",
+ method = "POST",
+ headers = {'x-csrf-token': csrf_token}
+ )
+ pause(1500, 3000)
+
+ ad_cfg["id"] = None
+ return True
+
+ def publish_ads(self, ad_cfgs:Iterable[Dict[str, Any]]) -> None:
+ count = 0
+
+ for (ad_file, ad_cfg, ad_cfg_orig) in ad_cfgs:
+ count += 1
+ LOG.info("Processing %s/%s: '%s' from [%s]...", count, len(ad_cfgs), ad_cfg["title"], ad_file)
+ self.publish_ad(ad_file, ad_cfg, ad_cfg_orig)
+ pause(3000, 5000)
+
+ LOG.info("############################################")
+ LOG.info("(Re-)published %s", pluralize("ad", count))
+ LOG.info("############################################")
+
+ def publish_ad(self, ad_file, ad_cfg: Dict[str, Any], ad_cfg_orig: Dict[str, Any]) -> None:
+ self.delete_ad(ad_cfg)
+
+ LOG.info("Publishing ad '%s'...", ad_cfg["title"])
+
+ if LOG.isEnabledFor(logging.DEBUG):
+ LOG.debug(" -> effective ad meta:")
+ YAML().dump(ad_cfg, sys.stdout)
+
+ self.web_open(f'{self.root_url}/p-anzeige-aufgeben-schritt2.html')
+
+ if ad_cfg["type"] == "WANTED":
+ self.web_click(By.ID, 'adType2')
+
+ #############################
+ # set title
+ #############################
+ self.web_input(By.ID, 'postad-title', ad_cfg["title"])
+
+ #############################
+ # set category
+ #############################
+ # trigger and wait for automatic category detection
+ self.web_click(By.ID, 'pstad-price')
+ try:
+ self.web_find(By.XPATH, "//*[@id='postad-category-path'][text()]")
+ is_category_auto_selected = True
+ except:
+ is_category_auto_selected = False
+
+ if ad_cfg["category"]:
+ self.web_click(By.ID, 'pstad-lnk-chngeCtgry')
+ self.web_find(By.ID, 'postad-step1-sbmt')
+
+ category_url = f'{self.root_url}/p-kategorie-aendern.html#?path={ad_cfg["category"]}'
+ self.web_open(category_url)
+ self.web_click(By.XPATH, "//*[@id='postad-step1-sbmt']/button")
+ else:
+ ensure(is_category_auto_selected, f'No category specified in [{ad_file}] and automatic category detection failed')
+
+ #############################
+ # set price
+ #############################
+ self.web_select(By.XPATH, "//select[@id='priceType']", ad_cfg["price_type"])
+ if ad_cfg["price_type"] != 'GIVE_AWAY':
+ self.web_input(By.ID, 'pstad-price', ad_cfg["price"])
+
+ #############################
+ # set description
+ #############################
+ self.web_execute("document.querySelector('#pstad-descrptn').value = `" + ad_cfg["description"].replace("`", "'") + "`")
+
+ #############################
+ # set contact zipcode
+ #############################
+ if ad_cfg["contact"]["zipcode"]:
+ self.web_input(By.ID, 'pstad-zip', ad_cfg["contact"]["zipcode"])
+
+ #############################
+ # set contact street
+ #############################
+ if ad_cfg["contact"]["street"]:
+ self.web_input(By.ID, 'pstad-street', ad_cfg["contact"]["street"])
+
+ #############################
+ # set contact name
+ #############################
+ if ad_cfg["contact"]["name"]:
+ self.web_input(By.ID, 'postad-contactname', ad_cfg["contact"]["name"])
+
+ #############################
+ # set contact phone
+ #############################
+ if ad_cfg["contact"]["phone"]:
+ self.web_input(By.ID, 'postad-phonenumber', ad_cfg["contact"]["phone"])
+
+ #############################
+ # upload images
+ #############################
+ LOG.info(" -> found %s", pluralize("image", ad_cfg["images"]))
+ image_upload = self.web_find(By.XPATH, "//input[@type='file']")
+
+ def count_uploaded_images():
+ return len(self.webdriver.find_elements(By.CLASS_NAME, "imagebox-new-thumbnail"))
+
+ for image in ad_cfg["images"]:
+ LOG.info(" -> uploading image [%s]", image)
+ previous_uploaded_images_count = count_uploaded_images()
+ image_upload.send_keys(image)
+ start_at = time.time()
+ while previous_uploaded_images_count == count_uploaded_images() and time.time() - start_at < 60:
+ print(".", end = '', flush = True)
+ time.sleep(1)
+ print(flush = True)
+
+ ensure(previous_uploaded_images_count < count_uploaded_images(), f"Couldn't upload image [{image}] within 60 seconds")
+ LOG.debug(" => uploaded image within %i seconds", time.time() - start_at)
+
+ #############################
+ # submit
+ #############################
+ self.web_click(By.ID, 'pstad-submit')
+ self.web_await(EC.url_contains("p-anzeige-aufgeben-bestaetigung.html?adId="), 20)
+
+ ad_cfg_orig["updated_on"] = datetime.utcnow().isoformat()
+ if not ad_cfg_orig["created_on"] and not ad_cfg_orig["id"]:
+ ad_cfg_orig["created_on"] = ad_cfg_orig["updated_on"]
+
+ # extract the ad id from the URL's query parameter
+ current_url_query_params = urllib.parse.parse_qs(urllib.parse.urlparse(self.webdriver.current_url).query)
+ ad_id = int(current_url_query_params.get('adId', None)[0])
+ ad_cfg_orig["id"] = ad_id
+
+ LOG.info(" -> SUCCESS: ad published with ID %s", ad_id)
+
+ utils.save_dict(ad_file, ad_cfg_orig)
+
+
+#############################
+# main entry point
+#############################
+def main(args:Iterable[str]):
+ if "version" not in args:
+ print(textwrap.dedent(r"""
+ _ _ _ _ _ _
+ | | _| | ___(_)_ __ __ _ _ __ _______(_) __ _ ___ _ __ | |__ ___ | |_
+ | |/ / |/ _ \ | '_ \ / _` | '_ \|_ / _ \ |/ _` |/ _ \ '_ \ ____| '_ \ / _ \| __|
+ | <| | __/ | | | | (_| | | | |/ / __/ | (_| | __/ | | |____| |_) | (_) | |_
+ |_|\_\_|\___|_|_| |_|\__,_|_| |_/___\___|_|\__, |\___|_| |_| |_.__/ \___/ \__|
+ |___/
+ https://github.com/kleinanzeigen-bot
+ """), flush = True)
+
+ utils.configure_console_logging()
+
+ signal.signal(signal.SIGINT, utils.on_sigint) # capture CTRL+C
+ sys.excepthook = utils.on_exception
+ atexit.register(utils.on_exit)
+
+ KleinanzeigenBot().run(args)
+
+
+if __name__ == '__main__':
+ utils.configure_console_logging()
+ LOG.error("Direct execution not supported. Use 'python -m kleinanzeigen_bot'")
+ sys.exit(1)
diff --git a/kleinanzeigen_bot/__main__.py b/kleinanzeigen_bot/__main__.py
new file mode 100644
index 0000000..b756170
--- /dev/null
+++ b/kleinanzeigen_bot/__main__.py
@@ -0,0 +1,8 @@
+"""
+Copyright (C) 2022 Sebastian Thomschke and contributors
+SPDX-License-Identifier: AGPL-3.0-or-later
+"""
+import sys
+import kleinanzeigen_bot
+
+kleinanzeigen_bot.main(sys.argv)
diff --git a/kleinanzeigen_bot/resources/__init__.py b/kleinanzeigen_bot/resources/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/kleinanzeigen_bot/resources/ad_fields.yaml b/kleinanzeigen_bot/resources/ad_fields.yaml
new file mode 100644
index 0000000..efea629
--- /dev/null
+++ b/kleinanzeigen_bot/resources/ad_fields.yaml
@@ -0,0 +1,18 @@
+active:
+type:
+title:
+description:
+category:
+price:
+price_type:
+shipping_type:
+images: []
+contact:
+ name:
+ street:
+ zipcode:
+ phone:
+republication_interval:
+id:
+created_on:
+updated_on:
diff --git a/kleinanzeigen_bot/resources/categories.yaml b/kleinanzeigen_bot/resources/categories.yaml
new file mode 100644
index 0000000..741f227
--- /dev/null
+++ b/kleinanzeigen_bot/resources/categories.yaml
@@ -0,0 +1,17 @@
+# Elektronik
+Notebooks: 161/27
+PCs: 161/228
+PC-Zubehör: 161/225/sonstiges
+Software: 161/225/software
+Telefone: 161/173/telefone
+
+# Freizeit
+Sammeln: 185/234/sonstige
+
+# Mode & Beauty
+Gesundheit: 153/224/gesundheit
+
+# Sonstiges
+Tauschen: 272/273
+Verleihen: 272/274
+Verschenken: 272/192
diff --git a/kleinanzeigen_bot/resources/config_defaults.yaml b/kleinanzeigen_bot/resources/config_defaults.yaml
new file mode 100644
index 0000000..912d79c
--- /dev/null
+++ b/kleinanzeigen_bot/resources/config_defaults.yaml
@@ -0,0 +1,35 @@
+ad_files:
+ - "**/ad_*.json"
+ - "**/ad_*.yml"
+ - "**/ad_*.yaml"
+
+ad_defaults:
+ active: true
+ type: OFFER
+ description:
+ prefix:
+ suffix:
+ price_type: NEGOTIABLE
+ shipping_type: SHIPPING
+ contact:
+ name:
+ street:
+ zipcode:
+ phone:
+ republication_interval: 7
+
+categories: []
+
+browser:
+ # https://peter.sh/experiments/chromium-command-line-switches/
+ arguments:
+ # https://stackoverflow.com/a/50725918/5116073
+ - --disable-dev-shm-usage
+ - --no-sandbox
+ # --headless
+ # --start-maximized
+ binary_location:
+
+login:
+ username:
+ password:
diff --git a/kleinanzeigen_bot/selenium_mixin.py b/kleinanzeigen_bot/selenium_mixin.py
new file mode 100644
index 0000000..5f64c45
--- /dev/null
+++ b/kleinanzeigen_bot/selenium_mixin.py
@@ -0,0 +1,261 @@
+"""
+Copyright (C) 2022 Sebastian Thomschke and contributors
+SPDX-License-Identifier: AGPL-3.0-or-later
+"""
+import logging, os, shutil, sys, tempfile
+from typing import Any, Callable, Dict, Final, Iterable, Tuple
+from importlib.resources import read_text as get_resource_as_string
+
+from selenium import webdriver
+from selenium.common.exceptions import NoSuchElementException, TimeoutException
+from selenium.webdriver.common.by import By
+from selenium.webdriver.chrome.service import Service as ChromeService, DEFAULT_EXECUTEABLE_PATH as DEFAULT_CHROMEDRIVER_PATH
+from selenium.webdriver.chromium.webdriver import ChromiumDriver
+from selenium.webdriver.edge.service import Service as EdgeService, DEFAULT_EXECUTEABLE_PATH as DEFAULT_EDGEDRIVER_PATH
+from selenium.webdriver.remote.webdriver import WebDriver
+from selenium.webdriver.remote.webelement import WebElement
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import Select, WebDriverWait
+import selenium_stealth
+import webdriver_manager.utils as ChromeDriverManagerUtils
+from webdriver_manager.chrome import ChromeDriverManager
+from webdriver_manager.microsoft import EdgeChromiumDriverManager
+from webdriver_manager.utils import ChromeType
+
+from .utils import ensure, is_frozen, pause
+
+LOG:Final[logging.Logger] = logging.getLogger("kleinanzeigen_bot.selenium_mixin")
+
+
+class SeleniumMixin:
+
+ def __init__(self):
+ self.browser_arguments:Iterable[str] = []
+ self.browser_binary_location:str = None
+ self.webdriver:WebDriver = None
+
+ def __del__(self):
+ if getattr(self, 'cacertfile', None):
+ os.remove(self.cacertfile)
+
+ def create_webdriver_session(self) -> None:
+ LOG.info("Creating WebDriver session...")
+
+ def init_browser_options(browser_options):
+ browser_options.add_argument("--disable-crash-reporter")
+ browser_options.add_argument("--no-first-run")
+ browser_options.add_argument("--no-service-autorun")
+ for chrome_option in self.browser_arguments:
+ LOG.info(" -> Custom chrome argument: %s", chrome_option)
+ browser_options.add_argument(chrome_option)
+
+ browser_options.add_experimental_option('excludeSwitches', ['enable-automation'])
+ browser_options.add_experimental_option('useAutomationExtension', False)
+ browser_options.add_experimental_option("prefs", {
+ "credentials_enable_service": False,
+ "profile.password_manager_enabled": False,
+ "devtools.preferences.currentDockState": "\"bottom\""
+ })
+
+ if self.browser_binary_location:
+ browser_options.binary_location = self.browser_binary_location
+ LOG.info(" -> Chrome binary location: %s", self.browser_binary_location)
+
+ return browser_options
+
+ # if run via py2exe fix resource lookup
+ if is_frozen():
+ import pathlib # pylint: disable=import-outside-toplevel
+
+ if not os.getenv("REQUESTS_CA_BUNDLE", None) or not os.path.exists(os.getenv("REQUESTS_CA_BUNDLE", None)):
+ with tempfile.NamedTemporaryFile(delete = False) as tmp:
+ LOG.debug("Writing cacert file to [%s]...", tmp.name)
+ tmp.write(get_resource_as_string("certifi", "cacert.pem").encode('utf-8'))
+ self.cacertfile = tmp.name
+ os.environ['REQUESTS_CA_BUNDLE'] = self.cacertfile
+
+ read_text_orig = pathlib.Path.read_text
+
+ def read_text_new(self, encoding = None, errors = None):
+ path = str(self)
+ if "selenium_stealth" in path:
+ return get_resource_as_string("selenium_stealth", self.name)
+ return read_text_orig(self, encoding, errors)
+
+ pathlib.Path.read_text = read_text_new
+
+ # check if a chrome driver is present already
+ if shutil.which(DEFAULT_CHROMEDRIVER_PATH):
+ self.webdriver = webdriver.Chrome(options = init_browser_options(webdriver.ChromeOptions()))
+ elif shutil.which(DEFAULT_EDGEDRIVER_PATH):
+ self.webdriver = webdriver.ChromiumEdge(options = init_browser_options(webdriver.EdgeOptions()))
+ else:
+ # determine browser major version
+ if self.browser_binary_location:
+ chrome_type, chrome_version = self.get_browser_version(self.browser_binary_location)
+ else:
+ chrome_type, chrome_version = self.get_browser_version_from_os()
+ chrome_major_version = chrome_version.split(".", 1)[0]
+
+ # download and install matching chrome driver
+ if chrome_type == ChromeType.MSEDGE:
+ webdriver_mgr = EdgeChromiumDriverManager(cache_valid_range = 14)
+ webdriver_mgr.driver.browser_version = chrome_major_version
+ webdriver_path = webdriver_mgr.install()
+ self.webdriver = webdriver.ChromiumEdge(service = EdgeService(webdriver_path), options = init_browser_options(webdriver.EdgeOptions()))
+ else:
+ webdriver_mgr = ChromeDriverManager(chrome_type = chrome_type, cache_valid_range = 14)
+ webdriver_mgr.driver.browser_version = chrome_major_version
+ webdriver_path = webdriver_mgr.install()
+ self.webdriver = webdriver.Chrome(service = ChromeService(webdriver_path), options = init_browser_options(webdriver.ChromeOptions()))
+
+ # workaround to support Edge, see https://github.com/diprajpatra/selenium-stealth/pull/25
+ selenium_stealth.Driver = ChromiumDriver
+
+ selenium_stealth.stealth(self.webdriver, # https://github.com/diprajpatra/selenium-stealth#args
+ languages = ("de-DE", "de", "en-US", "en"),
+ vendor = "Google Inc.",
+ platform = "Win32",
+ webgl_vendor = "Intel Inc.",
+ renderer = "Intel Iris OpenGL Engine",
+ fix_hairline = True,
+ )
+
+ LOG.info("New WebDriver session is: %s %s", self.webdriver.session_id, self.webdriver.command_executor._url) # pylint: disable=protected-access
+
+ def get_browser_version(self, executable_path: str) -> Tuple[ChromeType, str]:
+ if sys.platform == "win32":
+ import win32api # pylint: disable=import-outside-toplevel,import-error
+ # pylint: disable=no-member
+ lang, codepage = win32api.GetFileVersionInfo(executable_path, "\\VarFileInfo\\Translation")[0]
+ product_name = win32api.GetFileVersionInfo(executable_path, f"\\StringFileInfo\\{lang:04X}{codepage:04X}\\ProductName")
+ product_version = win32api.GetFileVersionInfo(executable_path, f"\\StringFileInfo\\{lang:04X}{codepage:04X}\\ProductVersion")
+ # pylint: enable=no-member
+ match product_name:
+ case "Chromium":
+ return (ChromeType.CHROMIUM, product_version)
+ case "Microsoft Edge":
+ return (ChromeType.MSEDGE, product_version)
+ case _: # "Google Chrome"
+ return (ChromeType.GOOGLE, product_version)
+
+ if sys.platform.startswith("linux"):
+ cmd = ChromeDriverManagerUtils.linux_browser_apps_to_cmd(executable_path)
+ else:
+ cmd = executable_path + " --version"
+
+ version = ChromeDriverManagerUtils.read_version_from_cmd(cmd, r'\d+\.\d+\.\d+')
+ filename = os.path.basename(executable_path).lower()
+ if "chromium" in filename:
+ return (ChromeType.CHROMIUM, version)
+ if "edge" in filename:
+ return (ChromeType.MSEDGE, version)
+ return (ChromeType.GOOGLE, version)
+
+ def get_browser_version_from_os(self) -> Tuple[ChromeType, str]:
+ version = ChromeDriverManagerUtils.get_browser_version_from_os(ChromeType.CHROMIUM)
+ if version != "UNKNOWN":
+ return (ChromeType.CHROMIUM, version)
+ LOG.debug("Chromium not found")
+
+ version = ChromeDriverManagerUtils.get_browser_version_from_os(ChromeType.GOOGLE)
+ if version != "UNKNOWN":
+ return (ChromeType.GOOGLE, version)
+ LOG.debug("Google Chrome not found")
+
+ version = ChromeDriverManagerUtils.get_browser_version_from_os(ChromeType.MSEDGE)
+ if version != "UNKNOWN":
+ return (ChromeType.MSEDGE, version)
+ LOG.debug("Microsoft Edge not found")
+
+ return (None, None)
+
+ def web_await(self, condition: Callable[[WebDriver], WebElement], timeout:int = 5) -> WebElement:
+ """
+ :param timeout: timeout in seconds
+ :raises NoSuchElementException: if element could not be found within time
+ """
+ try:
+ return WebDriverWait(self.webdriver, timeout).until(condition)
+ except TimeoutException as ex:
+ raise NoSuchElementException from ex
+
+ def web_click(self, selector_type:By, selector_value:str, timeout:int = 5) -> WebElement:
+ """
+ :param timeout: timeout in seconds
+ :raises NoSuchElementException: if element could not be found within time
+ """
+ elem = self.web_await(EC.element_to_be_clickable((selector_type, selector_value)), timeout)
+ elem.click()
+ pause()
+ return elem
+
+ def web_execute(self, javascript:str) -> Any:
+ """
+ :return: The command's JSON response
+ """
+ return self.webdriver.execute_script(javascript)
+
+ def web_find(self, selector_type:By, selector_value:str, timeout:int = 5) -> WebElement:
+ """
+ :param timeout: timeout in seconds
+ :raises NoSuchElementException: if element could not be found within time
+ """
+ return self.web_await(EC.presence_of_element_located((selector_type, selector_value)), timeout)
+
+ def web_input(self, selector_type:By, selector_value:str, text:str, timeout:int = 5) -> WebElement:
+ """
+ :param timeout: timeout in seconds
+ :raises NoSuchElementException: if element could not be found within time
+ """
+ input_field = self.web_find(selector_type, selector_value, timeout)
+ input_field.clear()
+ input_field.send_keys(text)
+ pause()
+
+ def web_open(self, url, timeout = 10, reload_if_already_open = False) -> None:
+ LOG.debug(" -> Opening [%s]...", url)
+ if not reload_if_already_open and url == self.webdriver.current_url:
+ LOG.debug(" => skipping, [%s] is already open", url)
+ return
+ self.webdriver.get(url)
+ WebDriverWait(self.webdriver, timeout).until(lambda _: self.web_execute("return document.readyState") == "complete")
+
+ # pylint: disable=dangerous-default-value
+ def web_request(self, url:str, method:str = "GET", valid_response_codes:Iterable[int] = [200], headers:Dict[str, str] = None) -> Dict[str, Any]:
+ method = method.upper()
+ LOG.debug(" -> HTTP %s [%s]...", method, url)
+ response = self.webdriver.execute_async_script(f"""
+ var callback = arguments[arguments.length - 1];
+ fetch("{url}", {{
+ method: "{method}",
+ redirect: "follow",
+ headers: {headers or {}}
+ }})
+ .then(response => response.text().then(responseText => {{
+ headers = {{}};
+ response.headers.forEach((v, k) => headers[k] = v);
+ callback({{
+ "statusCode": response.status,
+ "statusMessage": response.statusText,
+ "headers": headers,
+ "content": responseText
+ }})
+ }}))
+ """)
+ ensure(
+ response["statusCode"] in valid_response_codes,
+ f'Invalid response "{response["statusCode"]} response["statusMessage"]" received for HTTP {method} to {url}'
+ )
+ return response
+ # pylint: enable=dangerous-default-value
+
+ def web_select(self, selector_type:By, selector_value:str, selected_value:Any, timeout:int = 5) -> WebElement:
+ """
+ :param timeout: timeout in seconds
+ :raises NoSuchElementException: if element could not be found within time
+ """
+ elem = self.web_await(EC.element_to_be_clickable((selector_type, selector_value)), timeout)
+ Select(elem).select_by_value(selected_value)
+ pause()
+ return elem
diff --git a/kleinanzeigen_bot/utils.py b/kleinanzeigen_bot/utils.py
new file mode 100644
index 0000000..56fb910
--- /dev/null
+++ b/kleinanzeigen_bot/utils.py
@@ -0,0 +1,183 @@
+"""
+Copyright (C) 2022 Sebastian Thomschke and contributors
+SPDX-License-Identifier: AGPL-3.0-or-later
+"""
+import copy, json, logging, os, secrets, sys, traceback, time
+from importlib.resources import read_text as get_resource_as_string
+from types import ModuleType
+from typing import Any, Dict, Final, Iterable, Optional, Union
+
+import coloredlogs, inflect
+from ruamel.yaml import YAML
+
+LOG_ROOT:Final[logging.Logger] = logging.getLogger()
+LOG:Final[logging.Logger] = logging.getLogger("kleinanzeigen_bot.utils")
+
+
+def ensure(condition:bool, error_message:str) -> None:
+ """
+ :raises AssertionError: if condition is False
+ """
+ if not condition:
+ raise AssertionError(error_message)
+
+
+def is_frozen() -> bool:
+ """
+ >>> is_frozen()
+ False
+ """
+ return getattr(sys, 'frozen', False)
+
+
+def apply_defaults(target:Dict[Any, Any], defaults:Dict[Any, Any], ignore = lambda _k, _v: False, override = lambda _k, _v: False) -> Dict[Any, Any]:
+ """
+ >>> apply_defaults({}, {"foo": "bar"})
+ {'foo': 'bar'}
+ >>> apply_defaults({"foo": "foo"}, {"foo": "bar"})
+ {'foo': 'foo'}
+ >>> apply_defaults({"foo": ""}, {"foo": "bar"})
+ {'foo': ''}
+ >>> apply_defaults({}, {"foo": "bar"}, ignore = lambda k, _: k == "foo")
+ {}
+ >>> apply_defaults({"foo": ""}, {"foo": "bar"}, override = lambda _, v: v == "")
+ {'foo': 'bar'}
+ >>> apply_defaults({"foo": None}, {"foo": "bar"}, override = lambda _, v: v == "")
+ {'foo': None}
+ """
+ for key, default_value in defaults.items():
+ if key in target:
+ if isinstance(target[key], Dict) and isinstance(default_value, Dict):
+ apply_defaults(target[key], default_value, ignore = ignore)
+ elif override(key, target[key]):
+ target[key] = copy.deepcopy(default_value)
+ else:
+ if not ignore(key, default_value):
+ target[key] = copy.deepcopy(default_value)
+ return target
+
+
+def safe_get(a_map:Dict[Any, Any], *keys:str) -> Any:
+ """
+ >>> safe_get({"foo": {}}, "foo", "bar") is None
+ True
+ >>> safe_get({"foo": {"bar": "some_value"}}, "foo", "bar")
+ 'some_value'
+ """
+ if a_map:
+ for key in keys:
+ try:
+ a_map = a_map[key]
+ except (KeyError, TypeError):
+ return None
+ return a_map
+
+
+def configure_console_logging() -> None:
+ stdout_log = logging.StreamHandler(sys.stderr)
+ stdout_log.setLevel(logging.DEBUG)
+ stdout_log.setFormatter(coloredlogs.ColoredFormatter('[%(levelname)s] %(message)s'))
+ stdout_log.addFilter(type("", (logging.Filter,), {
+ "filter": lambda rec: rec.levelno <= logging.INFO
+ }))
+ LOG_ROOT.addHandler(stdout_log)
+
+ stderr_log = logging.StreamHandler(sys.stderr)
+ stderr_log.setLevel(logging.WARNING)
+ stderr_log.setFormatter(coloredlogs.ColoredFormatter('[%(levelname)s] %(message)s'))
+ LOG_ROOT.addHandler(stderr_log)
+
+
+def on_exception(ex_type, ex_value, ex_traceback) -> None:
+ if issubclass(ex_type, KeyboardInterrupt):
+ sys.__excepthook__(ex_type, ex_value, ex_traceback)
+ return
+ if LOG.isEnabledFor(logging.DEBUG) or isinstance(ex_value, (AttributeError, ImportError, NameError)):
+ LOG.error("".join(traceback.format_exception(ex_type, ex_value, ex_traceback)))
+ elif isinstance(ex_value, AssertionError):
+ LOG.error(ex_value)
+ else:
+ LOG.error("%s: %s", ex_type.__name__, ex_value)
+
+
+def on_exit() -> None:
+ for handler in LOG_ROOT.handlers:
+ handler.flush()
+
+
+def on_sigint(_sig:int, _frame) -> None:
+ LOG.warning('Aborted on user request.')
+ sys.exit(0)
+
+
+def pause(min_ms:int = 200, max_ms:int = None) -> None:
+ duration = secrets.randbelow((max_ms is None and 2000 or max_ms) - min_ms) + min_ms
+ LOG.log(logging.INFO if duration > 1500 else logging.DEBUG, " ... pausing for %d ms ...", duration)
+ time.sleep(duration / 1000)
+
+
+def pluralize(word:str, count:Union[int, Iterable], prefix = True):
+ """
+ >>> pluralize("field", 1)
+ '1 field'
+ >>> pluralize("field", 2)
+ '2 fields'
+ >>> pluralize("field", 2, prefix = False)
+ 'fields'
+ """
+ if not hasattr(pluralize, "inflect"):
+ pluralize.inflect = inflect.engine()
+ if isinstance(count, Iterable):
+ count = len(count)
+ plural = pluralize.inflect.plural_noun(word, count)
+ if prefix:
+ return f'{count} {plural}'
+ return plural
+
+
+def load_dict(filepath:str, content_label:str = "", must_exist = True) -> Optional[Dict[str, Any]]:
+ filepath = os.path.abspath(filepath)
+ LOG.info("Loading %s[%s]...", content_label and content_label + " from " or "", filepath)
+
+ _, file_ext = os.path.splitext(filepath)
+ if not file_ext in [ ".json", ".yaml" , ".yml" ]:
+ raise ValueError(f'Unsupported file type. The file name "{filepath}" must end with *.json, *.yaml, or *.yml')
+
+ if not os.path.exists(filepath):
+ if must_exist:
+ raise FileNotFoundError(filepath)
+ return None
+
+ with open(filepath, encoding = "utf-8") as file:
+ return json.load(file) if filepath.endswith(".json") else YAML().load(file)
+
+
+def load_dict_from_module(module:ModuleType, filename:str, content_label:str = "", must_exist = True) -> Optional[Dict[str, Any]]:
+ LOG.debug("Loading %s[%s.%s]...", content_label and content_label + " from " or "", module.__name__, filename)
+
+ _, file_ext = os.path.splitext(filename)
+ if not file_ext in [ ".json", ".yaml" , ".yml" ]:
+ raise ValueError(f'Unsupported file type. The file name "{filename}" must end with *.json, *.yaml, or *.yml')
+
+ try:
+ content = get_resource_as_string(module, filename)
+ except FileNotFoundError as ex:
+ if must_exist:
+ raise ex
+ return None
+
+ return json.loads(content) if filename.endswith(".json") else YAML().load(content)
+
+
+def save_dict(filepath:str, content:Dict[str, Any]) -> None:
+ filepath = os.path.abspath(filepath)
+ LOG.info("Saving [%s]...", filepath)
+ with open(filepath, "w", encoding = "utf-8") as file:
+ if filepath.endswith(".json"):
+ file.write(json.dumps(content, indent = 2, ensure_ascii = False))
+ else:
+ yaml = YAML()
+ yaml.indent(mapping = 2, sequence = 4, offset = 2)
+ yaml.allow_duplicate_keys = False
+ yaml.explicit_start = False
+ yaml.dump(content, file)
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..b3c16e5
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,54 @@
+# https://pip.pypa.io/en/stable/reference/build-system/pyproject-toml/
+
+#####################
+# bandit https://github.com/PyCQA/bandit
+#####################
+[tool.bandit]
+exclude = ["*/.eggs/*"] # broken :-( https://github.com/PyCQA/bandit/issues/657
+
+
+#####################
+# pylint
+#####################
+[tool.pylint.master]
+extension-pkg-whitelist = "win32api"
+ignore = "version.py"
+jobs = 4
+persistent = "no"
+
+[tool.pylint.basic]
+good-names = ["i", "j", "k", "v", "by", "ex", "fd", "_"]
+
+[tool.pylint.format]
+# https://pylint.pycqa.org/en/latest/technical_reference/features.html#format-checker
+max-line-length = 160
+
+[tool.pylint.logging]
+logging-modules = "logging"
+
+[tool.pylint.messages_control]
+# https://pylint.pycqa.org/en/latest/technical_reference/features.html#messages-control-options
+disable= [
+ "bare-except",
+ "missing-docstring",
+ "multiple-imports",
+ "multiple-statements",
+ "no-self-use"
+]
+
+[tool.pylint.miscelaneous]
+notes = [ "FIXME", "XXX", "TODO" ]
+
+[tool.pylint.design]
+max-attributes = 10
+max-branches = 20
+max-locals = 30
+max-returns = 10
+max-statements = 70
+
+#####################
+# pytest
+#####################
+[tool.pytest.ini_options]
+#https://docs.pytest.org/en/stable/reference.html#confval-addopts
+addopts = "-p no:cacheprovider --doctest-modules --ignore=kleinanzeigen_bot/__main__.py"
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000..2eda5db
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,6 @@
+bandit~=1.7.1
+py2exe~=0.11.0.1; sys_platform == 'win32'
+pylint~=2.12.2
+pytest~=6.2.5
+setuptools~=60.5.0
+wheel~=0.37.1
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..3e61ab8
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,7 @@
+coloredlogs~=15.0.1
+inflect~=5.3.0
+ruamel.yaml~=0.17.20
+pywin32==303; sys_platform == 'win32'
+selenium~=4.1.0
+selenium_stealth~=1.0.6
+webdriver_manager~=3.5.2
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..f7c73cd
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""
+Copyright (C) 2022 Sebastian Thomschke and contributors
+SPDX-License-Identifier: AGPL-3.0-or-later
+"""
+import sys, warnings
+import setuptools
+
+warnings.filterwarnings("ignore", message = "setup_requires is deprecated", category = setuptools.SetuptoolsDeprecationWarning)
+warnings.filterwarnings("ignore", message = "setuptools.installer is deprecated", category = setuptools.SetuptoolsDeprecationWarning)
+
+setup_args = {}
+
+if "py2exe" in sys.argv:
+ import importlib.resources, glob, os, py2exe, zipfile
+
+ # py2exe config https://www.py2exe.org/index.cgi/ListOfOptions
+ setup_args["options"] = {
+ "py2exe": {
+ "bundle_files": 1, # 1 = include the python runtime
+ "compressed": True,
+ "optimize": 2,
+ "includes": [
+ "kleinanzeigen_bot"
+ ],
+ "excludes": [
+ "_aix_support",
+ "_osx_support",
+ "argparse",
+ "backports",
+ "bz2",
+ "cryptography.hazmat",
+ "distutils",
+ "doctest",
+ "ftplib",
+ "lzma",
+ "pep517",
+ "pip",
+ "pydoc",
+ "pydoc_data",
+ "optparse",
+ "pyexpat",
+ "six",
+ "statistics",
+ "test",
+ "unittest",
+ "xml.sax"
+ ]
+ }
+ }
+ setup_args["console"] = [{
+ "script": "kleinanzeigen_bot/__main__.py",
+ "dest_base": "kleinanzeigen-bot",
+ }]
+ setup_args["zipfile"] = None
+
+ #
+ # embedding required DLLs directly into the exe
+ #
+ # http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls
+ bundle_dlls = ("libcrypto", "libffi", "libssl")
+ orig_determine_dll_type = py2exe.dllfinder.DllFinder.determine_dll_type
+
+ def determine_dll_type(self, dll_filepath):
+ basename = os.path.basename(dll_filepath)
+ if basename.startswith(bundle_dlls):
+ return "EXT"
+ return orig_determine_dll_type(self, dll_filepath)
+
+ py2exe.dllfinder.DllFinder.determine_dll_type = determine_dll_type
+
+ #
+ # embedding required resource files directly into the exe
+ #
+ files_to_embed = [
+ ("kleinanzeigen_bot/resources", "kleinanzeigen_bot/resources/*.yaml"),
+ ("certifi", importlib.resources.path("certifi", "cacert.pem")),
+ ("selenium_stealth", os.path.dirname(importlib.resources.path("selenium_stealth.js", "util.js")))
+ ]
+
+ orig_copy_files = py2exe.runtime.Runtime.copy_files
+
+ def embed_files(self, destdir):
+ orig_copy_files(self, destdir)
+
+ libpath = os.path.join(destdir, "kleinanzeigen-bot.exe")
+ with zipfile.ZipFile(libpath, "a", zipfile.ZIP_DEFLATED if self.options.compress else zipfile.ZIP_STORED) as arc:
+ for target, source in files_to_embed:
+ print(source)
+ if os.path.isdir(source):
+ for file in os.listdir(source):
+ if self.options.verbose:
+ print(f"Embedding file {source}\\{file} in {libpath}")
+ arc.write(os.path.join(source, file), target + "/" + file)
+ elif isinstance(source, str):
+ for file in glob.glob(source, root_dir = os.getcwd(), recursive = True):
+ if self.options.verbose:
+ print(f"Embedding file {file} in {libpath}")
+ arc.write(file, target + "/" + os.path.basename(file))
+ else:
+ if self.options.verbose:
+ print(f"Embedding file {source} in {libpath}")
+ arc.write(source, target + "/" + os.path.basename(source))
+ os.remove(os.path.join(destdir, "cacert.pem")) # file was embedded
+
+ py2exe.runtime.Runtime.copy_files = embed_files
+
+ #
+ # use best zip compression level 9
+ #
+ from zipfile import ZipFile
+
+ class ZipFileExt(ZipFile):
+
+ def __init__(self, file, mode = "r", compression = zipfile.ZIP_STORED):
+ super().__init__(file, mode, compression, compresslevel = 9)
+
+ py2exe.runtime.zipfile.ZipFile = ZipFileExt
+
+
+def load_requirements(filepath:str):
+ with open(filepath, encoding = "utf-8") as fd:
+ return [nonempty for line in fd if (nonempty := line.strip())]
+
+
+setuptools.setup(
+ name = "kleinanzeigen-bot",
+ use_scm_version = {
+ "write_to": "kleinanzeigen_bot/version.py",
+ },
+ packages = setuptools.find_packages(""),
+ package_data = {"kleinanzeigen_bot": ["*.yaml"]},
+
+ # https://docs.python.org/3/distutils/setupscript.html#additional-meta-data
+ author = "The kleinanzeigen-bot authors",
+ url = "https://github.com/kleinanzeigen-bot/kleinanzeigen-bot",
+ description = "Command line tool to publish ads on ebay-kleinanzeigen.de",
+ license = "GNU AGPL 3.0+",
+ classifiers = [ # https://pypi.org/classifiers/
+ "Development Status :: 4 - Beta",
+ "Environment :: Console",
+ "Operating System :: OS Independent",
+
+ "Intended Audience :: End Users/Desktop",
+ "Topic :: Office/Business",
+
+ "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
+ "Programming Language :: Python :: 3.10",
+ ],
+
+ python_requires = ">=3.10",
+ install_requires = load_requirements("requirements.txt"),
+ extras_require = {
+ "dev": load_requirements("requirements-dev.txt")
+ },
+ setup_requires = [
+ "setuptools_scm"
+ ],
+
+ ** setup_args
+)