From ab73397b8225ad0a150bafd8cf1ffc79b1f49547 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Fri, 20 Sep 2024 14:01:36 +0200 Subject: [PATCH 01/31] Converted to dotnet project --- .dockerignore | 27 + .gitignore | 322 +++++--- LICENSE | 695 +----------------- MoxfieldPriceScraper.sln | 21 + MoxfieldPriceScraper/Dockerfile | 24 + MoxfieldPriceScraper/EmailService.cs | 61 ++ MoxfieldPriceScraper/IMoxfieldScraper.cs | 11 + MoxfieldPriceScraper/ISettings.cs | 19 + MoxfieldPriceScraper/LoggerFactory.cs | 45 ++ .../MoxfieldPriceScraper.csproj | 26 + MoxfieldPriceScraper/MoxfieldScraper.cs | 299 ++++++++ MoxfieldPriceScraper/Program.cs | 66 ++ MoxfieldPriceScraper/Settings.cs | 83 +++ MoxfieldPriceScraper/settings.json | 14 + README.md | 72 +- config.py | 78 -- docker-compose.yml | 6 + email_notification.py | 36 - main.py | 12 - menu.py | 151 ---- moxfield_scraper.py | 193 ----- requirements.txt | 2 - 22 files changed, 973 insertions(+), 1290 deletions(-) create mode 100644 .dockerignore create mode 100644 MoxfieldPriceScraper.sln create mode 100644 MoxfieldPriceScraper/Dockerfile create mode 100644 MoxfieldPriceScraper/EmailService.cs create mode 100644 MoxfieldPriceScraper/IMoxfieldScraper.cs create mode 100644 MoxfieldPriceScraper/ISettings.cs create mode 100644 MoxfieldPriceScraper/LoggerFactory.cs create mode 100644 MoxfieldPriceScraper/MoxfieldPriceScraper.csproj create mode 100644 MoxfieldPriceScraper/MoxfieldScraper.cs create mode 100644 MoxfieldPriceScraper/Program.cs create mode 100644 MoxfieldPriceScraper/Settings.cs create mode 100644 MoxfieldPriceScraper/settings.json delete mode 100644 config.py create mode 100644 docker-compose.yml delete mode 100644 email_notification.py delete mode 100644 main.py delete mode 100644 menu.py delete mode 100644 moxfield_scraper.py delete mode 100644 requirements.txt diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c67702b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,27 @@ +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.idea +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +**/Logs +**/Data +LICENSE +README.md diff --git a/.gitignore b/.gitignore index df4874c..ba4ee6b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,139 +1,233 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -pip-wheel-metadata/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: +# The following command works for downloading when using Git for Windows: +# curl -LOf http://gist.githubusercontent.com/kmorcinek/2710267/raw/.gitignore +# +# Download this file using PowerShell v3 under Windows with the following comand: +# Invoke-WebRequest https://gist.githubusercontent.com/kmorcinek/2710267/raw/ -OutFile .gitignore +# +# or wget: +# wget --no-check-certificate http://gist.githubusercontent.com/kmorcinek/2710267/raw/.gitignore + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Rr]elease/ +x64/ +[Bb]in/ +[Oo]bj/ +# build folder is nowadays used for build scripts and should not be ignored +#build/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj *.log -local_settings.py -db.sqlite3 -db.sqlite3-journal +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# OS generated files # +.DS_Store* +Icon? + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings +modulesbin/ +tempbin/ + +# EPiServer Site file (VPP) +AppData/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# vim +*.txt~ +*.swp +*.swo + +# Temp files when opening LibreOffice on ubuntu +.~lock.* + +# svn +.svn + +# CVS - Source Control +**/CVS/ + +# Remainings from resolving conflicts in Source Control +*.orig -# Flask stuff: -instance/ -.webassets-cache +# SQL Server files +**/App_Data/*.mdf +**/App_Data/*.ldf +**/App_Data/*.sdf -# Scrapy stuff: -.scrapy -# Sphinx documentation -docs/_build/ +#LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml -# PyBuilder -target/ +# ========================= +# Windows detritus +# ========================= -# Jupyter Notebook -.ipynb_checkpoints +# Windows image file caches +Thumbs.db +ehthumbs.db -# IPython -profile_default/ -ipython_config.py +# Folder config file +Desktop.ini -# pyenv -.python-version +# Recycle Bin used on file shares +$RECYCLE.BIN/ -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock +# Mac desktop service store files +.DS_Store -# PEP 582; used by e.g. github.com/David-OConnor/pyflow -__pypackages__/ +# SASS Compiler cache +.sass-cache -# Celery stuff -celerybeat-schedule -celerybeat.pid +# Visual Studio 2014 CTP +**/*.sln.ide -# SageMath parsed files -*.sage.py +# Visual Studio temp something +.vs/ -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ +# dotnet stuff +project.lock.json -# Spyder project settings -.spyderproject -.spyproject +# VS 2015+ +*.vc.vc.opendb +*.vc.db -# Rope project settings -.ropeproject +# Rider +.idea/ -# mkdocs documentation -/site +# Visual Studio Code +.vscode/ -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json +# Output folder used by Webpack or other FE stuff +**/node_modules/* +#**/wwwroot/* -# Pyre type checker -.pyre/ +# SpecFlow specific +*.feature.cs +*.feature.xlsx.* +*.Specs_*.html -# IntelliJ -.idea +##### +# End of core ignore list, below put you custom 'per project' settings (patterns or path) +##### # Data [Dd]ata/ -settings.json +[Ll]ogs/ # Images *.png +*.jpng diff --git a/LICENSE b/LICENSE index f288702..a6389c8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 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 General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is 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. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - 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. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - 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 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. Use with the GNU Affero General Public License. - - 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 Affero 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 special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU 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 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 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 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - 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 GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2023 Nicolai Hejlesen Jørgensen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MoxfieldPriceScraper.sln b/MoxfieldPriceScraper.sln new file mode 100644 index 0000000..b6db665 --- /dev/null +++ b/MoxfieldPriceScraper.sln @@ -0,0 +1,21 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MoxfieldPriceScraper", "MoxfieldPriceScraper\MoxfieldPriceScraper.csproj", "{59040D38-0177-4DBB-B527-651DDEC710EA}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3726EE0C-A16A-483E-881C-4290B7B95620}" + ProjectSection(SolutionItems) = preProject + docker-compose.yml = docker-compose.yml + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {59040D38-0177-4DBB-B527-651DDEC710EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59040D38-0177-4DBB-B527-651DDEC710EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59040D38-0177-4DBB-B527-651DDEC710EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59040D38-0177-4DBB-B527-651DDEC710EA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile new file mode 100644 index 0000000..4420c17 --- /dev/null +++ b/MoxfieldPriceScraper/Dockerfile @@ -0,0 +1,24 @@ +FROM alpine:3.20 as base + +RUN useradd -m moxfieldpricescraper +USER moxfieldpricescraper + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env +ARG BUILD_CONFIGURATION=Release +WORKDIR /app + +COPY *.csproj ./ +RUN dotnet restore --disable-parallel + +COPY . ./ +RUN dotnet publish -c $BUILD_CONFIGURATION -o out --no-restore + +FROM mcr.microsoft.com/dotnot/runtime:8.0 AS runtime +WORKDIR /app +COPY --from=build-env /app/out . + +# Set environment variable to disable GPU hardware acceleration +ENV CHROME_NO_SANDBOX=1 +ENV CHROME_DISABLE_GPU=1 + +ENTRYPOINT ["dotnet", "MoxfieldPriceScraper.dll"] diff --git a/MoxfieldPriceScraper/EmailService.cs b/MoxfieldPriceScraper/EmailService.cs new file mode 100644 index 0000000..3c17505 --- /dev/null +++ b/MoxfieldPriceScraper/EmailService.cs @@ -0,0 +1,61 @@ +using System.Net; +using System.Net.Mail; +using System.Net.Mime; +using Serilog; + +namespace MoxfieldPriceScraper; + +public static class EmailService +{ + private const string SmtpServer = "smtp.gmail.com"; + private const int SmtpPort = 587; + + /// + /// Sends an email with an embedded image. + /// + /// The email that the message should be sent from. + /// The password to the email that the message should be sent from. + /// The email that the message should be sent to. + /// The subject of the email message. + /// The body is the email message. + /// The path to the image that should be embedded in the email body. + /// The email could not be sent. + public static async Task SendEmailWithEmbeddedImageAsync(string fromEmail, string fromPassword, string toEmail, + string subject, string body, string imagePath) + { + try + { + MailMessage mailMessage = new MailMessage(); + mailMessage.From = new MailAddress(fromEmail); + mailMessage.To.Add(new MailAddress(toEmail)); + mailMessage.Subject = subject; + mailMessage.IsBodyHtml = true; + + // Embedding the image in the email body + var htmlView = AlternateView.CreateAlternateViewFromString( + body + "

", null, "text/html"); + + // Load the image and attach it as a linked resource + var imageResource = new LinkedResource(imagePath, MediaTypeNames.Image.Png) + { + ContentId = "EmbeddedImage", // Must match the src attribute in the body + TransferEncoding = TransferEncoding.Base64 + }; + + htmlView.LinkedResources.Add(imageResource); + mailMessage.AlternateViews.Add(htmlView); + + using var smtpClient = new SmtpClient(SmtpServer, SmtpPort); + smtpClient.Credentials = new NetworkCredential(fromEmail, fromPassword); + smtpClient.EnableSsl = true; + + await smtpClient.SendMailAsync(mailMessage); + Log.Information("Email with subject [{Subject}] sent successfully", subject); + } + catch (Exception e) + { + Log.Error(e, "Failed to send email"); + throw new Exception("Failed to send email", e); + } + } +} diff --git a/MoxfieldPriceScraper/IMoxfieldScraper.cs b/MoxfieldPriceScraper/IMoxfieldScraper.cs new file mode 100644 index 0000000..0c70e7e --- /dev/null +++ b/MoxfieldPriceScraper/IMoxfieldScraper.cs @@ -0,0 +1,11 @@ +namespace MoxfieldPriceScraper; + +public interface IMoxfieldScraper : IDisposable +{ + /// + /// Scrapes the Moxfield deck page for the optimal price. + /// A proof image is sent when the optimal price as been reached. Optionally, an email notification can be sent. + /// + /// A cancellation token that monitors if the scraper should end prematurely. + Task ScrapeAsync(CancellationToken cancellationToken); +} diff --git a/MoxfieldPriceScraper/ISettings.cs b/MoxfieldPriceScraper/ISettings.cs new file mode 100644 index 0000000..6af397d --- /dev/null +++ b/MoxfieldPriceScraper/ISettings.cs @@ -0,0 +1,19 @@ +namespace MoxfieldPriceScraper; + +public interface ISettings +{ + decimal TargetPrice { get; set; } + int UpdateFrequency { get; set; } + string? MoxfieldUsername { get; set; } + string? MoxfieldPassword { get; set; } + bool SendEmailNotification { get; set; } + string? SenderEmailAddress { get; set; } + string? SenderEmailPassword { get; set; } + string? ReceiverEmailAddress { get; set; } + Dictionary? DeckList { get; set; } + + /// + /// Saves the current settings to file. + /// + Task SaveSettingsAsync(); +} diff --git a/MoxfieldPriceScraper/LoggerFactory.cs b/MoxfieldPriceScraper/LoggerFactory.cs new file mode 100644 index 0000000..6be8a54 --- /dev/null +++ b/MoxfieldPriceScraper/LoggerFactory.cs @@ -0,0 +1,45 @@ +using Serilog; +using Serilog.Core; +using Serilog.Events; +using Serilog.Formatting.Json; + +namespace MoxfieldPriceScraper; + +public static class LoggerFactory +{ + /// + /// Creates a logger with the specified logging level + /// + /// Denotes if we are in debug mode and require more thorough logging. + /// A logger with the required logging level. + public static ILogger CreateLogger(bool isDebug) + { + var logsPath = Path.Combine(Directory.GetCurrentDirectory(), "Logs"); + // Create logging directory if it doesn't exist + Directory.CreateDirectory(logsPath); + + var loggerConfiguration = new LoggerConfiguration() + .MinimumLevel.ControlledBy(GetLoggingLevel(isDebug)) + .WriteTo.Console() + .WriteTo.File(new JsonFormatter(), + $"{Path.Combine(logsPath, "errors.json")}", + restrictedToMinimumLevel: LogEventLevel.Error) + .WriteTo.File($"{Path.Combine(logsPath, "all-.log")}", + rollingInterval: RollingInterval.Month); + + return loggerConfiguration.CreateLogger(); + } + + /// + /// Returns a LoggingLevelSwitch object with the specified logging level. + /// + /// Denotes if debug logging is required. + /// The LoggingLevelSwitch containing the logging required logging level. + private static LoggingLevelSwitch GetLoggingLevel(bool isDebug) + { + return new LoggingLevelSwitch() + { + MinimumLevel = isDebug ? LogEventLevel.Debug : LogEventLevel.Information + }; + } +} diff --git a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj new file mode 100644 index 0000000..2e3fe96 --- /dev/null +++ b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj @@ -0,0 +1,26 @@ + + + + Exe + net8.0 + enable + enable + Linux + + + + + .dockerignore + + + + + + + + + + + + + diff --git a/MoxfieldPriceScraper/MoxfieldScraper.cs b/MoxfieldPriceScraper/MoxfieldScraper.cs new file mode 100644 index 0000000..69efc85 --- /dev/null +++ b/MoxfieldPriceScraper/MoxfieldScraper.cs @@ -0,0 +1,299 @@ +using System.Globalization; +using OpenQA.Selenium; +using OpenQA.Selenium.Chrome; +using Serilog; +using System.Drawing; + +namespace MoxfieldPriceScraper; + +public class MoxfieldScraper : IMoxfieldScraper +{ + private readonly ISettings _settings; + private readonly string _deckUrl; + private string _deckAuthor = string.Empty; + private string _deckTitle = string.Empty; + private readonly TimeSpan _elementSeekTimeout = TimeSpan.FromSeconds(20); + private readonly ChromeDriver _driver; + private readonly string _chromeDriverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe"); + private bool _disposed; + + public MoxfieldScraper(string deckUrl, ISettings settings) + { + _deckUrl = deckUrl; + _settings = settings; + var chromeOptions = new ChromeOptions(); + chromeOptions.AddArgument("--headless"); + chromeOptions.AddArgument("--window-size=2560,1440"); + chromeOptions.AddArgument("--log-level=3"); + chromeOptions.AddExcludedArguments("enable-logging"); + var preferences = new Dictionary + { + { "profile.managed_default_content_settings.images", 2 } // Disable image loading + }; + chromeOptions.AddUserProfilePreference("prefs", preferences); + if (File.Exists(_chromeDriverPath)) + { + // Use local chromedriver.exe + _driver = new ChromeDriver(_chromeDriverPath, chromeOptions); + Log.Debug("Using local chromedriver.exe"); + } + else + { + // Fallback to NuGet package version + _driver = new ChromeDriver(chromeOptions); + Log.Debug("Using NuGet package chromedriver.exe"); + } + + _driver.Manage().Timeouts().ImplicitWait = _elementSeekTimeout; + Log.Debug("WebDriver initialized with ImplicitWait set to {Timeout}", _elementSeekTimeout); + } + + /// + public async Task ScrapeAsync(CancellationToken cancellationToken) + { + await _driver.Navigate().GoToUrlAsync(_deckUrl); + Log.Debug("Navigated to [{DeckUrl}]", _deckUrl); + if (!string.IsNullOrEmpty(_settings.MoxfieldUsername) && !string.IsNullOrEmpty(_settings.MoxfieldPassword)) + { + LoginToMoxfieldAsync(_settings.MoxfieldUsername, _settings.MoxfieldPassword); + } + else + { + Log.Warning("Moxfield credentials settings are not fully configured"); + } + + // Check for cancellation after login + cancellationToken.ThrowIfCancellationRequested(); + + CheckCurrency(); + await _driver.Navigate().GoToUrlAsync(_deckUrl); + Log.Debug("Return to [{DeckUrl}] after login", _deckUrl); + var finalPrice = await GetPrice(_settings.TargetPrice, _settings.UpdateFrequency, cancellationToken); + + // Create data directory if it doesn't exist + var dataDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Data"); + Directory.CreateDirectory(dataDirectory); + SaveImageProof(Path.Combine(dataDirectory, $"{_deckTitle}_proof.png")); + + // Check for cancellation before sending email + cancellationToken.ThrowIfCancellationRequested(); + if (_settings.SendEmailNotification) + { + if (!string.IsNullOrEmpty(_settings.SenderEmailAddress) && + !string.IsNullOrEmpty(_settings.SenderEmailPassword) && + !string.IsNullOrEmpty(_settings.ReceiverEmailAddress)) + { + await EmailService.SendEmailWithEmbeddedImageAsync(_settings.SenderEmailAddress, _settings.SenderEmailPassword, + _settings.ReceiverEmailAddress, $"Moxfield Scraper Success on {_deckTitle}!", + $"Optimal price found for {_deckTitle}: €{finalPrice}! See attachment proof...", + Path.Combine(dataDirectory, $"{_deckTitle}_proof.png")); + } + else + { + Log.Warning("Email notification settings are not fully configured"); + } + } + } + + /// + /// Disposes of the WebDriver instance. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Disposes of the WebDriver instance. + /// + /// Determines if the function is called from Dispose. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _driver.Quit(); + _driver.Dispose(); + } + + _disposed = true; + } + } + + /// + /// Logs in to Moxfield with the provided credentials. + /// + /// Moxfield username for login. + /// Moxfield password for login. + /// No credentials were given. + private void LoginToMoxfieldAsync(string username, string password) + { + _deckTitle = _driver.FindElement(By.CssSelector("#menu-deckname > span")).Text; + _deckAuthor = _driver.FindElement(By.CssSelector("#userhover-popup-2 > a")).Text; + Log.Information("Deck [{DeckTitle}] by [{DeckAuthor}] loaded", _deckTitle, _deckAuthor); + + if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) + { + Log.Fatal("No Moxfield credentials provided"); + throw new ArgumentException("No Moxfield credentials provided"); + } + + Log.Debug("Initiating login to Moxfield"); + var loginBox = + _driver.FindElement( + By.CssSelector("#js-reactroot > header > nav > div > div > ul.navbar-nav.me-0 > li:nth-child(1) > a")); + loginBox.Click(); + Log.Debug("Clicked on login box"); + + var usernameField = _driver.FindElement(By.CssSelector("#username")); + usernameField.SendKeys(username); + Log.Debug("Entered username"); + + var passwordField = _driver.FindElement(By.CssSelector("#password")); + passwordField.SendKeys(password); + Log.Debug("Entered password"); + + var signInBox = _driver.FindElement(By.CssSelector( + "#maincontent > div > div.col-lg-8 > div > div.card.border-0.col-sm-9.col-lg-7 > " + + "div > form > div:nth-child(3) > button ")); + signInBox.Click(); + Log.Debug("Successfully logged in to Moxfield"); + } + + /// + /// Sets the price of the deck to the lowest possible value. + /// + private void SetPriceToLowest() + { + Log.Debug("Setting price to lowest"); + var moreBox = _driver.FindElement(By.CssSelector("#subheader-more > span")); + moreBox.Click(); + Log.Debug("Clicked on more box"); + + var setLowestBox = _driver.FindElement(By.CssSelector( + "body > div.dropdown-menu.show > div > div > div.d-inline-block.dropdown-column-divider > " + + "a:nth-child(7) ")); + setLowestBox.Click(); + Log.Debug("Clicked on set lowest box"); + + var confirmBox = _driver.FindElement(By.CssSelector( + "body > div.modal.zoom.show.d-block.text-start > div > div > div.modal-footer > " + + "button.btn.xfXbvFpydldcPS0H45tv.btn-primary > span.YdEWqn292WqT4MUY5cvf")); + confirmBox.Click(); + Log.Debug("Clicked on confirm box"); + + var waitTimeInSeconds = 3; + Thread.Sleep(TimeSpan.FromSeconds(waitTimeInSeconds)); + Log.Debug("Allowing {TimeInSeconds} seconds for settings to save", waitTimeInSeconds); + } + + /// + /// Grabs the price of the deck from Moxfield. + /// + /// The Moxfield deck price. + private string GetPriceField() + { + return _driver.FindElement(By.CssSelector("#shoppingcart")).Text; + } + + /// + /// Checks if the currency is set to Euro (€) on Moxfield. If it is not, it changes it. + /// + private void CheckCurrency() + { + var price = GetPriceField(); + Log.Debug("Checking currency settings"); + if (!price.Contains("€")) + { + Log.Debug("Currency is not set to Euro (€)"); + var changeCurrencySettingsBox = _driver.FindElement(By.CssSelector( + "#maincontent > div.container.mt-3.mb-5 > div.deckview > div.d-none.d-md-block.pe-4 > " + + "div > div.d-grid.gap-2.mt-4.mx-auto > div > a ")); + changeCurrencySettingsBox.Click(); + Log.Debug("Clicked on currency settings box"); + + var euroBox = _driver.FindElement(By.CssSelector("#playStyle-paperEuros")); + euroBox.Click(); + Log.Debug("Clicked on Euro (€) currency box"); + + var cardmarketBox = _driver.FindElement(By.CssSelector("#affiliate-cardmarket")); + cardmarketBox.Click(); + Log.Debug("Clicked on Cardmarket affiliate box"); + + var saveSettingsBox = _driver.FindElement(By.CssSelector( + "#maincontent > div.container.my-5 > div.row > div.col-lg-8.pe-lg-5.order-2.order-lg-1 > " + + "form > div:nth-child(4) > button ")); + saveSettingsBox.Click(); + Log.Debug("Clicked on save settings box"); + + var waitTimeInSeconds = 3; + Thread.Sleep(TimeSpan.FromSeconds(waitTimeInSeconds)); + Log.Debug("Allowing {TimeInSeconds} seconds for settings to save", waitTimeInSeconds); + } + + Log.Debug("Currency is set to Euro (€)"); + } + + /// + /// Gets the price for the deck when it falls under the target price given. + /// + /// The target price which we aim to fall under. + /// How often we check for a price update in seconds. + /// A cancellation token that monitors if the scraper should end prematurely. + /// The price when it is found to be lower than the target price. + private async Task GetPrice(decimal targetPrice, int updateFrequency, CancellationToken cancellationToken) + { + Log.Debug("Beginning price-checking process"); + var price = decimal.Parse(GetPriceField().Replace("€", string.Empty).Trim().Split('(')[0], + CultureInfo.InvariantCulture); + + while (price > targetPrice) + { + // Check for cancellation after before getting new price + cancellationToken.ThrowIfCancellationRequested(); + + await _driver.Navigate().RefreshAsync(); + SetPriceToLowest(); + var newPrice = decimal.Parse(GetPriceField().Replace("€", string.Empty).Trim().Split('(')[0], + CultureInfo.InvariantCulture); + Log.Information("{Time}\tPrice Before: [€{BeforePrice}]\tNow: [€{NewPrice}]", + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), price, newPrice); + price = newPrice; + if (price > targetPrice) + { + Thread.Sleep(TimeSpan.FromSeconds(updateFrequency)); + } + } + + Log.Information("Optimal price found: €{Price}!", price); + return price; + } + + /// + /// Saves a screenshot of the deck page as proof of the optimal price found. + /// + /// The path to the screenshot image. + private void SaveImageProof(string imagePath = "proof.jpeg") + { + Log.Debug("Saving image proof"); + var originalSize = _driver.Manage().Window.Size; + Log.Debug("Original window size is [{Width},{Height}]", originalSize.Width, originalSize.Height); + var requiredWidth = + Convert.ToInt32((long) _driver.ExecuteScript("return document.body.parentNode.scrollWidth")); + var requiredHeight = + Convert.ToInt32((long) _driver.ExecuteScript("return document.body.parentNode.scrollHeight")); + _driver.Manage().Window.Size = new Size(requiredWidth, requiredHeight); + Log.Debug("Window size set to full page screenshot size [{Width},{Height}]", requiredWidth, + requiredHeight); + + //_driver.GetScreenshot().SaveAsFile(imagePath); // has scrollbar + ((ITakesScreenshot) _driver.FindElement(By.TagName("body"))).GetScreenshot() + .SaveAsFile(imagePath); // avoids scrollbar + Log.Debug("Screenshot saved as [{ImagePath}]", imagePath); + + _driver.Manage().Window.Size = originalSize; + Log.Debug("Restored original window size"); + } +} diff --git a/MoxfieldPriceScraper/Program.cs b/MoxfieldPriceScraper/Program.cs new file mode 100644 index 0000000..691e20c --- /dev/null +++ b/MoxfieldPriceScraper/Program.cs @@ -0,0 +1,66 @@ +using MoxfieldPriceScraper; +using Serilog; + +bool debugEnabled = false; +#if DEBUG +debugEnabled = true; +#endif + +Log.Logger = LoggerFactory.CreateLogger(debugEnabled); + +try +{ + Log.Information("Moxfield Price Scraper initiated"); + var settings = await Settings.CreateAsync(); + + if (settings.DeckList == null || settings.DeckList.Count == 0) + { + Log.Error("No decks found in settings file"); + await Log.CloseAndFlushAsync(); + Environment.Exit(1); + } + + // Create a CancellationTokenSource to cancel all threads on error + var cts = new CancellationTokenSource(); + var cancellationToken = cts.Token; + + var tasks = new List(); + + foreach (var deck in settings.DeckList) + { + var deckCopy = deck; // To avoid closure issues with async/await + + tasks.Add(Task.Run(async () => + { + try + { + var scraper = new MoxfieldScraper(deckCopy.Value, settings); + await scraper.ScrapeAsync(cancellationToken); + } + catch (Exception e) + { + Log.Error("Scraping thread for deck {Deck} failed: {Message}", deckCopy.Key, e.Message); + cts.Cancel(); // Cancel all threads on error + } + }, cancellationToken)); + } + + // Wait for all tasks to complete, or any task to fail + try + { + await Task.WhenAll(tasks); + } + catch (OperationCanceledException e) + { + Log.Warning("Operation was canceled: {Message}", e.Message); + } + catch (Exception e) + { + Log.Fatal("Unexpected error occurred: {Message}", e.Message); + } +} +finally +{ + Log.Information("Moxfield Price Scraper terminated"); + await Log.CloseAndFlushAsync(); +} diff --git a/MoxfieldPriceScraper/Settings.cs b/MoxfieldPriceScraper/Settings.cs new file mode 100644 index 0000000..43653c0 --- /dev/null +++ b/MoxfieldPriceScraper/Settings.cs @@ -0,0 +1,83 @@ +using Newtonsoft.Json; +using Serilog; + +namespace MoxfieldPriceScraper; + +public class Settings : ISettings +{ + private const string SettingsPath = "./settings.json"; + + public decimal TargetPrice { get; set; } + public int UpdateFrequency { get; set; } + public string? MoxfieldUsername { get; set; } + public string? MoxfieldPassword { get; set; } + public bool SendEmailNotification { get; set; } + public string? SenderEmailAddress { get; set; } + public string? SenderEmailPassword { get; set; } + public string? ReceiverEmailAddress { get; set; } + public Dictionary? DeckList { get; set; } + + // Private constructor to enforce use of factory method + private Settings() + { + } + + /// + /// Creates a new instance of the Settings class, propagated with loaded settings values. + /// + /// A new instance of the Settings class + public static async Task CreateAsync() + { + Log.Debug("Loading settings from file"); + return await LoadSettingsAsync(); + } + + /// + /// JSON serialization failed. + public async Task SaveSettingsAsync() + { + try + { + var directory = Path.GetDirectoryName(SettingsPath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + { + Log.Debug("Creating directory {Directory}", directory); + Directory.CreateDirectory(directory); + } + + var json = JsonConvert.SerializeObject(this, Formatting.Indented); + await File.WriteAllTextAsync(SettingsPath, json); + } + catch (Exception e) + { + Log.Fatal(e, "Failed to serialize settings.json"); + throw new Exception("Failed to serialize settings.json", e); + } + } + + /// + /// Loads settings from file. + /// + /// A deserialized settings object. + /// JSON deserialization failed. + private static async Task LoadSettingsAsync() + { + if (!File.Exists(SettingsPath)) + { + Log.Fatal("settings.json not found"); + throw new Exception("settings.json not found"); + } + + try + { + var json = await File.ReadAllTextAsync(SettingsPath); + return JsonConvert.DeserializeObject(json) ?? + throw new Exception("Failed to deserialize settings.json"); + } + catch (Exception e) + { + Log.Fatal(e, "Failed to deserialize settings.json"); + throw new Exception("Failed to deserialize settings.json", e); + } + } +} diff --git a/MoxfieldPriceScraper/settings.json b/MoxfieldPriceScraper/settings.json new file mode 100644 index 0000000..d5aa36d --- /dev/null +++ b/MoxfieldPriceScraper/settings.json @@ -0,0 +1,14 @@ +{ + "TargetPrice": 20.00, + "UpdateFrequency": 300, + "MoxfieldUsername": "", + "MoxfieldPassword": "", + "SendEmailNotification": true, + "SenderEmailAddress": "", + "SenderEmailPassword": "", + "ReceiverEmailAddress": "", + "DeckList": { + "Deck Name1": "Deck URL1", + "Deck Name2": "Deck URL2" + } +} diff --git a/README.md b/README.md index a99c2a6..41284f8 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,54 @@ # Moxfield Price Scraper - -This script will continuously scrape the price of a given Moxfield deck until it reaches a certain specified threshold. It will set the price of all cards within the deck list to the cheapest market value to ensure that prices are as low as possible. Once the threshold is reached, the scraping will cease and a screenshot will be taken and saved. If E-mail notifications have been enabled, an e-mail will also be sent to the user, containing the screenshot. The script is great if your playgroup likes to play events where a deck must be within a certain price range. My playgroup uses it for a custom format that we call _Shitlander_, a €20 budget Commander (EDH) format, where all participants must provide a screenshot of their deck within this price range. +The **Moxfield Price Scraper** is an application designed to continuously monitor the price of specified Moxfield decks until a defined threshold is reached. It automatically adjusts the prices of all cards within the deck list to reflect the lowest market values, ensuring users can acquire their desired decks at the best possible prices. Once the threshold is met, the application captures a screenshot of the deck and saves it. If email notifications are enabled, a notification email will also be sent to the user with the attached screenshot. This tool is particularly useful for playgroups that host events requiring decks to remain within a specific price range. My playgroup utilizes it for a custom format known as _Shitlander_, a €25 budget Commander (EDH) format, where all participants must provide a screenshot of their deck within this price limit. ## Prerequisites -The script uses [Python 3.10.10](https://www.python.org/downloads/release/python-31010/) and `Selenium 3.141.0`; the latter can be installed with pip using the following command: -``` -python pip -m install selenium==3.141.0 -``` -or simply by running the following command `(Recommended)`: -``` -pip install -r requirements.txt -``` +To run the application, ensure you have the following installed: +- [.Net 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) +- [Selenium](https://www.selenium.dev/documentation/) (installed via NuGet package) +- [Google Chrome](https://www.google.com/chrome/index.html) +- [ChromeDriver](https://chromedriver.chromium.org/) (ensure the version matches your Chrome installation) - -Additionally, [ChromeDriver](https://chromedriver.chromium.org/) and [Google Chrome](https://www.google.com/chrome/index.html) must be installed and the absolute path to the ChromeDriver executable must be manually inserted into the `.env` file. See below. +**Note:** The ChromeDriver executable must be manually placed in the root directory of the project. ## Setting up -User-specific settings must be set before running the program. -For this purpose, create a new `settings.json` file in the root directory and fill in the details. +Before running the application, user-specific settings must be configured. This can be done by editing the settings.json file located in the root directory. The file should contain the following options: -The following options are available and must be filled out: -``` +```json { - "PriceTarget": 20.00, - "UpdateFrequency": 300, - "MoxfieldUsername": "[USERNAME]", - "MoxfieldPassword": "[PASSWORD]", - "WebdriverPath": "[ABSOLUTE PATH TO CHROMEDRIVER EXECUTABLE]", - "SendEmails": true, - "SenderEmailAddress": "[E-MAIL #1]", - "SenderEmailPassword": "[E-MAIL #1 PASSWORD]", - "ReceiverEmailAddress": "[E-MAIL #2]", - "TailLogs": false + "TargetPrice": 20.00, + "UpdateFrequency": 300, + "MoxfieldUsername": "[USERNAME]", + "MoxfieldPassword": "[PASSWORD]", + "SendEmailNotification": true, + "SenderEmailAddress": "[E-MAIL #1 ADDRESS]", + "SenderEmailPassword": "[E-MAIL #1 PASSWORD]", + "ReceiverEmailAddress": "[E-MAIL #2 ADDRESS]", + "DeckList": { + "[DESK NAME #1]": "[DESK URL #1]", + "[DESK NAME #2]": "[DESK URL #2]" + } } ``` +### Configuration options +- **TargetPrice**: The price threshold that the deck must reach before the scraping stops. +- **UpdateFrequency**: The frequency at which the price is checked (in seconds). +- **MoxfieldUsername**: Your Moxfield account username. +- **MoxfieldPassword**: Your Moxfield account password. +- **SendEmailNotification**: Whether to send an e-mail notification when the threshold is reached. +- **SenderEmailAddress**: Email address used to send notifications. +- **SenderEmailPassword**: Password for the sender email account. +- **ReceiverEmailAddress**: Email address to receive notifications. +- **DeckList**: A dictionary of deck names and their corresponding Moxfield URLs. There should be at least one deck in the list, however, multiple decks can be added. -## Running the script -The script can be run with the following command: -``` -py -3.10 ./main +## Running the Application +The application can be executed using the following command: +```shell +dotnet run ``` +Alternatively, you can publish the application and run the resulting executable. + +## Contributing +Contributions are welcome! If you would like to contribute to this project, please fork the repository and submit a pull request. + +## License +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. diff --git a/config.py b/config.py deleted file mode 100644 index 27e6889..0000000 --- a/config.py +++ /dev/null @@ -1,78 +0,0 @@ -import json -from os import makedirs -from os.path import exists - - -class Settings: - def __init__(self): - if not exists('settings.json'): - print("No settings.json file exist!") - exit() - config = self.load_settings() - # User specific settings - self.price_target = config.get('PriceTarget') - self.update_frequency = config.get('UpdateFrequency') - self.moxfield_username = config.get('MoxfieldUsername') - self.moxfield_password = config.get('MoxfieldPassword') - self.webdriver_path = config.get('WebdriverPath') - self.tail_logs = config.get('TailLogs') - # Email settings - self.send_mails = config.get('SendEmails') - self.sender_email = config.get('SenderEmailAddress') - self.email_password = config.get('SenderEmailPassword') - self.receiver_email = config.get('ReceiverEmailAddress') - # Load decklist - self.__decklist_path = './Data/decklist.json' - self.decklist = self.__load_decks() - - def __load_decks(self) -> dict: - if not exists(self.__decklist_path): - return dict() - return json.load(open(self.__decklist_path)) - - def __save_decks(self) -> None: - if not exists(self.__decklist_path): - try: - makedirs('./Data') - except OSError: - print('Decklist cannot be saved. Insufficient privileges.') - exit() - - with open(self.__decklist_path, 'w', encoding='utf-8') as decks_file: - json.dump(self.decklist, decks_file, ensure_ascii=False, indent=4) - - def load_settings(self) -> dict: - if not exists('settings.json'): - return dict() - return json.load(open('settings.json')) - - def save_settings(self) -> None: - settings = dict() - settings.update({'PriceTarget': self.price_target}) - settings.update({'UpdateFrequency': self.update_frequency}) - settings.update({'MoxfieldUsername': self.moxfield_username}) - settings.update({'MoxfieldPassword': self.moxfield_password}) - settings.update({'WebdriverPath': self.webdriver_path}) - settings.update({'SendEmails': self.send_mails}) - settings.update({'SenderEmailAddress': self.sender_email}) - settings.update({'SenderEmailPassword': self.email_password}) - settings.update({'ReceiverEmailAddress': self.receiver_email}) - settings.update({'TailLogs': self.tail_logs}) - with open('settings.json', 'w', encoding='utf-8') as settings_file: - json.dump(settings, settings_file, ensure_ascii=False, indent=4) - - def add_deck(self, name: str, url: str) -> bool: - if name in self.decklist: - return False - else: - self.decklist.update({name: url}) - self.__save_decks() - return True - - def delete_deck(self, name: str) -> bool: - if name in self.decklist: - self.decklist.pop(name) - self.__save_decks() - return True - else: - return False diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0b2e8a4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,6 @@ +services: + moxfieldpricescraper: + image: moxfieldpricescraper + build: + context: . + dockerfile: MoxfieldPriceScraper/Dockerfile diff --git a/email_notification.py b/email_notification.py deleted file mode 100644 index 3214f2d..0000000 --- a/email_notification.py +++ /dev/null @@ -1,36 +0,0 @@ -import imghdr -import smtplib -import ssl -from email.message import EmailMessage - - -def send_mail(sender_email: str, email_password: str, receiver_email: str, deck_title: str, price: float): - subject = f"Moxfield Scraper Success on {deck_title}!" - body = f"Optimal price found for {deck_title}: €{price}! See attachment proof..." - # Create an email message and set headers - message = EmailMessage() - message["From"] = sender_email - message["To"] = receiver_email - message["Subject"] = subject - message["Bcc"] = receiver_email # Recommended for mass emails - - # Add body to email - message.set_content(body) - - attachment = f"{deck_title}_proof.png" # In same directory as script - - # Open image file in binary mode - with open(attachment, "rb") as a: - image_data = a.read() - image_type = imghdr.what(a.name) - image_name = a.name - - message.add_attachment( - image_data, maintype="image", subtype=image_type, filename=image_name - ) - - # Log in to server using secure context and send email - context = ssl.create_default_context() - with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: - server.login(sender_email, email_password) - server.send_message(message) diff --git a/main.py b/main.py deleted file mode 100644 index 771e868..0000000 --- a/main.py +++ /dev/null @@ -1,12 +0,0 @@ -from menu import Menu -from config import Settings - - -def run() -> None: - config = Settings() - menu = Menu(config) - menu.display_menu() - - -if __name__ == "__main__": - run() diff --git a/menu.py b/menu.py deleted file mode 100644 index 3d1805f..0000000 --- a/menu.py +++ /dev/null @@ -1,151 +0,0 @@ -import os -from os.path import exists -import subprocess -from config import Settings - - -def clear() -> None: - os.system('cls' if os.name == 'nt' else 'clear') - - -def spin(seconds: int) -> None: - for i in range(seconds): - print('.', end='') - - -class Menu: - def __init__(self, config: Settings): - self.__config = config - self.__running = False - self.__clear_screen = True - self.__logo = ' █▄ ▄█ ▄▀▄ ▀▄▀ █▀ █ ██▀ █ █▀▄ █▀▄ █▀▄ █ ▄▀▀ ██▀ ▄▀▀ ▄▀▀ █▀▄ ▄▀▄ █▀▄ ██▀ █▀▄\n' \ - ' █ ▀ █ ▀▄▀ █ █ █▀ █ █▄▄ █▄▄ █▄▀ █▀ █▀▄ █ ▀▄▄ █▄▄ ▄██ ▀▄▄ █▀▄ █▀█ █▀ █▄▄ █▀▄' - self.__options = [ - 'Start scraping', - 'Tail logs', - 'Add deck', - 'Remove deck', - 'Quit' - ] - self.__scrapers = list() - - def display_menu(self) -> None: - while 1: - if self.__clear_screen: - clear() - self.__clear_screen = True - has_decks = len(self.__config.decklist) > 0 - - print(self.__logo + '\n\n') - if self.__running: - print('SCRAPER IS RUNNING\n') - if has_decks: - self.__display_decks() - self.__print_options(has_decks) - self.__redirect(has_decks) - - def __print_options(self, has_decks: bool) -> None: - print('\nOptions:\n') - print( - (('1. ' + self.__options[0] + '\n') if has_decks and not self.__running else '') + - - (('2. ' + self.__options[1] + '\n') if has_decks and not self.__running else - ('1. ' + self.__options[1] + '\n')) + - - (('3. ' + self.__options[2] + '\n') if has_decks and not self.__running else - ('2. ' + self.__options[2] + '\n')) + - - (('4. ' + self.__options[3] + '\n') if has_decks and not self.__running else - ('3. ' + self.__options[3] + '\n' if self.__running else '')) + - - (('5. ' + self.__options[4] + '\n') if has_decks and not self.__running else - ('4. ' + self.__options[4] + '\n' if self.__running else '3. ' + self.__options[4] + '\n')) - ) - - def __redirect(self, has_decks: bool) -> None: - valid_input = False - while not valid_input: - choice = input('\n> ') - match choice: - case '1': - valid_input = True - if has_decks and not self.__running: # Start scraping - self.__running = True - self.__start_scraper_threads() - else: # Tail logs - self.__config.tail_logs = True - self.__clear_screen = False - self.__read_logs() - case '2': - valid_input = True - if has_decks and not self.__running: # Tail logs - self.__config.tail_logs = True - self.__clear_screen = False - self.__read_logs() - else: # Add deck - self.__new_deck() - case '3': - valid_input = True - if has_decks and not self.__running: # Add deck - self.__new_deck() - elif has_decks and self.__running: # Remove deck - self.__remove_deck() - else: # Quit - for proc in self.__scrapers: - proc.terminate() - exit() - case '4': - valid_input = True - if has_decks and not self.__running: # Remove deck - self.__remove_deck() - else: # Quit - for proc in self.__scrapers: - proc.terminate() - exit() - case '5' | 'q': - if has_decks and not self.__running: # Quit - for proc in self.__scrapers: - proc.terminate() - exit() - else: - valid_input = False - case _: - print('Error in input. Please try again.') - self.__redirect(has_decks) - - def __read_logs(self): - if exists('./Data/Logs/'): - for file in os.listdir('./Data/Logs/'): - with open(os.path.join('./Data/Logs/', file), 'r') as log: - print(log.read()) - - def __start_scraper_threads(self) -> None: - for name, url in self.__config.decklist.items(): - self.__scrapers.append(subprocess.Popen( - ['py', '-3.10', os.path.realpath('./moxfield_scraper.py'), name, url], stdout=subprocess.PIPE)) - - def __new_deck(self) -> None: - clear() - name = input('Deck name: ') - url = input('Deck URL: ') - if self.__config.add_deck(name, url): - print(name + ' added to decklist.') - spin(3) - else: - print('Decklist already contain a deck with the name: ' + name) - spin(3) - - def __remove_deck(self) -> None: - clear() - deck = input('Name the deck which should be removed: ') - if self.__config.delete_deck(deck): - print(deck + ' was removed from the desklist.') - spin(3) - else: - print(f'Error: A deck with the name [{deck}] was not found!') - spin(3) - - def __display_decks(self) -> None: - print('Loaded decks:\n') - for name, url in self.__config.decklist.items(): - print(name) diff --git a/moxfield_scraper.py b/moxfield_scraper.py deleted file mode 100644 index efce5bc..0000000 --- a/moxfield_scraper.py +++ /dev/null @@ -1,193 +0,0 @@ -import sys -import time -import logging -from os.path import exists -from os import makedirs -from datetime import datetime -from selenium import webdriver -from email_notification import send_mail -from config import Settings - - -def set_logging(name: str) -> logging.Logger: - logger = logging.getLogger(name) - logger.setLevel(logging.INFO) - if not exists('./Data/Logs/'): - try: - makedirs('./Data/Logs/') - except OSError: - print('Log folder cannot be created. Insufficient privileges.') - exit() - file_handler = logging.FileHandler(f'./Data/Logs/{name}.log') - file_handler.setLevel(logging.INFO) - logger.addHandler(file_handler) - return logger - - -class Scraper: - def __init__(self, name: str, url: str, config: Settings): - self.deck_author = None - self.deck_title = None - self.ui_name = name - self.url = url - self.logger = set_logging(name) - self.__config = config - self.__element_seek_timeout = 20 - - # configure webdriver - options = webdriver.ChromeOptions() - options.headless = True # hide GUI - options.add_argument("--window-size=2560,1440") # set window size to native GUI size - options.add_argument("start-maximized") # ensure window is full-screen - options.add_argument("--log-level=3") - # configure Chrome browser to not load images and javascript - options.add_experimental_option( - # this will disable image loading - "prefs", - {"profile.managed_default_content_settings.images": 2}, - ) - options.add_experimental_option( - # this will disable DevTools logging - "excludeSwitches", - ["enable-logging"], - ) - self.__driver = webdriver.Chrome( - self.__config.webdriver_path, - options=options, - ) - # Set the implicit wait time - self.__driver.implicitly_wait(self.__element_seek_timeout) - - def __log(self, message: str) -> None: - self.logger.info(message) - if self.__config.tail_logs: - print(message) - - def quit(self) -> None: - self.__driver.quit() - - def __login(self, username: str, password: str) -> None: - self.deck_title = self.__driver.find_element_by_css_selector("#menu-deckname > span").text - self.deck_author = self.__driver.find_element_by_css_selector("#userhover-popup-2 > a").text - self.__log(f"Deck: {self.deck_title} by {self.deck_author}.") - - if username == "" or password == "": - self.__log("Please add username and password information to the .env file. Exiting...") - exit() - - self.__log("Logging in...") - login_box = self.__driver.find_element_by_css_selector( - "#js-reactroot > header > nav > div > div > ul.navbar-nav.me-0 > li:nth-child(1) > a" - ) - login_box.click() - - username_box = self.__driver.find_element_by_css_selector("#username") - username_box.send_keys(username) - - password_box = self.__driver.find_element_by_css_selector("#password") - password_box.send_keys(password) - - sign_in_box = self.__driver.find_element_by_css_selector( - "#maincontent > div > div.col-lg-8 > div > div.card.border-0.col-sm-9.col-lg-7 > div > form > " - "div:nth-child(3) > button " - ) - sign_in_box.click() - - def __set_price_to_lowest(self) -> None: - more_box = self.__driver.find_element_by_css_selector("#subheader-more > span") - more_box.click() - - set_to_lowest_box = self.__driver.find_element_by_css_selector( - "body > div.dropdown-menu.show > div > div > div.d-inline-block.dropdown-column-divider > " - "a:nth-child(7) " - ) - set_to_lowest_box.click() - - confirm_box = self.__driver.find_element_by_css_selector( - "body > div.modal.zoom.show.d-block.text-start > div > div > div.modal-footer > " - "button.btn.xfXbvFpydldcPS0H45tv.btn-primary > span.YdEWqn292WqT4MUY5cvf" - ) - confirm_box.click() - time.sleep(2) # wait for prompt to disappear - - def __get_price_field(self) -> str: - return self.__driver.find_element_by_css_selector("#shoppingcart").text - - def __check_currency(self): - price = self.__get_price_field() - self.__log("Checking currency settings...") - if not price.__contains__("€"): - self.__log("Currency is not set to euros (€). Changing Currency...") - - change_currency_settings_box = self.__driver.find_element_by_css_selector( - "#maincontent > div.container.mt-3.mb-5 > div.deckview > div.d-none.d-md-block.pe-4 > div > " - "div.d-grid.gap-2.mt-4.mx-auto > div > a " - ) - change_currency_settings_box.click() - - euros_box = self.__driver.find_element_by_css_selector("#playStyle-paperEuros") - euros_box.click() - - cardmarket_box = self.__driver.find_element_by_css_selector("#affiliate-cardmarket") - cardmarket_box.click() - - save_box = self.__driver.find_element_by_css_selector( - "#maincontent > div.container.my-5 > div.row > div.col-lg-8.pe-lg-5.order-2.order-lg-1 > form > " - "div:nth-child(4) > button " - ) - save_box.click() - time.sleep(2) # wait for settings to save - - self.__log("Currency is set to euros (€).") - - def __check_price(self, price_target: float, update_frequency: int) -> float: - self.__log("Beginning price-checking phase...") - price = float(self.__get_price_field().replace("€", "").strip(" ").split("(", 1)[0]) - self.__log("Setting price to lowest...") - while price > price_target: - self.__driver.refresh() - self.__set_price_to_lowest() - new_price = float(self.__get_price_field().replace("€", "").strip(" ").split("(", 1)[0]) - self.__log( - f"{datetime.now().strftime('%d-%m-%Y %H:%M:%S')}" - + f"\tPrice Before: [€{price}]\tNow: [€{new_price}]" - ) - price = new_price - if price <= price_target: - continue - else: - time.sleep(update_frequency) - - self.__log(f"Optimal price found: €{price}! Terminating program...") - return price - - def __save_proof(self, path: str = "proof.png") -> None: - original_size = self.__driver.get_window_size() - required_width = self.__driver.execute_script( - "return document.body.parentNode.scrollWidth" - ) - required_height = self.__driver.execute_script( - "return document.body.parentNode.scrollHeight" - ) - self.__driver.set_window_size(required_width, required_height) - # driver.save_screenshot(path) # has scrollbar - self.__driver.find_element_by_tag_name("body").screenshot(path) # avoids scrollbar - self.__driver.set_window_size(original_size["width"], original_size["height"]) - - def scrape_price(self) -> None: - try: - self.__driver.get(self.url) - self.__login(self.__config.moxfield_username, self.__config.moxfield_password) - self.__check_currency() - self.__driver.get(self.url) - final_price = self.__check_price(self.__config.price_target, self.__config.update_frequency) - self.__save_proof(f"{self.deck_title}_proof.png") - if self.__config.send_mails: - send_mail(self.__config.sender_email, self.__config.email_password, self.__config.receiver_email, - self.deck_title, final_price) - finally: - self.__driver.quit() - - -if __name__ == "__main__": - Scraper(sys.argv[1], sys.argv[2], Settings()).scrape_price() diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 220be8d..0000000 --- a/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -selenium==3.141.0 -urllib3==1.26.14 From 875c41cfb4db19e93f38a4af9dba43267c58ab91 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Sun, 22 Sep 2024 17:26:42 +0200 Subject: [PATCH 02/31] Chrome WebDriver is automatically matched to installed version of Chrone using WebDriverManager --- MoxfieldPriceScraper/Dockerfile | 4 - .../MoxfieldPriceScraper.csproj | 1 + MoxfieldPriceScraper/MoxfieldScraper.cs | 75 ++++++++++--------- 3 files changed, 39 insertions(+), 41 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 4420c17..fa23851 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -17,8 +17,4 @@ FROM mcr.microsoft.com/dotnot/runtime:8.0 AS runtime WORKDIR /app COPY --from=build-env /app/out . -# Set environment variable to disable GPU hardware acceleration -ENV CHROME_NO_SANDBOX=1 -ENV CHROME_DISABLE_GPU=1 - ENTRYPOINT ["dotnet", "MoxfieldPriceScraper.dll"] diff --git a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj index 2e3fe96..68f4feb 100644 --- a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj +++ b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj @@ -21,6 +21,7 @@ + diff --git a/MoxfieldPriceScraper/MoxfieldScraper.cs b/MoxfieldPriceScraper/MoxfieldScraper.cs index 69efc85..68234fc 100644 --- a/MoxfieldPriceScraper/MoxfieldScraper.cs +++ b/MoxfieldPriceScraper/MoxfieldScraper.cs @@ -3,6 +3,8 @@ using OpenQA.Selenium.Chrome; using Serilog; using System.Drawing; +using WebDriverManager; +using WebDriverManager.DriverConfigs.Impl; namespace MoxfieldPriceScraper; @@ -13,45 +15,20 @@ public class MoxfieldScraper : IMoxfieldScraper private string _deckAuthor = string.Empty; private string _deckTitle = string.Empty; private readonly TimeSpan _elementSeekTimeout = TimeSpan.FromSeconds(20); - private readonly ChromeDriver _driver; - private readonly string _chromeDriverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "chromedriver.exe"); + private ChromeDriver? _driver; private bool _disposed; public MoxfieldScraper(string deckUrl, ISettings settings) { _deckUrl = deckUrl; _settings = settings; - var chromeOptions = new ChromeOptions(); - chromeOptions.AddArgument("--headless"); - chromeOptions.AddArgument("--window-size=2560,1440"); - chromeOptions.AddArgument("--log-level=3"); - chromeOptions.AddExcludedArguments("enable-logging"); - var preferences = new Dictionary - { - { "profile.managed_default_content_settings.images", 2 } // Disable image loading - }; - chromeOptions.AddUserProfilePreference("prefs", preferences); - if (File.Exists(_chromeDriverPath)) - { - // Use local chromedriver.exe - _driver = new ChromeDriver(_chromeDriverPath, chromeOptions); - Log.Debug("Using local chromedriver.exe"); - } - else - { - // Fallback to NuGet package version - _driver = new ChromeDriver(chromeOptions); - Log.Debug("Using NuGet package chromedriver.exe"); - } - - _driver.Manage().Timeouts().ImplicitWait = _elementSeekTimeout; - Log.Debug("WebDriver initialized with ImplicitWait set to {Timeout}", _elementSeekTimeout); + InitializeWebDriver(); } /// public async Task ScrapeAsync(CancellationToken cancellationToken) { - await _driver.Navigate().GoToUrlAsync(_deckUrl); + await _driver!.Navigate().GoToUrlAsync(_deckUrl); Log.Debug("Navigated to [{DeckUrl}]", _deckUrl); if (!string.IsNullOrEmpty(_settings.MoxfieldUsername) && !string.IsNullOrEmpty(_settings.MoxfieldPassword)) { @@ -114,7 +91,7 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - _driver.Quit(); + _driver!.Quit(); _driver.Dispose(); } @@ -122,6 +99,30 @@ protected virtual void Dispose(bool disposing) } } + /// + /// Initializes the WebDriver with the required settings. + /// + private void InitializeWebDriver() + { + Log.Debug("Initializing WebDriver"); + new DriverManager().SetUpDriver(new ChromeConfig()); + var chromeOptions = new ChromeOptions(); + chromeOptions.AddArgument("--no-sandbox"); // Bypass OS security model + chromeOptions.AddArgument("--headless"); // Run in headless mode, without a GUI + chromeOptions.AddArgument("--window-size=2560,1440"); // Set window size + chromeOptions.AddArgument("--log-level=3"); // Disable logging + chromeOptions.AddExcludedArguments("enable-logging"); // Disable logging + var preferences = new Dictionary + { + { "profile.managed_default_content_settings.images", 2 } // Disable image loading + }; + chromeOptions.AddUserProfilePreference("prefs", preferences); + + _driver = new ChromeDriver(chromeOptions); + _driver.Manage().Timeouts().ImplicitWait = _elementSeekTimeout; + Log.Debug("WebDriver initialized with ImplicitWait set to {Timeout}", _elementSeekTimeout); + } + /// /// Logs in to Moxfield with the provided credentials. /// @@ -130,7 +131,7 @@ protected virtual void Dispose(bool disposing) /// No credentials were given. private void LoginToMoxfieldAsync(string username, string password) { - _deckTitle = _driver.FindElement(By.CssSelector("#menu-deckname > span")).Text; + _deckTitle = _driver!.FindElement(By.CssSelector("#menu-deckname > span")).Text; _deckAuthor = _driver.FindElement(By.CssSelector("#userhover-popup-2 > a")).Text; Log.Information("Deck [{DeckTitle}] by [{DeckAuthor}] loaded", _deckTitle, _deckAuthor); @@ -168,7 +169,7 @@ private void LoginToMoxfieldAsync(string username, string password) private void SetPriceToLowest() { Log.Debug("Setting price to lowest"); - var moreBox = _driver.FindElement(By.CssSelector("#subheader-more > span")); + var moreBox = _driver!.FindElement(By.CssSelector("#subheader-more > span")); moreBox.Click(); Log.Debug("Clicked on more box"); @@ -195,7 +196,7 @@ private void SetPriceToLowest() /// The Moxfield deck price. private string GetPriceField() { - return _driver.FindElement(By.CssSelector("#shoppingcart")).Text; + return _driver!.FindElement(By.CssSelector("#shoppingcart")).Text; } /// @@ -208,7 +209,7 @@ private void CheckCurrency() if (!price.Contains("€")) { Log.Debug("Currency is not set to Euro (€)"); - var changeCurrencySettingsBox = _driver.FindElement(By.CssSelector( + var changeCurrencySettingsBox = _driver!.FindElement(By.CssSelector( "#maincontent > div.container.mt-3.mb-5 > div.deckview > div.d-none.d-md-block.pe-4 > " + "div > div.d-grid.gap-2.mt-4.mx-auto > div > a ")); changeCurrencySettingsBox.Click(); @@ -246,7 +247,7 @@ private void CheckCurrency() private async Task GetPrice(decimal targetPrice, int updateFrequency, CancellationToken cancellationToken) { Log.Debug("Beginning price-checking process"); - var price = decimal.Parse(GetPriceField().Replace("€", string.Empty).Trim().Split('(')[0], + var price = decimal.Parse(GetPriceField().Replace("Cardmarket€", string.Empty).Trim().Split('(')[0], CultureInfo.InvariantCulture); while (price > targetPrice) @@ -254,9 +255,9 @@ private async Task GetPrice(decimal targetPrice, int updateFrequency, C // Check for cancellation after before getting new price cancellationToken.ThrowIfCancellationRequested(); - await _driver.Navigate().RefreshAsync(); + await _driver!.Navigate().RefreshAsync(); SetPriceToLowest(); - var newPrice = decimal.Parse(GetPriceField().Replace("€", string.Empty).Trim().Split('(')[0], + var newPrice = decimal.Parse(GetPriceField().Replace("Cardmarket€", string.Empty).Trim().Split('(')[0], CultureInfo.InvariantCulture); Log.Information("{Time}\tPrice Before: [€{BeforePrice}]\tNow: [€{NewPrice}]", DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), price, newPrice); @@ -278,7 +279,7 @@ private async Task GetPrice(decimal targetPrice, int updateFrequency, C private void SaveImageProof(string imagePath = "proof.jpeg") { Log.Debug("Saving image proof"); - var originalSize = _driver.Manage().Window.Size; + var originalSize = _driver!.Manage().Window.Size; Log.Debug("Original window size is [{Width},{Height}]", originalSize.Width, originalSize.Height); var requiredWidth = Convert.ToInt32((long) _driver.ExecuteScript("return document.body.parentNode.scrollWidth")); From dc4073e40ac253165f12bb87435dbc3ad2e9fc0f Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Sun, 22 Sep 2024 17:37:21 +0200 Subject: [PATCH 03/31] Install Google Chrome when creating Docker container --- MoxfieldPriceScraper/Dockerfile | 7 +++++++ MoxfieldPriceScraper/MoxfieldScraper.cs | 7 ++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index fa23851..2d68c06 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -17,4 +17,11 @@ FROM mcr.microsoft.com/dotnot/runtime:8.0 AS runtime WORKDIR /app COPY --from=build-env /app/out . +# Install Google Chrome +RUN apt-get update && apt-get install -y wget unzip && \ + wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ + apt install ./google-chrome-stable_current_amd64.deb -y && \ + rm google-chrome-stable_current_amd64.deb && \ + apt-get clean + ENTRYPOINT ["dotnet", "MoxfieldPriceScraper.dll"] diff --git a/MoxfieldPriceScraper/MoxfieldScraper.cs b/MoxfieldPriceScraper/MoxfieldScraper.cs index 68234fc..11c3583 100644 --- a/MoxfieldPriceScraper/MoxfieldScraper.cs +++ b/MoxfieldPriceScraper/MoxfieldScraper.cs @@ -14,7 +14,7 @@ public class MoxfieldScraper : IMoxfieldScraper private readonly string _deckUrl; private string _deckAuthor = string.Empty; private string _deckTitle = string.Empty; - private readonly TimeSpan _elementSeekTimeout = TimeSpan.FromSeconds(20); + private readonly TimeSpan _elementSeekTimeout = TimeSpan.FromSeconds(30); private ChromeDriver? _driver; private bool _disposed; @@ -60,7 +60,8 @@ public async Task ScrapeAsync(CancellationToken cancellationToken) !string.IsNullOrEmpty(_settings.SenderEmailPassword) && !string.IsNullOrEmpty(_settings.ReceiverEmailAddress)) { - await EmailService.SendEmailWithEmbeddedImageAsync(_settings.SenderEmailAddress, _settings.SenderEmailPassword, + await EmailService.SendEmailWithEmbeddedImageAsync(_settings.SenderEmailAddress, + _settings.SenderEmailPassword, _settings.ReceiverEmailAddress, $"Moxfield Scraper Success on {_deckTitle}!", $"Optimal price found for {_deckTitle}: €{finalPrice}! See attachment proof...", Path.Combine(dataDirectory, $"{_deckTitle}_proof.png")); @@ -111,7 +112,7 @@ private void InitializeWebDriver() chromeOptions.AddArgument("--headless"); // Run in headless mode, without a GUI chromeOptions.AddArgument("--window-size=2560,1440"); // Set window size chromeOptions.AddArgument("--log-level=3"); // Disable logging - chromeOptions.AddExcludedArguments("enable-logging"); // Disable logging + chromeOptions.AddExcludedArguments("enable-logging"); // Disable logging var preferences = new Dictionary { { "profile.managed_default_content_settings.images", 2 } // Disable image loading From b17e7da0a6336edc70770df26ea4e63ee232890b Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Sun, 22 Sep 2024 17:44:55 +0200 Subject: [PATCH 04/31] Add docker volumes for data and logs to retain information between versions --- MoxfieldPriceScraper/Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 2d68c06..f24032b 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -22,6 +22,8 @@ RUN apt-get update && apt-get install -y wget unzip && \ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt install ./google-chrome-stable_current_amd64.deb -y && \ rm google-chrome-stable_current_amd64.deb && \ - apt-get clean + apt-get clean \ + +VOLUME ["app/Data", "/app/Logs"] ENTRYPOINT ["dotnet", "MoxfieldPriceScraper.dll"] From 09fd2a55d38db3fd5bbdcc44781c1393d8a2af57 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Sun, 22 Sep 2024 19:37:57 +0200 Subject: [PATCH 05/31] Revamp settings --- .gitignore | 1 + MoxfieldPriceScraper/ISettings.cs | 23 ++-- .../MoxfieldPriceScraper.csproj | 1 + MoxfieldPriceScraper/MoxfieldScraper.cs | 1 + MoxfieldPriceScraper/Program.cs | 3 +- MoxfieldPriceScraper/Settings.cs | 128 ++++++++++-------- README.md | 27 ++-- 7 files changed, 95 insertions(+), 89 deletions(-) diff --git a/.gitignore b/.gitignore index ba4ee6b..9f3f025 100644 --- a/.gitignore +++ b/.gitignore @@ -223,6 +223,7 @@ project.lock.json ##### # End of core ignore list, below put you custom 'per project' settings (patterns or path) ##### +.env # Data [Dd]ata/ diff --git a/MoxfieldPriceScraper/ISettings.cs b/MoxfieldPriceScraper/ISettings.cs index 6af397d..1b2057e 100644 --- a/MoxfieldPriceScraper/ISettings.cs +++ b/MoxfieldPriceScraper/ISettings.cs @@ -2,18 +2,13 @@ public interface ISettings { - decimal TargetPrice { get; set; } - int UpdateFrequency { get; set; } - string? MoxfieldUsername { get; set; } - string? MoxfieldPassword { get; set; } - bool SendEmailNotification { get; set; } - string? SenderEmailAddress { get; set; } - string? SenderEmailPassword { get; set; } - string? ReceiverEmailAddress { get; set; } - Dictionary? DeckList { get; set; } - - /// - /// Saves the current settings to file. - /// - Task SaveSettingsAsync(); + decimal TargetPrice { get; } + int UpdateFrequency { get; } + string? MoxfieldUsername { get; } + string? MoxfieldPassword { get; } + bool SendEmailNotification { get; } + string? SenderEmailAddress { get; } + string? SenderEmailPassword { get; } + string? ReceiverEmailAddress { get; } + Dictionary? DeckList { get; } } diff --git a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj index 68f4feb..8bd6fa4 100644 --- a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj +++ b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj @@ -15,6 +15,7 @@ + diff --git a/MoxfieldPriceScraper/MoxfieldScraper.cs b/MoxfieldPriceScraper/MoxfieldScraper.cs index 11c3583..a596ceb 100644 --- a/MoxfieldPriceScraper/MoxfieldScraper.cs +++ b/MoxfieldPriceScraper/MoxfieldScraper.cs @@ -42,6 +42,7 @@ public async Task ScrapeAsync(CancellationToken cancellationToken) // Check for cancellation after login cancellationToken.ThrowIfCancellationRequested(); + await _driver.Navigate().GoToUrlAsync(_deckUrl); CheckCurrency(); await _driver.Navigate().GoToUrlAsync(_deckUrl); Log.Debug("Return to [{DeckUrl}] after login", _deckUrl); diff --git a/MoxfieldPriceScraper/Program.cs b/MoxfieldPriceScraper/Program.cs index 691e20c..bc9779d 100644 --- a/MoxfieldPriceScraper/Program.cs +++ b/MoxfieldPriceScraper/Program.cs @@ -11,7 +11,7 @@ try { Log.Information("Moxfield Price Scraper initiated"); - var settings = await Settings.CreateAsync(); + ISettings settings = new Settings(); if (settings.DeckList == null || settings.DeckList.Count == 0) { @@ -41,6 +41,7 @@ { Log.Error("Scraping thread for deck {Deck} failed: {Message}", deckCopy.Key, e.Message); cts.Cancel(); // Cancel all threads on error + throw; } }, cancellationToken)); } diff --git a/MoxfieldPriceScraper/Settings.cs b/MoxfieldPriceScraper/Settings.cs index 43653c0..754a5ac 100644 --- a/MoxfieldPriceScraper/Settings.cs +++ b/MoxfieldPriceScraper/Settings.cs @@ -1,83 +1,95 @@ -using Newtonsoft.Json; +using DotNetEnv; +using Newtonsoft.Json; using Serilog; namespace MoxfieldPriceScraper; public class Settings : ISettings { - private const string SettingsPath = "./settings.json"; + public decimal TargetPrice { get; } + public int UpdateFrequency { get; } + public string? MoxfieldUsername { get; } + public string? MoxfieldPassword { get; } + public bool SendEmailNotification { get; } + public string? SenderEmailAddress { get; } + public string? SenderEmailPassword { get; } + public string? ReceiverEmailAddress { get; } + public Dictionary? DeckList { get; } - public decimal TargetPrice { get; set; } - public int UpdateFrequency { get; set; } - public string? MoxfieldUsername { get; set; } - public string? MoxfieldPassword { get; set; } - public bool SendEmailNotification { get; set; } - public string? SenderEmailAddress { get; set; } - public string? SenderEmailPassword { get; set; } - public string? ReceiverEmailAddress { get; set; } - public Dictionary? DeckList { get; set; } - - // Private constructor to enforce use of factory method - private Settings() + public Settings() { +#if DEBUG + Log.Debug("Loading settings from .env file"); + Env.Load(".env"); +#endif + TargetPrice = GetDecimal("TARGET_PRICE", 25.00m); + UpdateFrequency = GetInt("UPDATE_FREQUENCY", 300); + MoxfieldUsername = GetString("MOXFIELD_USERNAME"); + MoxfieldPassword = GetString("MOXFIELD_PASSWORD"); + SendEmailNotification = GetBool("SEND_EMAIL_NOTIFICATION", false); + SenderEmailAddress = GetString("SENDER_EMAIL_ADDRESS"); + SenderEmailPassword = GetString("SENDER_EMAIL_PASSWORD"); + ReceiverEmailAddress = GetString("RECEIVER_EMAIL_ADDRESS"); + DeckList = GetDeckList("DECK_LIST"); // Expecting a JSON-formatted string in env variable } /// - /// Creates a new instance of the Settings class, propagated with loaded settings values. + /// Gets a decimal value from the environment variables, or returns a default value if not found. /// - /// A new instance of the Settings class - public static async Task CreateAsync() + /// The key from the environment containing a decimal value. + /// The default fallback value. + /// A decimal value associated with the given key. + private static decimal GetDecimal(string key, decimal defaultValue) { - Log.Debug("Loading settings from file"); - return await LoadSettingsAsync(); + var value = Environment.GetEnvironmentVariable(key); + return decimal.TryParse(value, out var result) ? result : defaultValue; } - /// - /// JSON serialization failed. - public async Task SaveSettingsAsync() + /// + /// Gets an integer value from the environment variables, or returns a default value if not found. + /// + /// The key from the environment containing an integer value. + /// The default fallback value. + /// An integer value associated with the given key. + private static int GetInt(string key, int defaultValue) { - try - { - var directory = Path.GetDirectoryName(SettingsPath); - if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) - { - Log.Debug("Creating directory {Directory}", directory); - Directory.CreateDirectory(directory); - } + var value = Environment.GetEnvironmentVariable(key); + return int.TryParse(value, out var result) ? result : defaultValue; + } - var json = JsonConvert.SerializeObject(this, Formatting.Indented); - await File.WriteAllTextAsync(SettingsPath, json); - } - catch (Exception e) - { - Log.Fatal(e, "Failed to serialize settings.json"); - throw new Exception("Failed to serialize settings.json", e); - } + /// + /// Gets a string value from the environment variables. + /// + /// The key from the environment containing a string value. + /// A string value associated with the given key. + private static string? GetString(string key) + { + return Environment.GetEnvironmentVariable(key); } /// - /// Loads settings from file. + /// Gets a boolean value from the environment variables, or returns a default value if not found. /// - /// A deserialized settings object. - /// JSON deserialization failed. - private static async Task LoadSettingsAsync() + /// The key from the environment containing a boolean value. + /// The default fallback value. + /// A boolean value associated with the given key. + private static bool GetBool(string key, bool defaultValue) { - if (!File.Exists(SettingsPath)) - { - Log.Fatal("settings.json not found"); - throw new Exception("settings.json not found"); - } + var value = Environment.GetEnvironmentVariable(key); + return bool.TryParse(value, out var result) ? result : defaultValue; + } - try - { - var json = await File.ReadAllTextAsync(SettingsPath); - return JsonConvert.DeserializeObject(json) ?? - throw new Exception("Failed to deserialize settings.json"); - } - catch (Exception e) - { - Log.Fatal(e, "Failed to deserialize settings.json"); - throw new Exception("Failed to deserialize settings.json", e); - } + /// + /// Gets a dictionary of deck names and URLs from the environment variables. + /// + /// The key from the environment containing a dictionary of deck names and URLs in json format. + /// A dictionary of deck names and URLs associated with the given key. + private static Dictionary? GetDeckList(string key) + { + var json = Environment.GetEnvironmentVariable(key); + Console.WriteLine(json); + return json != null + ? JsonConvert.DeserializeObject>(json) + : null; } } diff --git a/README.md b/README.md index 41284f8..5a04b6c 100644 --- a/README.md +++ b/README.md @@ -11,23 +11,18 @@ To run the application, ensure you have the following installed: **Note:** The ChromeDriver executable must be manually placed in the root directory of the project. ## Setting up -Before running the application, user-specific settings must be configured. This can be done by editing the settings.json file located in the root directory. The file should contain the following options: +Before running the application in development mode, user-specific settings must be configured. This can be done by creating and editing a `.env` file in the root directory. The file should contain the following options: -```json -{ - "TargetPrice": 20.00, - "UpdateFrequency": 300, - "MoxfieldUsername": "[USERNAME]", - "MoxfieldPassword": "[PASSWORD]", - "SendEmailNotification": true, - "SenderEmailAddress": "[E-MAIL #1 ADDRESS]", - "SenderEmailPassword": "[E-MAIL #1 PASSWORD]", - "ReceiverEmailAddress": "[E-MAIL #2 ADDRESS]", - "DeckList": { - "[DESK NAME #1]": "[DESK URL #1]", - "[DESK NAME #2]": "[DESK URL #2]" - } -} +```dockerfile +TARGET_PRICE=25.00 +UPDATE_FREQUENCY=300 +MOXFIELD_USERNAME='moxfieldUsername' +MOXFIELD_PASSWORD='moxfieldPassword' +SEND_EMAIL_NOTIFICATION=true +SENDER_EMAIL_ADDRESS='senderemail@example.com' +SENDER_EMAIL_PASSWORD='senderemailpassword' +RECEIVER_EMAIL_ADDRESS='receiveremail@example.com' +DECK_LIST='{"Deck1":"https://moxfield.com/deck1", "Deck2":"https://moxfield.com/deck2"}' ``` ### Configuration options - **TargetPrice**: The price threshold that the deck must reach before the scraping stops. From 34430164eddb6460fa887b99274558301b487056 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Sun, 22 Sep 2024 20:44:37 +0200 Subject: [PATCH 06/31] Fixed currency affiliation settings --- MoxfieldPriceScraper/MoxfieldScraper.cs | 54 ++++++++++++++++--------- MoxfieldPriceScraper/Settings.cs | 1 - README.md | 2 +- 3 files changed, 37 insertions(+), 20 deletions(-) diff --git a/MoxfieldPriceScraper/MoxfieldScraper.cs b/MoxfieldPriceScraper/MoxfieldScraper.cs index a596ceb..b7370a8 100644 --- a/MoxfieldPriceScraper/MoxfieldScraper.cs +++ b/MoxfieldPriceScraper/MoxfieldScraper.cs @@ -37,13 +37,13 @@ public async Task ScrapeAsync(CancellationToken cancellationToken) else { Log.Warning("Moxfield credentials settings are not fully configured"); + throw new ArgumentException("Moxfield credentials settings are not fully configured"); } // Check for cancellation after login cancellationToken.ThrowIfCancellationRequested(); - await _driver.Navigate().GoToUrlAsync(_deckUrl); - CheckCurrency(); + await CheckCurrency(); await _driver.Navigate().GoToUrlAsync(_deckUrl); Log.Debug("Return to [{DeckUrl}] after login", _deckUrl); var finalPrice = await GetPrice(_settings.TargetPrice, _settings.UpdateFrequency, cancellationToken); @@ -162,6 +162,12 @@ private void LoginToMoxfieldAsync(string username, string password) "#maincontent > div > div.col-lg-8 > div > div.card.border-0.col-sm-9.col-lg-7 > " + "div > form > div:nth-child(3) > button ")); signInBox.Click(); + Log.Debug("Clicked on sign in box"); + + var waitTimeInSeconds = 3; + Log.Debug("Allowing {TimeInSeconds} seconds for login to complete", waitTimeInSeconds); + Thread.Sleep(TimeSpan.FromSeconds(waitTimeInSeconds)); + Log.Debug("Successfully logged in to Moxfield"); } @@ -204,30 +210,42 @@ private string GetPriceField() /// /// Checks if the currency is set to Euro (€) on Moxfield. If it is not, it changes it. /// - private void CheckCurrency() + private async Task CheckCurrency() { var price = GetPriceField(); Log.Debug("Checking currency settings"); - if (!price.Contains("€")) + if (!price.Contains('€')) { Log.Debug("Currency is not set to Euro (€)"); - var changeCurrencySettingsBox = _driver!.FindElement(By.CssSelector( - "#maincontent > div.container.mt-3.mb-5 > div.deckview > div.d-none.d-md-block.pe-4 > " + - "div > div.d-grid.gap-2.mt-4.mx-auto > div > a ")); - changeCurrencySettingsBox.Click(); - Log.Debug("Clicked on currency settings box"); - - var euroBox = _driver.FindElement(By.CssSelector("#playStyle-paperEuros")); - euroBox.Click(); - Log.Debug("Clicked on Euro (€) currency box"); + await _driver!.Navigate().GoToUrlAsync("https://www.moxfield.com/account/settings/affiliates"); + Log.Debug("Navigated to affiliate settings"); - var cardmarketBox = _driver.FindElement(By.CssSelector("#affiliate-cardmarket")); - cardmarketBox.Click(); - Log.Debug("Clicked on Cardmarket affiliate box"); + // Try to find the "up" arrow to change currency to Euro using Cardmarket + while (true) + { + try + { + var upButton = _driver.FindElement(By.CssSelector("#affiliate-control-cardmarket-up")); + if (upButton != null) + { + // Click the "up" button to move the item up + upButton.Click(); + Log.Debug("Clicked on up button to change currency to Cardmarket's Euro (€)"); + var uiUpdateDelay = TimeSpan.FromSeconds(1); + await Task.Delay(uiUpdateDelay); + } + } + catch (NoSuchElementException) + { + // If the "up" arrow is not found, break out of the loop + Log.Debug("Cardmarket affiliate is listed at the top"); + break; + } + } var saveSettingsBox = _driver.FindElement(By.CssSelector( - "#maincontent > div.container.my-5 > div.row > div.col-lg-8.pe-lg-5.order-2.order-lg-1 > " + - "form > div:nth-child(4) > button ")); + "#maincontent > div > div.row > div.col-lg-8.pe-lg-5.order-2.order-lg-1 > form > " + + "div:nth-child(3) > button")); saveSettingsBox.Click(); Log.Debug("Clicked on save settings box"); diff --git a/MoxfieldPriceScraper/Settings.cs b/MoxfieldPriceScraper/Settings.cs index 754a5ac..5614dd8 100644 --- a/MoxfieldPriceScraper/Settings.cs +++ b/MoxfieldPriceScraper/Settings.cs @@ -87,7 +87,6 @@ private static bool GetBool(string key, bool defaultValue) private static Dictionary? GetDeckList(string key) { var json = Environment.GetEnvironmentVariable(key); - Console.WriteLine(json); return json != null ? JsonConvert.DeserializeObject>(json) : null; diff --git a/README.md b/README.md index 5a04b6c..b93a2ee 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ To run the application, ensure you have the following installed: Before running the application in development mode, user-specific settings must be configured. This can be done by creating and editing a `.env` file in the root directory. The file should contain the following options: ```dockerfile -TARGET_PRICE=25.00 +TARGET_PRICE=25 UPDATE_FREQUENCY=300 MOXFIELD_USERNAME='moxfieldUsername' MOXFIELD_PASSWORD='moxfieldPassword' From 07464dd17d56d62dfefa12b5f6d47dd5b1609123 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolai=20Hejlesen=20J=C3=B8rgensen?= Date: Mon, 23 Sep 2024 17:27:46 +0200 Subject: [PATCH 07/31] Create dotnet.yml --- .github/workflows/dotnet.yml | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 .github/workflows/dotnet.yml diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 0000000..015b327 --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -0,0 +1,42 @@ +name: .NET + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master", "dev" ] + +permissions: {} + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + packages: read + # To report GitHub Actions status checks + statuses: write + + steps: + - uses: actions/checkout@v4 + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + - name: Restore dependencies for Moxfield Price Scraper + working-directory: MoxfieldPriceScraper/ + run: dotnet restore + - name: Build Moxfield Price Scraper + working-directory: MoxfieldPriceScraper/ + env: + TARGET_PRICE: ${{secrets.TARGET_PRICE}} + UPDATE_FREQUENCY: ${{secrets.UPDATE_FREQUENCY}} + MOXFIELD_USERNAME: ${{secrets.MOXFIELD_USERNAME}} + MOXFIELD_PASSWORD: ${{secrets.MOXFIELD_PASSWORD}} + SEND_EMAIL_NOTIFICATION: ${{secrets.SEND_EMAIL_NOTIFICATION}} + SENDER_EMAIL_ADDRESS: ${{secrets.SENDER_EMAIL_ADDRESS}} + SENDER_EMAIL_PASSWORD: ${{secrets.SENDER_EMAIL_PASSWORD}} + RECEIVER_EMAIL_ADDRESS: ${{secrets.RECEIVER_EMAIL_ADDRESS}} + DECK_LIST: ${{secrets.DECK_LIST}} + run: dotnet build --no-restore From 89ecbf37ca978a6471d019b4d9b7c8838b08e77a Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 17:28:17 +0200 Subject: [PATCH 08/31] Modify docker-compose.yml file --- docker-compose.yml | 53 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 0b2e8a4..512f3f1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,51 @@ services: moxfieldpricescraper: - image: moxfieldpricescraper - build: - context: . - dockerfile: MoxfieldPriceScraper/Dockerfile + image: ghcr.io/karmakamikaze/moxfield-price-scraper:latest + container_name: MoxfieldPriceScraper + restart: always + environment: + - TZ=${TIMEZONE} + - TARGET_PRICE=${TARGET_PRICE} + - UPDATE_FREQUENCY=${UPDATE_FREQUENCY} + - MOXFIELD_USERNAME=${MOXFIELD_USERNAME} + - SEND_EMAIL_NOTIFICATION=${SEND_EMAIL_NOTIFICATION} + - SENDER_EMAIL_ADDRESS=${SENDER_EMAIL_ADDRESS} + - RECEIVER_EMAIL_ADDRESS=${RECEIVER_EMAIL_ADDRESS} + - DECK_LIST=${DECK_LIST} + secrets: + - MOXFIELD_PASSWORD + - SENDER_EMAIL_PASSWORD + volumes: + - ./Data:/app/Data + - ./Logs:/app/Logs + labels: + - "com.centurylinklabs.watchtower.enable=true" + deploy: + resources: + limits: + cpus: "3.0" + memory: "6G" + + watchtower: + image: containrrr/watchtower:latest + container_name: Watchtower + restart: always + environment: + - TZ=${TIMEZONE} + - WATCHTOWER_SCHEDULE=${WATCHTOWER_SCHEDULE} + - WATCHTOWER_CLEANUP=true + - WATCHTOWER_LABEL_ENABLE=true + - WATCHTOWER_INCLUDE_RESTARTING=true + volumes: + - /var/run/docker.sock:/var/run/docker.sock + deploy: + resources: + limits: + cpus: "0.5" + memory: "512M" + +secrets: + MOXFIELD_PASSWORD: + file: ./secrets/moxfield_password.txt + SENDER_EMAIL_PASSWORD: + file: ./secrets/sender_email_password.txt From 322105e533f1920af45ea5639dcd3173272a9c98 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 17:32:53 +0200 Subject: [PATCH 09/31] Add linter action --- .github/workflows/linter.yaml | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 .github/workflows/linter.yaml diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml new file mode 100644 index 0000000..38f5c4b --- /dev/null +++ b/.github/workflows/linter.yaml @@ -0,0 +1,40 @@ +name: Lint Code Base + +on: + push: + branches: [master, dev] + pull_request: + branches: [master, dev] + +permissions: {} + +jobs: + build: + name: Lint Code Base + runs-on: ubuntu-latest + permissions: + contents: read + packages: read + statuses: write + + steps: + - name: Checkout Code + uses: actions/checkout@v4 + with: + # Full git history is needed to get a proper + # list of changed files within `super-linter` + fetch-depth: 0 + + - name: Super Linter + uses: super-linter/super-linter@v7.1.0 + env: + VALIDATE_ALL_CODEBASE: false + VALIDATE_CSS: false + VALIDATE_JAVASCRIPT_ES: false + VALIDATE_JAVASCRIPT_STANDARD: false + VALIDATE_JSCPD: false + VALIDATE_MARKDOWN: false + VALIDATE_NATURAL_LANGUAGE: false + DEFAULT_BRANCH: master + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + FILTER_REGEX_EXCLUDE: .*Tests/.* \ No newline at end of file From 02f601fb19c3c86e40a6aa9baff172b468e55f66 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 17:38:55 +0200 Subject: [PATCH 10/31] Add docker-publish github action --- .github/workflows/docker-publish.yml | 99 ++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 .github/workflows/docker-publish.yml diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 0000000..a14704b --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,99 @@ +name: Docker Publish + +on: + push: + branches: ["master"] + # Publish semver tags as releases. + tags: ["*.*.*"] + pull_request: + branches: ["master"] + +permissions: {} + +env: + # Use docker.io for Docker Hub if empty + REGISTRY: ghcr.io + # github.repository as / + IMAGE_NAME: ${{ github.repository }} + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + # This is used to complete the identity challenge + # with sigstore/fulcio when running outside of PRs. + id-token: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + # Install the cosign tool except on PR + # https://github.com/sigstore/cosign-installer + - name: Install cosign + if: github.event_name != 'pull_request' + uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0 + with: + cosign-release: "v2.2.4" + + # Set up BuildKit Docker container builder to be able to build + # multi-platform images and export cache + # https://github.com/docker/setup-buildx-action + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 + + # Set up QEMU for cross-architecture builds + - name: Install QEMU for ARM64 + uses: docker/setup-qemu-action@v3 + with: + platforms: linux/arm64 + + # Login against a Docker registry except on PR + # https://github.com/docker/login-action + - name: Log into registry ${{ env.REGISTRY }} + if: github.event_name != 'pull_request' + uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + # Extract metadata (tags, labels) for Docker + # https://github.com/docker/metadata-action + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + + # Build and push Docker image with Buildx (don't push on PR) + # https://github.com/docker/build-push-action + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 + with: + context: MoxfieldPriceScraper/ + file: MoxfieldPriceScraper/Dockerfile + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + platforms: linux/arm64 + + # Sign the resulting Docker image digest except on PRs. + # This will only write to the public Rekor transparency log when the Docker + # repository is public to avoid leaking data. If you would like to publish + # transparency data even for private images, pass --force to cosign below. + # https://github.com/sigstore/cosign + - name: Sign the published Docker image + if: ${{ github.event_name != 'pull_request' }} + env: + # https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable + TAGS: ${{ steps.meta.outputs.tags }} + DIGEST: ${{ steps.build-and-push.outputs.digest }} + # This step uses the identity token to provision an ephemeral certificate + # against the sigstore community Fulcio instance. + run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@"${DIGEST}" \ No newline at end of file From 1ac99befc17494b3bb3a903cc0563be6c60146fb Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 17:48:52 +0200 Subject: [PATCH 11/31] Use apt-get instead of apt --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index f24032b..8283f51 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -20,7 +20,7 @@ COPY --from=build-env /app/out . # Install Google Chrome RUN apt-get update && apt-get install -y wget unzip && \ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ - apt install ./google-chrome-stable_current_amd64.deb -y && \ + apt-get install ./google-chrome-stable_current_amd64.deb -y && \ rm google-chrome-stable_current_amd64.deb && \ apt-get clean \ From bcd023304f7fa4b55e1da23e7ad2b3246537c395 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 19:13:05 +0200 Subject: [PATCH 12/31] Add healthcheck --- MoxfieldPriceScraper/Dockerfile | 4 +- .../Healthcheck/Healthcheck.cs | 60 +++++++++++++++++++ .../Healthcheck/TaskStatus.cs | 6 ++ MoxfieldPriceScraper/Program.cs | 18 ++++++ MoxfieldPriceScraper/settings.json | 14 ----- docker-compose.yml | 1 + 6 files changed, 88 insertions(+), 15 deletions(-) create mode 100644 MoxfieldPriceScraper/Healthcheck/Healthcheck.cs create mode 100644 MoxfieldPriceScraper/Healthcheck/TaskStatus.cs delete mode 100644 MoxfieldPriceScraper/settings.json diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 8283f51..ea5f7f2 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -24,6 +24,8 @@ RUN apt-get update && apt-get install -y wget unzip && \ rm google-chrome-stable_current_amd64.deb && \ apt-get clean \ -VOLUME ["app/Data", "/app/Logs"] +HEALTHCHECK --interval=5m --timeout=1m --start-period=30s --retries=3 CMD ["dotnet", "MoxfieldPriceScraper.dll", "healthcheck"] + +VOLUME ["/app/Data", "/app/Logs"] ENTRYPOINT ["dotnet", "MoxfieldPriceScraper.dll"] diff --git a/MoxfieldPriceScraper/Healthcheck/Healthcheck.cs b/MoxfieldPriceScraper/Healthcheck/Healthcheck.cs new file mode 100644 index 0000000..c59b155 --- /dev/null +++ b/MoxfieldPriceScraper/Healthcheck/Healthcheck.cs @@ -0,0 +1,60 @@ +using Newtonsoft.Json; + +namespace MoxfieldPriceScraper.Healthcheck; + +public static class Healthcheck +{ + private const string StatusFilePath = "tasks.status"; + private static readonly object FileLock = new object(); + + /// + /// Initializes the status file with an empty dictionary if it doesn't exist. + /// + public static void InitializeStatusFile() + { + lock (FileLock) + { + if (!File.Exists(StatusFilePath)) + { + var initialStatus = new TaskStatus(); + File.WriteAllText(StatusFilePath, JsonConvert.SerializeObject(initialStatus, Formatting.Indented)); + } + } + } + + /// + /// Updates the status of a task in the status file. + /// + /// The task name associated with the status that needs to update. + /// The new status. + public static void UpdateTaskStatus(string taskName, string status) + { + lock (FileLock) + { + var taskStatus = JsonConvert.DeserializeObject(File.ReadAllText(StatusFilePath)); + if (taskStatus != null) + { + taskStatus.Statuses[taskName] = status; + File.WriteAllText(StatusFilePath, JsonConvert.SerializeObject(taskStatus, Formatting.Indented)); + } + } + } + + /// + /// Checks if any tasks are running. + /// + /// True if tasks are still running, false otherwise. + public static bool AreTasksRunning() + { + lock (FileLock) + { + if (!File.Exists(StatusFilePath)) + { + return false; + } + + var taskStatus = JsonConvert.DeserializeObject(File.ReadAllText(StatusFilePath)); + return taskStatus != null && taskStatus.Statuses.ContainsValue("running"); + } + } +} diff --git a/MoxfieldPriceScraper/Healthcheck/TaskStatus.cs b/MoxfieldPriceScraper/Healthcheck/TaskStatus.cs new file mode 100644 index 0000000..d203ba0 --- /dev/null +++ b/MoxfieldPriceScraper/Healthcheck/TaskStatus.cs @@ -0,0 +1,6 @@ +namespace MoxfieldPriceScraper.Healthcheck; + +public class TaskStatus +{ + public Dictionary Statuses { get; set; } = new(); +} diff --git a/MoxfieldPriceScraper/Program.cs b/MoxfieldPriceScraper/Program.cs index bc9779d..5a3eac0 100644 --- a/MoxfieldPriceScraper/Program.cs +++ b/MoxfieldPriceScraper/Program.cs @@ -1,6 +1,19 @@ using MoxfieldPriceScraper; +using MoxfieldPriceScraper.Healthcheck; using Serilog; +if (args.Length > 0 && args[0] == "healthcheck") +{ + if (Healthcheck.AreTasksRunning()) + { + Console.WriteLine("Tasks are running"); + Environment.Exit(0); // Healthy, tasks are running + } + + Console.WriteLine("No tasks are running"); + Environment.Exit(1); // Unhealthy, no tasks running +} + bool debugEnabled = false; #if DEBUG debugEnabled = true; @@ -20,6 +33,8 @@ Environment.Exit(1); } + Healthcheck.InitializeStatusFile(); + // Create a CancellationTokenSource to cancel all threads on error var cts = new CancellationTokenSource(); var cancellationToken = cts.Token; @@ -34,12 +49,15 @@ { try { + Healthcheck.UpdateTaskStatus(deckCopy.Key, "running"); var scraper = new MoxfieldScraper(deckCopy.Value, settings); await scraper.ScrapeAsync(cancellationToken); + Healthcheck.UpdateTaskStatus(deckCopy.Key, "completed"); } catch (Exception e) { Log.Error("Scraping thread for deck {Deck} failed: {Message}", deckCopy.Key, e.Message); + Healthcheck.UpdateTaskStatus(deckCopy.Key, "failed"); cts.Cancel(); // Cancel all threads on error throw; } diff --git a/MoxfieldPriceScraper/settings.json b/MoxfieldPriceScraper/settings.json deleted file mode 100644 index d5aa36d..0000000 --- a/MoxfieldPriceScraper/settings.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "TargetPrice": 20.00, - "UpdateFrequency": 300, - "MoxfieldUsername": "", - "MoxfieldPassword": "", - "SendEmailNotification": true, - "SenderEmailAddress": "", - "SenderEmailPassword": "", - "ReceiverEmailAddress": "", - "DeckList": { - "Deck Name1": "Deck URL1", - "Deck Name2": "Deck URL2" - } -} diff --git a/docker-compose.yml b/docker-compose.yml index 512f3f1..81ccd0e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,6 +18,7 @@ volumes: - ./Data:/app/Data - ./Logs:/app/Logs + - ./tasks.status:/app/tasks.status labels: - "com.centurylinklabs.watchtower.enable=true" deploy: From 6288de95efc9fd910c445c01ffca39b9a313cd88 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 19:14:49 +0200 Subject: [PATCH 13/31] Fix CSHARP linter errors --- MoxfieldPriceScraper/Program.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/MoxfieldPriceScraper/Program.cs b/MoxfieldPriceScraper/Program.cs index 5a3eac0..84241bb 100644 --- a/MoxfieldPriceScraper/Program.cs +++ b/MoxfieldPriceScraper/Program.cs @@ -6,11 +6,9 @@ { if (Healthcheck.AreTasksRunning()) { - Console.WriteLine("Tasks are running"); Environment.Exit(0); // Healthy, tasks are running } - Console.WriteLine("No tasks are running"); Environment.Exit(1); // Unhealthy, no tasks running } From 65d75f11430bffb8ff33603a9af1d3e4fc036e5d Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 19:35:02 +0200 Subject: [PATCH 14/31] Fix yml linter errors --- .github/workflows/docker-publish.yml | 2 +- .github/workflows/dotnet.yml | 47 ++++++++++++++-------------- .github/workflows/linter.yaml | 2 +- 3 files changed, 25 insertions(+), 26 deletions(-) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index a14704b..55deb5b 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -96,4 +96,4 @@ jobs: DIGEST: ${{ steps.build-and-push.outputs.digest }} # This step uses the identity token to provision an ephemeral certificate # against the sigstore community Fulcio instance. - run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@"${DIGEST}" \ No newline at end of file + run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@"${DIGEST}" diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 015b327..5b543cd 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -2,15 +2,14 @@ name: .NET on: push: - branches: [ "master" ] + branches: ["master"] pull_request: - branches: [ "master", "dev" ] + branches: ["master", "dev"] permissions: {} jobs: build: - runs-on: ubuntu-latest permissions: contents: read @@ -19,24 +18,24 @@ jobs: statuses: write steps: - - uses: actions/checkout@v4 - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: 8.0.x - - name: Restore dependencies for Moxfield Price Scraper - working-directory: MoxfieldPriceScraper/ - run: dotnet restore - - name: Build Moxfield Price Scraper - working-directory: MoxfieldPriceScraper/ - env: - TARGET_PRICE: ${{secrets.TARGET_PRICE}} - UPDATE_FREQUENCY: ${{secrets.UPDATE_FREQUENCY}} - MOXFIELD_USERNAME: ${{secrets.MOXFIELD_USERNAME}} - MOXFIELD_PASSWORD: ${{secrets.MOXFIELD_PASSWORD}} - SEND_EMAIL_NOTIFICATION: ${{secrets.SEND_EMAIL_NOTIFICATION}} - SENDER_EMAIL_ADDRESS: ${{secrets.SENDER_EMAIL_ADDRESS}} - SENDER_EMAIL_PASSWORD: ${{secrets.SENDER_EMAIL_PASSWORD}} - RECEIVER_EMAIL_ADDRESS: ${{secrets.RECEIVER_EMAIL_ADDRESS}} - DECK_LIST: ${{secrets.DECK_LIST}} - run: dotnet build --no-restore + - uses: actions/checkout@v4 + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + - name: Restore dependencies for Moxfield Price Scraper + working-directory: MoxfieldPriceScraper/ + run: dotnet restore + - name: Build Moxfield Price Scraper + working-directory: MoxfieldPriceScraper/ + env: + TARGET_PRICE: ${{secrets.TARGET_PRICE}} + UPDATE_FREQUENCY: ${{secrets.UPDATE_FREQUENCY}} + MOXFIELD_USERNAME: ${{secrets.MOXFIELD_USERNAME}} + MOXFIELD_PASSWORD: ${{secrets.MOXFIELD_PASSWORD}} + SEND_EMAIL_NOTIFICATION: ${{secrets.SEND_EMAIL_NOTIFICATION}} + SENDER_EMAIL_ADDRESS: ${{secrets.SENDER_EMAIL_ADDRESS}} + SENDER_EMAIL_PASSWORD: ${{secrets.SENDER_EMAIL_PASSWORD}} + RECEIVER_EMAIL_ADDRESS: ${{secrets.RECEIVER_EMAIL_ADDRESS}} + DECK_LIST: ${{secrets.DECK_LIST}} + run: dotnet build --no-restore diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml index 38f5c4b..960f71e 100644 --- a/.github/workflows/linter.yaml +++ b/.github/workflows/linter.yaml @@ -37,4 +37,4 @@ jobs: VALIDATE_NATURAL_LANGUAGE: false DEFAULT_BRANCH: master GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - FILTER_REGEX_EXCLUDE: .*Tests/.* \ No newline at end of file + FILTER_REGEX_EXCLUDE: .*Tests/.* From 715edbe7d54d6f15ea007f6ba91cb5c2c3567722 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 19:40:02 +0200 Subject: [PATCH 15/31] Fix CSHARP linter errors --- MoxfieldPriceScraper/MoxfieldScraper.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MoxfieldPriceScraper/MoxfieldScraper.cs b/MoxfieldPriceScraper/MoxfieldScraper.cs index b7370a8..be4f06f 100644 --- a/MoxfieldPriceScraper/MoxfieldScraper.cs +++ b/MoxfieldPriceScraper/MoxfieldScraper.cs @@ -302,15 +302,15 @@ private void SaveImageProof(string imagePath = "proof.jpeg") var originalSize = _driver!.Manage().Window.Size; Log.Debug("Original window size is [{Width},{Height}]", originalSize.Width, originalSize.Height); var requiredWidth = - Convert.ToInt32((long) _driver.ExecuteScript("return document.body.parentNode.scrollWidth")); + Convert.ToInt32((long)_driver.ExecuteScript("return document.body.parentNode.scrollWidth")); var requiredHeight = - Convert.ToInt32((long) _driver.ExecuteScript("return document.body.parentNode.scrollHeight")); + Convert.ToInt32((long)_driver.ExecuteScript("return document.body.parentNode.scrollHeight")); _driver.Manage().Window.Size = new Size(requiredWidth, requiredHeight); Log.Debug("Window size set to full page screenshot size [{Width},{Height}]", requiredWidth, requiredHeight); //_driver.GetScreenshot().SaveAsFile(imagePath); // has scrollbar - ((ITakesScreenshot) _driver.FindElement(By.TagName("body"))).GetScreenshot() + ((ITakesScreenshot)_driver.FindElement(By.TagName("body"))).GetScreenshot() .SaveAsFile(imagePath); // avoids scrollbar Log.Debug("Screenshot saved as [{ImagePath}]", imagePath); From 5961bcbed2e8df517c94d0026bcc4e81aafec690 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 19:52:59 +0200 Subject: [PATCH 16/31] Fix Dockerfile linter errors --- MoxfieldPriceScraper/Dockerfile | 4 ++-- README.md | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index ea5f7f2..422b01f 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -18,8 +18,8 @@ WORKDIR /app COPY --from=build-env /app/out . # Install Google Chrome -RUN apt-get update && apt-get install -y wget unzip && \ - wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ +RUN apt-get update && apt-get install -y wget=1.21-1+deb11u1 unzip=6.0-26+deb11u1 && \ + wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt-get install ./google-chrome-stable_current_amd64.deb -y && \ rm google-chrome-stable_current_amd64.deb && \ apt-get clean \ diff --git a/README.md b/README.md index b93a2ee..f5d14cb 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@ # Moxfield Price Scraper + The **Moxfield Price Scraper** is an application designed to continuously monitor the price of specified Moxfield decks until a defined threshold is reached. It automatically adjusts the prices of all cards within the deck list to reflect the lowest market values, ensuring users can acquire their desired decks at the best possible prices. Once the threshold is met, the application captures a screenshot of the deck and saves it. If email notifications are enabled, a notification email will also be sent to the user with the attached screenshot. This tool is particularly useful for playgroups that host events requiring decks to remain within a specific price range. My playgroup utilizes it for a custom format known as _Shitlander_, a €25 budget Commander (EDH) format, where all participants must provide a screenshot of their deck within this price limit. ## Prerequisites + To run the application, ensure you have the following installed: + - [.Net 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) - [Selenium](https://www.selenium.dev/documentation/) (installed via NuGet package) - [Google Chrome](https://www.google.com/chrome/index.html) @@ -11,6 +14,7 @@ To run the application, ensure you have the following installed: **Note:** The ChromeDriver executable must be manually placed in the root directory of the project. ## Setting up + Before running the application in development mode, user-specific settings must be configured. This can be done by creating and editing a `.env` file in the root directory. The file should contain the following options: ```dockerfile @@ -24,7 +28,9 @@ SENDER_EMAIL_PASSWORD='senderemailpassword' RECEIVER_EMAIL_ADDRESS='receiveremail@example.com' DECK_LIST='{"Deck1":"https://moxfield.com/deck1", "Deck2":"https://moxfield.com/deck2"}' ``` + ### Configuration options + - **TargetPrice**: The price threshold that the deck must reach before the scraping stops. - **UpdateFrequency**: The frequency at which the price is checked (in seconds). - **MoxfieldUsername**: Your Moxfield account username. @@ -33,17 +39,22 @@ DECK_LIST='{"Deck1":"https://moxfield.com/deck1", "Deck2":"https://moxfield.com/ - **SenderEmailAddress**: Email address used to send notifications. - **SenderEmailPassword**: Password for the sender email account. - **ReceiverEmailAddress**: Email address to receive notifications. -- **DeckList**: A dictionary of deck names and their corresponding Moxfield URLs. There should be at least one deck in the list, however, multiple decks can be added. +- **DeckList**: A dictionary of deck names and their corresponding Moxfield URLs. There should be at least one deck in the list, however, multiple decks can be added. ## Running the Application + The application can be executed using the following command: + ```shell dotnet run ``` + Alternatively, you can publish the application and run the resulting executable. ## Contributing + Contributions are welcome! If you would like to contribute to this project, please fork the repository and submit a pull request. ## License + This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. From eb2f00553f541ceffd4801faff7590a3fca62cdf Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:02:19 +0200 Subject: [PATCH 17/31] Fix linter errors in csproj --- .../MoxfieldPriceScraper.csproj | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj index 8bd6fa4..405e46b 100644 --- a/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj +++ b/MoxfieldPriceScraper/MoxfieldPriceScraper.csproj @@ -9,20 +9,20 @@ - - .dockerignore - + + .dockerignore + - - - - - - - - + + + + + + + + From 42b552d88ebee13f66998f2df61e7fdb08274ae9 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:03:40 +0200 Subject: [PATCH 18/31] Fix spelling error --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 422b01f..5278c9a 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -13,7 +13,7 @@ RUN dotnet restore --disable-parallel COPY . ./ RUN dotnet publish -c $BUILD_CONFIGURATION -o out --no-restore -FROM mcr.microsoft.com/dotnot/runtime:8.0 AS runtime +FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime WORKDIR /app COPY --from=build-env /app/out . From 0cb2b7348668c6d4dbaf1960563054d0c8c69630 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:08:04 +0200 Subject: [PATCH 19/31] Remove bad character --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 5278c9a..e4199a9 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -22,7 +22,7 @@ RUN apt-get update && apt-get install -y wget=1.21-1+deb11u1 unzip=6.0-26+deb11u wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt-get install ./google-chrome-stable_current_amd64.deb -y && \ rm google-chrome-stable_current_amd64.deb && \ - apt-get clean \ + apt-get clean HEALTHCHECK --interval=5m --timeout=1m --start-period=30s --retries=3 CMD ["dotnet", "MoxfieldPriceScraper.dll", "healthcheck"] From 8dc7f638812cc59c683a01a9efc374988281bc80 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:13:11 +0200 Subject: [PATCH 20/31] Simplify versioning in Dockerfile --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index e4199a9..9677d89 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -18,7 +18,7 @@ WORKDIR /app COPY --from=build-env /app/out . # Install Google Chrome -RUN apt-get update && apt-get install -y wget=1.21-1+deb11u1 unzip=6.0-26+deb11u1 && \ +RUN apt-get update && apt-get install -y wget=1.21-1 unzip=6.0-26 && \ wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt-get install ./google-chrome-stable_current_amd64.deb -y && \ rm google-chrome-stable_current_amd64.deb && \ From 9ddae99b63ee54df54ebea33b94d1b083c0d3557 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:16:49 +0200 Subject: [PATCH 21/31] Use available version --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 9677d89..240be56 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -18,7 +18,7 @@ WORKDIR /app COPY --from=build-env /app/out . # Install Google Chrome -RUN apt-get update && apt-get install -y wget=1.21-1 unzip=6.0-26 && \ +RUN apt-get update && apt-get install -y wget unzip && \ wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ apt-get install ./google-chrome-stable_current_amd64.deb -y && \ rm google-chrome-stable_current_amd64.deb && \ From a17bb2b920b42c8c1c8f966fafa3fbc0f1065fed Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:38:50 +0200 Subject: [PATCH 22/31] Use different cache for each build --- .github/workflows/docker-publish.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 55deb5b..706cb0b 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -82,6 +82,8 @@ jobs: cache-from: type=gha cache-to: type=gha,mode=max platforms: linux/arm64 + build-args: | + CACHEBUST=${{ github.run_id }} # Sign the resulting Docker image digest except on PRs. # This will only write to the public Rekor transparency log when the Docker From 5e8d3be3b93e7827433ada988d4ed1b5daf58216 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 20:41:02 +0200 Subject: [PATCH 23/31] Use same case-sensitivity --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 240be56..a2adf58 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20 as base +FROM alpine:3.20 AS base RUN useradd -m moxfieldpricescraper USER moxfieldpricescraper From e240979b77dc3a481eab6dc67f40b31aed093c40 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 21:04:10 +0200 Subject: [PATCH 24/31] We try something funky: https://github.com/docker/setup-qemu-action/issues/69 --- MoxfieldPriceScraper/Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index a2adf58..d5b4ccc 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -8,10 +8,10 @@ ARG BUILD_CONFIGURATION=Release WORKDIR /app COPY *.csproj ./ -RUN dotnet restore --disable-parallel +RUN DOTNET_EnableWriteXorExecute=0 dotnet restore --disable-parallel COPY . ./ -RUN dotnet publish -c $BUILD_CONFIGURATION -o out --no-restore +RUN DOTNET_EnableWriteXorExecute=0 dotnet publish -c $BUILD_CONFIGURATION -o out --no-restore FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime WORKDIR /app From fe020b37d7b18d47e029af8300d5715b146178c9 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 21:13:52 +0200 Subject: [PATCH 25/31] Use chromium for alpine --- MoxfieldPriceScraper/Dockerfile | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index d5b4ccc..5446ad3 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -17,12 +17,9 @@ FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime WORKDIR /app COPY --from=build-env /app/out . -# Install Google Chrome -RUN apt-get update && apt-get install -y wget unzip && \ - wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \ - apt-get install ./google-chrome-stable_current_amd64.deb -y && \ - rm google-chrome-stable_current_amd64.deb && \ - apt-get clean +# Install chromium +RUN apk add --no-cache chromium + HEALTHCHECK --interval=5m --timeout=1m --start-period=30s --retries=3 CMD ["dotnet", "MoxfieldPriceScraper.dll", "healthcheck"] From eb0a8dfdd1d6a2c6db5088fd14c90be53bdbbb2a Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Mon, 23 Sep 2024 21:25:37 +0200 Subject: [PATCH 26/31] Add chromium during runtime stage --- MoxfieldPriceScraper/Dockerfile | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 5446ad3..a1bb33e 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -15,11 +15,25 @@ RUN DOTNET_EnableWriteXorExecute=0 dotnet publish -c $BUILD_CONFIGURATION -o out FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime WORKDIR /app -COPY --from=build-env /app/out . # Install chromium -RUN apk add --no-cache chromium +RUN apt-get update && apt-get install -y \ + chromium \ + libgtk-3-0 \ + libx11-xcb1 \ + libxcomposite1 \ + libxcursor1 \ + libxdamage1 \ + libxrandr2 \ + libxi6 \ + libxtst6 \ + libxss1 \ + libasound2 \ + libdbus-glib-1-2 \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* +COPY --from=build-env /app/out . HEALTHCHECK --interval=5m --timeout=1m --start-period=30s --retries=3 CMD ["dotnet", "MoxfieldPriceScraper.dll", "healthcheck"] From 28812fd55b5f05f3dc3c10c0691d697f8991a10f Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Tue, 24 Sep 2024 15:14:23 +0200 Subject: [PATCH 27/31] Set specific versions --- MoxfieldPriceScraper/Dockerfile | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index a1bb33e..3901a2f 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -18,18 +18,18 @@ WORKDIR /app # Install chromium RUN apt-get update && apt-get install -y \ - chromium \ - libgtk-3-0 \ - libx11-xcb1 \ - libxcomposite1 \ - libxcursor1 \ - libxdamage1 \ - libxrandr2 \ - libxi6 \ - libxtst6 \ - libxss1 \ - libasound2 \ - libdbus-glib-1-2 \ + chromium=129.0.6668.58 \ + libgtk-3-0=3.24.38 \ + libx11-xcb1=2:1.8.4 \ + libxcomposite1=1:0.4.5 \ + libxcursor1=1:1.2.1 \ + libxdamage1=1:1.1.6 \ + libxrandr2=2:1.5.2 \ + libxi6=2:1.8 \ + libxtst6=2:1.2.3 \ + libxss1=1:1.2.3 \ + libasound2=1.2.8 \ + libdbus-glib-1-2=0.112 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* From c2aa99de03eec50f4b1f835c5ba6d02e286b3cf4 Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Tue, 24 Sep 2024 15:27:41 +0200 Subject: [PATCH 28/31] Add hadolint ignore --- .github/workflows/.hadolint.yaml | 2 ++ MoxfieldPriceScraper/Dockerfile | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/.hadolint.yaml diff --git a/.github/workflows/.hadolint.yaml b/.github/workflows/.hadolint.yaml new file mode 100644 index 0000000..8f7e23e --- /dev/null +++ b/.github/workflows/.hadolint.yaml @@ -0,0 +1,2 @@ +ignored: + - DL3008 diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index 3901a2f..a1bb33e 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -18,18 +18,18 @@ WORKDIR /app # Install chromium RUN apt-get update && apt-get install -y \ - chromium=129.0.6668.58 \ - libgtk-3-0=3.24.38 \ - libx11-xcb1=2:1.8.4 \ - libxcomposite1=1:0.4.5 \ - libxcursor1=1:1.2.1 \ - libxdamage1=1:1.1.6 \ - libxrandr2=2:1.5.2 \ - libxi6=2:1.8 \ - libxtst6=2:1.2.3 \ - libxss1=1:1.2.3 \ - libasound2=1.2.8 \ - libdbus-glib-1-2=0.112 \ + chromium \ + libgtk-3-0 \ + libx11-xcb1 \ + libxcomposite1 \ + libxcursor1 \ + libxdamage1 \ + libxrandr2 \ + libxi6 \ + libxtst6 \ + libxss1 \ + libasound2 \ + libdbus-glib-1-2 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* From c02494bb0c1d0e62fb2f865fd1a452523b8b616b Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Tue, 24 Sep 2024 15:32:57 +0200 Subject: [PATCH 29/31] Add hadolint file to superlinter --- .github/{workflows => linter}/.hadolint.yaml | 0 .github/workflows/linter.yaml | 1 + 2 files changed, 1 insertion(+) rename .github/{workflows => linter}/.hadolint.yaml (100%) diff --git a/.github/workflows/.hadolint.yaml b/.github/linter/.hadolint.yaml similarity index 100% rename from .github/workflows/.hadolint.yaml rename to .github/linter/.hadolint.yaml diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml index 960f71e..d96f02e 100644 --- a/.github/workflows/linter.yaml +++ b/.github/workflows/linter.yaml @@ -35,6 +35,7 @@ jobs: VALIDATE_JSCPD: false VALIDATE_MARKDOWN: false VALIDATE_NATURAL_LANGUAGE: false + DOCKERFILE_HADOLINT_FILE_NAME: "../linter/.hadolint.yaml" DEFAULT_BRANCH: master GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} FILTER_REGEX_EXCLUDE: .*Tests/.* From 66d02349d235a14361533f5bed2fc2d3c7bd4f6e Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Tue, 24 Sep 2024 15:37:05 +0200 Subject: [PATCH 30/31] Add linter rules path --- .github/workflows/linter.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml index d96f02e..102fcf1 100644 --- a/.github/workflows/linter.yaml +++ b/.github/workflows/linter.yaml @@ -35,7 +35,7 @@ jobs: VALIDATE_JSCPD: false VALIDATE_MARKDOWN: false VALIDATE_NATURAL_LANGUAGE: false - DOCKERFILE_HADOLINT_FILE_NAME: "../linter/.hadolint.yaml" + LINTER_RULES_PATH: .github/linter DEFAULT_BRANCH: master GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} FILTER_REGEX_EXCLUDE: .*Tests/.* From 0a4e95512dabf9c02e56b56191c754fc3ed4da4a Mon Sep 17 00:00:00 2001 From: KarmaKamikaze Date: Tue, 24 Sep 2024 15:40:59 +0200 Subject: [PATCH 31/31] Add --no-install-recommends flag to apt-get install --- MoxfieldPriceScraper/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MoxfieldPriceScraper/Dockerfile b/MoxfieldPriceScraper/Dockerfile index a1bb33e..75bbc1b 100644 --- a/MoxfieldPriceScraper/Dockerfile +++ b/MoxfieldPriceScraper/Dockerfile @@ -17,7 +17,7 @@ FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime WORKDIR /app # Install chromium -RUN apt-get update && apt-get install -y \ +RUN apt-get update && apt-get install -y --no-install-recommends \ chromium \ libgtk-3-0 \ libx11-xcb1 \