File heroic-gogdl-1.1.2.obscpio of Package HeroicGamesLauncher

07070100000000000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000001B00000000heroic-gogdl-1.1.2/.github07070100000001000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000002500000000heroic-gogdl-1.1.2/.github/workflows07070100000002000081A400000000000000000000000166E0651E000003D9000000000000000000000000000000000000003000000000heroic-gogdl-1.1.2/.github/workflows/build.yamlname: Build binaries
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build:
    strategy:
      fail-fast: false
      max-parallel: 3
      matrix:
        os: [ubuntu-20.04, macos-12, macos-14, windows-2022]
    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.9"

      - name: Install pyinstaller and dependencies
        run: pip3 install --upgrade pyinstaller requests

      - name: Set strip on Linux and Mac
        id: strip
        run: echo "option=--strip" >> $GITHUB_OUTPUT
        if: runner.os != 'Windows'

      - name: Build
        run: pyinstaller
          --onefile
          --name gogdl
          ${{ steps.strip.outputs.option }}
          gogdl/cli.py
        env:
          PYTHONOPTIMIZE: 1

      - uses: actions/upload-artifact@v4
        with:
          name: gogdl-${{ matrix.os }}
          path: dist/*
07070100000003000081A400000000000000000000000166E0651E00000028000000000000000000000000000000000000001E00000000heroic-gogdl-1.1.2/.gitignorebuild
dist
*.egg-info
*.spec
__pycache__07070100000004000081A400000000000000000000000166E0651E0000894D000000000000000000000000000000000000001B00000000heroic-gogdl-1.1.2/LICENSE                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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 <https://www.gnu.org/licenses/>.

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:

    <program>  Copyright (C) <year>  <name of author>
    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
<https://www.gnu.org/licenses/>.

  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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
07070100000005000081ED00000000000000000000000166E0651E00000621000000000000000000000000000000000000001D00000000heroic-gogdl-1.1.2/README.md# heroic-gogdl

GOG download module for [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)

## Important note

This is **not** user friendly cli, it's meant to be used by some other application wanting to download game files, manage cloud saves or conveniently launch the game

## Contributing

The only python dependency needed at this moment is `requests`

You can install it using your Linux distribution package manager or using pip

```
pip install requests
```

To run a code locally, use `bin/gogdl` script, which is a convenient python wrapper

gogdl now manages authentication, so it no longer needs --token parameter, although you now need to provide a path to json file where the tokens will be stored
Heroic uses `$XDG_CONFIG_HOME/heroic/gog_store/auth.json`

Here is the command to pull the source code

```
git clone https://github.com/Heroic-Games-Launcher/heroic-gogdl
cd heroic-gogdl
./bin/gogdl --help
```

If you have any questions ask on our [Discord](https://discord.com/invite/rHJ2uqdquK) or through GitHub issue

## Building PyInstaller executable

If you wish to test the gogdl in Heroic flatpak you likely need to build `gogdl` executable using pyinstaller

- Get pyinstaller

```
pip install pyinstaller
```

- Build the binary (assuming you are in heroic-gogdl direcory)

```
pyinstaller --onefile --name gogdl gogdl/cli.py
```

## Great resources about GOG API

- https://github.com/Lariaa/GameLauncherResearch/wiki/
- https://github.com/Sude-/lgogdownloader
- https://gogapidocs.readthedocs.io/en/latest/
07070100000006000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000001700000000heroic-gogdl-1.1.2/bin07070100000007000081ED00000000000000000000000166E0651E0000006E000000000000000000000000000000000000001D00000000heroic-gogdl-1.1.2/bin/gogdl#!/bin/sh
cd "$(dirname $(readlink -f "$0"))/.."
/usr/bin/env python3 -m gogdl.cli "$@"
STATUS=$?
exit $STATUS07070100000008000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000001900000000heroic-gogdl-1.1.2/gogdl07070100000009000081A400000000000000000000000166E0651E00000150000000000000000000000000000000000000002500000000heroic-gogdl-1.1.2/gogdl/__init__.py#  _                    _                                 _ _
# | |__   ___ _ __ ___ (_) ___       __ _  ___   __ _  __| | |
# | '_ \ / _ \ '__/ _ \| |/ __|____ / _` |/ _ \ / _` |/ _` | |
# | | | |  __/ | | (_) | | (_|_____| (_| | (_) | (_| | (_| | |
# |_| |_|\___|_|  \___/|_|\___|     \__, |\___/ \__, |\__,_|_|




version = "1.1.2"
0707010000000A000081ED00000000000000000000000166E0651E00000ECD000000000000000000000000000000000000002000000000heroic-gogdl-1.1.2/gogdl/api.pyimport logging
import time
import requests
import json
from multiprocessing import cpu_count
from gogdl.dl import dl_utils
from gogdl import version
import gogdl.constants as constants
from gogdl import version



class ApiHandler:
    def __init__(self, auth_manager):
        self.auth_manager = auth_manager
        self.logger = logging.getLogger("API")
        self.session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_maxsize=cpu_count())
        self.session.mount("https://", adapter)
        self.session.headers = {
            'User-Agent': f'gogdl/{version} (Heroic Games Launcher)'
        }
        credentials = self.auth_manager.get_credentials()
        if credentials:
            token = credentials["access_token"]
            self.session.headers["Authorization"] = f"Bearer {token}"
        self.owned = []

        self.endpoints = dict()  # Map of secure link endpoints
        self.working_on_ids = list()  # List of products we are waiting for to complete getting the secure link

    def get_item_data(self, id, expanded=None):
        if expanded is None:
            expanded = []
        self.logger.info(f"Getting info from products endpoint for id: {id}")
        url = f'{constants.GOG_API}/products/{id}'
        expanded_arg = '?expand='
        if len(expanded) > 0:
            expanded_arg += ','.join(expanded)
            url += expanded_arg
        response = self.session.get(url)
        self.logger.debug(url)
        if response.ok:
            return response.json()
        else:
            self.logger.error(f"Request failed {response}")

    def get_game_details(self, id):
        url = f'{constants.GOG_EMBED}/account/gameDetails/{id}.json'
        response = self.session.get(url)
        self.logger.debug(url)
        if response.ok:
            return response.json()

    def get_dependencies_repo(self, depot_version=2):
        self.logger.info("Getting Dependencies repository")
        url = constants.DEPENDENCIES_URL if depot_version == 2 else constants.DEPENDENCIES_V1_URL
        response = self.session.get(url)
        if not response.ok:
            return None

        json_data = json.loads(response.content)
        return json_data

    def does_user_own(self, id):
        if not self.owned:
            response = self.session.get(f'{constants.GOG_EMBED}/user/data/games')
            self.owned = response.json()['owned']
        for owned in self.owned:
            if str(owned) == str(id):
                return True
        return False

    def __obtain_secure_link(self, id, path, generation):
        self.endpoints[id] = None
        if self.auth_manager.is_credential_expired():
            if self.auth_manager.refresh_credentials():
                credentials = self.auth_manager.get_credentials()
                token = credentials["access_token"]
                self.session.headers["Authorization"] = f"Bearer {token}"
        return dl_utils.get_secure_link(self, path, id, generation, self.logger)

    def get_new_secure_link(self, id, path="/", generation=2):
        if id not in self.working_on_ids:
            self.working_on_ids.append(id)
            new = self.__obtain_secure_link(id, path, generation)
            self.endpoints[id] = new
            self.working_on_ids.remove(id)
            return new
        else:
            while True:
                if self.endpoints.get(id):
                    return self.endpoints[id]

    def get_secure_link(self, id):
        if self.endpoints.get(id):
            return self.endpoints.get(id)
        else:
            while True:  # Await for other thread to fetch the data
                if self.endpoints.get(id):
                    return self.endpoints.get(id)

                time.sleep(0.2)
0707010000000B000081ED00000000000000000000000166E0651E00002072000000000000000000000000000000000000002100000000heroic-gogdl-1.1.2/gogdl/args.py# Initialize argparse module and return arguments
import argparse
from multiprocessing import cpu_count


def init_parser():
    parser = argparse.ArgumentParser(
        description="GOG downloader for Heroic Games Launcher"
    )

    parser.add_argument(
        "--version",
        "-v",
        dest="display_version",
        action="store_true",
        help="Display GOGDL version",
    )

    parser.add_argument("--auth-config-path", dest="auth_config_path",
                        help="Path to json file where tokens will be stored", required=True)

    subparsers = parser.add_subparsers(dest="command")

    import_parser = subparsers.add_parser(
        "import", help="Show data about game in the specified path"
    )
    import_parser.add_argument("path")

    # REDIST DOWNLOAD

    redist_download_parser = subparsers.add_parser("redist", aliases=["dependencies"],
                                                   help="Download specified dependencies to provided location")

    redist_download_parser.add_argument("--ids", help="Coma separated ids")
    redist_download_parser.add_argument("--path", help="Location where to download the files")
    redist_download_parser.add_argument("--print-manifest", action="store_true", help="Prints manifest to stdout and exits")
    redist_download_parser.add_argument(
        "--max-workers",
        dest="workers_count",
        default=cpu_count(),
        help="Specify number of worker threads, by default number of CPU threads",
    )


    # AUTH

    auth_parser = subparsers.add_parser("auth", help="Manage authorization")
    auth_parser.add_argument("--client-id", dest="client_id")
    auth_parser.add_argument("--client-secret", dest="client_secret")
    auth_parser.add_argument("--code", dest="authorization_code",
                             help="Pass authorization code (use for login), when passed client-id and secret are ignored")

    # DOWNLOAD

    download_parser = subparsers.add_parser(
        "download", aliases=["repair", "update"], help="Download/update/repair game"
    )
    download_parser.add_argument("id", help="Game id")
    download_parser.add_argument("--lang", "-l", help="Specify game language")
    download_parser.add_argument(
        "--build", "-b", dest="build", help="Specify buildId"
    )
    download_parser.add_argument(
        "--path", "-p", dest="path", help="Specify download path", required=True
    )
    download_parser.add_argument("--support", dest="support_path", help="Specify path where support files should be stored, by default they are put into game dir")
    download_parser.add_argument(
        "--platform",
        "--os",
        dest="platform",
        help="Target opearting system",
        choices=["windows", "osx", "linux"],
    )
    download_parser.add_argument(
        "--with-dlcs", dest="dlcs", action="store_true", help="Should download all dlcs"
    )
    download_parser.add_argument(
        "--skip-dlcs", dest="dlcs", action="store_false", help="Should skip all dlcs"
    )
    download_parser.add_argument(
        "--dlcs",
        dest="dlcs_list",
        default=[],
        help="List of dlc ids to download (separated by coma)",
    )
    download_parser.add_argument(
        "--dlc-only", dest="dlc_only", action="store_true", help="Download only DLC"
    )
    download_parser.add_argument("--branch", help="Choose build branch to use")
    download_parser.add_argument("--password", help="Password to access other branches")
    download_parser.add_argument("--force-gen", choices=["1", "2"], dest="force_generation", help="Force specific manifest generation (FOR DEBUGGING)")
    download_parser.add_argument(
        "--max-workers",
        dest="workers_count",
        default=cpu_count(),
        help="Specify number of worker threads, by default number of CPU threads",
    )

    # SIZE CALCULATING, AND OTHER MANIFEST INFO

    calculate_size_parser = subparsers.add_parser(
        "info", help="Calculates estimated download size and list of DLCs"
    )

    calculate_size_parser.add_argument(
        "--with-dlcs",
        dest="dlcs",
        action="store_true",
        help="Should download all dlcs",
    )
    calculate_size_parser.add_argument(
        "--skip-dlcs", dest="dlcs", action="store_false", help="Should skip all dlcs"
    )
    calculate_size_parser.add_argument(
        "--dlcs",
        dest="dlcs_list",
        help="Coma separated list of dlc ids to download",
    )
    calculate_size_parser.add_argument(
        "--dlc-only", dest="dlc_only", action="store_true", help="Download only DLC"
    )
    calculate_size_parser.add_argument("id")
    calculate_size_parser.add_argument(
        "--platform",
        "--os",
        dest="platform",
        help="Target opearting system",
        choices=["windows", "osx", "linux"],
    )
    calculate_size_parser.add_argument(
        "--build", "-b", dest="build", help="Specify buildId"
    )
    calculate_size_parser.add_argument("--lang", "-l", help="Specify game language")
    calculate_size_parser.add_argument("--branch", help="Choose build branch to use")
    calculate_size_parser.add_argument("--password", help="Password to access other branches")
    calculate_size_parser.add_argument("--force-gen", choices=["1", "2"], dest="force_generation", help="Force specific manifest generation (FOR DEBUGGING)")
    calculate_size_parser.add_argument(
        "--max-workers",
        dest="workers_count",
        default=cpu_count(),
        help="Specify number of worker threads, by default number of CPU threads",
    )

    # LAUNCH

    launch_parser = subparsers.add_parser(
        "launch", help="Launch the game in specified path", add_help=False
    )
    launch_parser.add_argument("path")
    launch_parser.add_argument("id")
    launch_parser.add_argument(
        "--platform",
        "--os",
        dest="platform",
        help="Target opearting system",
        choices=["windows", "osx", "linux"],
        required=True,
    )
    launch_parser.add_argument("--prefer-task", dest="preferred_task", default=None, help="Select playTask index to be run")
    launch_parser.add_argument(
        "--no-wine", action="store_true", dest="dont_use_wine", default=False
    )
    launch_parser.add_argument("--wine", dest="wine", help="Specify wine bin path")
    launch_parser.add_argument("--wine-prefix", dest="wine_prefix")
    launch_parser.add_argument("--wrapper", dest="wrapper")
    launch_parser.add_argument(
        "--override-exe", dest="override_exe", help="Override executable to be run"
    )

    # SAVES

    save_parser = subparsers.add_parser("save-sync", help="Sync game saves")
    save_parser.add_argument("path", help="Path to sync files")
    save_parser.add_argument("id", help="Game id")
    save_parser.add_argument(
        "--ts", dest="timestamp", help="Last sync timestamp", required=True
    )
    save_parser.add_argument("--name", dest="dirname", default="__default")
    save_parser.add_argument(
        "--skip-download", dest="prefered_action", action="store_const", const="upload"
    )
    save_parser.add_argument(
        "--skip-upload", dest="prefered_action", action="store_const", const="download"
    )
    save_parser.add_argument(
        "--force-upload",
        dest="prefered_action",
        action="store_const",
        const="forceupload",
    )
    save_parser.add_argument(
        "--force-download",
        dest="prefered_action",
        action="store_const",
        const="forcedownload",
    )

    save_parser.add_argument(
        "--os",
        "--platform",
        dest="platform",
        help="Target opearting system",
        choices=["windows", "osx", "linux"],
        required=True,
    )

    # SAVES CLEAR

    clear_parser = subparsers.add_parser("save-clear", help="Clear cloud game saves")
    clear_parser.add_argument("path", help="Path to sync files")
    clear_parser.add_argument("id", help="Game id")
    clear_parser.add_argument("--name", dest="dirname", default="__default")

    clear_parser.add_argument(
        "--os",
        "--platform",
        dest="platform",
        help="Target opearting system",
        choices=["windows", "osx", "linux"],
        required=True,
    )


    return parser.parse_known_args()
0707010000000C000081A400000000000000000000000166E0651E0000137C000000000000000000000000000000000000002100000000heroic-gogdl-1.1.2/gogdl/auth.py# Manages authorization
# with ability to have multiple tokens (will come in handy in the future)
import json
import logging
import os.path
import requests
import time
from gogdl import version

CODE_URL = "https://auth.gog.com/token?client_id=46899977096215655&client_secret=9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&code="
CLIENT_ID = "46899977096215655"
CLIENT_SECRET = "9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9"


class AuthorizationManager:
    def __init__(self, config_path):
        self.session = requests.session()
        self.logger = logging.getLogger("AUTH")

        self.config_path = config_path
        self.credentials_data = {}
        self.__read_config()

        self.session.headers.update(
            {"User-Agent": f"gogdl/{version} (Heroic Games Launcher)"}
        )

    def __read_config(self):
        if os.path.exists(self.config_path):
            with open(self.config_path, "r") as f:
                self.credentials_data = json.loads(f.read())
                f.close()

    def __write_config(self):
        with open(self.config_path, "w") as f:
            f.write(json.dumps(self.credentials_data))
            f.close()

    def get_credentials(self, client_id=None, client_secret=None):
        """
        Reads data from config and returns it
        :param client_id:
        :return: dict with credentials or None if not present
        """
        if not client_id:
            client_id = CLIENT_ID

        if not client_secret:
            client_secret = CLIENT_SECRET

        credentials = self.credentials_data.get(client_id)
        if not credentials:
            if client_id != CLIENT_ID and client_secret != CLIENT_SECRET:
                if self.refresh_credentials(client_id, client_secret):
                    return self.credentials_data.get(client_id)
            return None

        if self.is_credential_expired(client_id):
            if self.refresh_credentials(client_id, client_secret):
                credentials = self.credentials_data.get(client_id)
            else:
                return None
        return credentials

    def is_credential_expired(self, client_id=None) -> bool:
        """
        Checks if provided client_id credential is expired
        If the credential with this client_id doesn't exist raises Exception
        :param client_id:
        :return: whether credentials are expired
        """
        if not client_id:
            client_id = CLIENT_ID
        credentials = self.credentials_data.get(client_id)

        if not credentials:
            raise ValueError("Credential doesn't exist")

        return time.time() >= credentials["loginTime"] + credentials["expires_in"]

    def refresh_credentials(self, client_id=None, client_secret=None) -> bool:
        """
        Refreshes credentials and saves them to config
        Can be used to obtain credentials for game scopes
        :param client_id:
        :param client_secret:
        :return: bool if operation was success
        """
        no_new_session = False
        if client_id and client_secret:
            no_new_session = True
        if not client_id:
            client_id = CLIENT_ID
        if not client_secret:
            client_secret = CLIENT_SECRET

        credentials = self.credentials_data.get(CLIENT_ID)
        refresh_token = credentials["refresh_token"]

        url = f"https://auth.gog.com/token?client_id={client_id}&client_secret={client_secret}&grant_type=refresh_token&refresh_token={refresh_token}"

        if no_new_session:
            url = url + "&without_new_session=1"

        try:
            response = self.session.get(url, timeout=10)
        except (requests.ConnectionError, requests.Timeout):
            self.logger.error("Failed to refresh credentials")
            return False
        if not response.ok:
            return False
        data = response.json()
        data["loginTime"] = time.time()
        self.credentials_data.update({client_id: data})
        self.__write_config()
        return True

    def handle_cli(self, arguments, unknown_arguments):
        self.logger.debug("Handling cli")

        if arguments.authorization_code:
            response = self.session.get(CODE_URL + arguments.authorization_code)

            if not response.ok:
                print(json.dumps({"error": True}))
                return
            data = response.json()
            data.update({"loginTime": time.time()})

            self.credentials_data.update({CLIENT_ID: data})
            self.__write_config()

            print(json.dumps(data))
            return

        client_id = arguments.client_id or CLIENT_ID
        client_secret = arguments.client_secret or CLIENT_SECRET

        credentials = self.get_credentials(client_id, client_secret)

        print(json.dumps(credentials))
0707010000000D000081ED00000000000000000000000166E0651E00000916000000000000000000000000000000000000002000000000heroic-gogdl-1.1.2/gogdl/cli.py#!/usr/bin/env python3
from multiprocessing import freeze_support
import gogdl.args as args
from gogdl.dl.managers import manager
from gogdl.dl.managers import dependencies
import gogdl.api as api
import gogdl.imports as imports
import gogdl.launch as launch
import gogdl.saves as saves
import gogdl.auth as auth
from gogdl import version as gogdl_version
import logging



def display_version():
    print(f"{gogdl_version}")


def main():
    arguments, unknown_args = args.init_parser()
    level = logging.INFO
    if '-d' in unknown_args or '--debug' in unknown_args:
        level = logging.DEBUG
    logging.basicConfig(format="[%(name)s] %(levelname)s: %(message)s", level=level)
    logger = logging.getLogger("MAIN")
    logger.debug(arguments)
    if arguments.display_version:
        display_version()
        return
    if not arguments.command:
        print("No command provided!")
        return
    authorization_manager = auth.AuthorizationManager(arguments.auth_config_path)
    api_handler = api.ApiHandler(authorization_manager)
    clouds_storage_manager = saves.CloudStorageManager(api_handler, authorization_manager)

    switcher = {}
    if arguments.command in ["download", "repair", "update", "info"]:
        download_manager = manager.Manager(arguments, unknown_args, api_handler)
        switcher = {
            "download": download_manager.download,
            "repair": download_manager.download,
            "update": download_manager.download,
            "info": download_manager.calculate_download_size,
        }
    elif arguments.command in ["redist", "dependencies"]:
        dependencies_handler = dependencies.DependenciesManager(arguments.ids.split(","), arguments.path, arguments.workers_count, api_handler, print_manifest=arguments.print_manifest)
        if not arguments.print_manifest:
            dependencies_handler.get()
    else:
        switcher = {
            "import": imports.get_info,
            "launch": launch.launch,
            "save-sync": clouds_storage_manager.sync,
            "save-clear": clouds_storage_manager.clear,
            "auth": authorization_manager.handle_cli
        }

    function = switcher.get(arguments.command)
    if function:
        function(arguments, unknown_args)


if __name__ == "__main__":
    freeze_support()
    main()
0707010000000E000081ED00000000000000000000000166E0651E00000429000000000000000000000000000000000000002600000000heroic-gogdl-1.1.2/gogdl/constants.pyimport os
from sys import platform

GOG_CDN = "https://gog-cdn-fastly.gog.com"
GOG_CONTENT_SYSTEM = "https://content-system.gog.com"
GOG_EMBED = "https://embed.gog.com"
GOG_AUTH = "https://auth.gog.com"
GOG_API = "https://api.gog.com"
GOG_CLOUDSTORAGE = "https://cloudstorage.gog.com"
DEPENDENCIES_URL = "https://content-system.gog.com/dependencies/repository?generation=2"
DEPENDENCIES_V1_URL = "https://content-system.gog.com/redists/repository"

NON_NATIVE_SEP = "\\" if os.sep == "/" else "/"

if platform == 'linux':
    CONFIG_DIR = os.path.join(
        os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), 'heroic_gogdl'
    )
elif platform == 'win32':
    CONFIG_DIR = os.path.join(
        os.getenv("APPDATA"), 'heroic_gogdl'
    )
elif platform == 'darwin':
    CONFIG_DIR = os.path.join(
        os.path.expanduser("~/Library"), "Application Support", "heroic_gogdl"
    )

if os.getenv("GOGDL_CONFIG_PATH"):
    CONFIG_DIR = os.path.join(os.getenv("GOGDL_CONFIG_PATH"), "heroic_gogdl")

MANIFESTS_DIR = os.path.join(CONFIG_DIR, "manifests")
0707010000000F000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000001C00000000heroic-gogdl-1.1.2/gogdl/dl07070100000010000081A400000000000000000000000166E0651E00000000000000000000000000000000000000000000002800000000heroic-gogdl-1.1.2/gogdl/dl/__init__.py07070100000011000081ED00000000000000000000000166E0651E000013F1000000000000000000000000000000000000002800000000heroic-gogdl-1.1.2/gogdl/dl/dl_utils.pyimport json
import zlib
import os
import gogdl.constants as constants
from gogdl.dl.objects import v1, v2
import shutil
import time
import requests
from sys import exit, platform

PATH_SEPARATOR = os.sep
TIMEOUT = 10


def get_json(api_handler, url):
    x = api_handler.session.get(url, headers={"Accept": "application/json"})
    if not x.ok:
        return
    return x.json()


def get_zlib_encoded(api_handler, url):
    retries = 5
    while retries > 0:
        try:
            x = api_handler.session.get(url, timeout=TIMEOUT)
            if not x.ok:
                return None, None
            try:
                decompressed = json.loads(zlib.decompress(x.content, 15))
            except zlib.error:
                return x.json(), x.headers
            return decompressed, x.headers
        except Exception:
            time.sleep(2)
            retries-=1
    return None, None


def prepare_location(path, logger=None):
    os.makedirs(path, exist_ok=True)
    if logger:
        logger.debug(f"Created directory {path}")


# V1 Compatible
def galaxy_path(manifest: str):
    galaxy_path = manifest
    if galaxy_path.find("/") == -1:
        galaxy_path = manifest[0:2] + "/" + manifest[2:4] + "/" + galaxy_path
    return galaxy_path


def get_secure_link(api_handler, path, gameId, generation=2, logger=None, root=None):
    url = ""
    if generation == 2:
        url = f"{constants.GOG_CONTENT_SYSTEM}/products/{gameId}/secure_link?_version=2&generation=2&path={path}"
    elif generation == 1:
        url = f"{constants.GOG_CONTENT_SYSTEM}/products/{gameId}/secure_link?_version=2&type=depot&path={path}"
    if root:
        url += f"&root={root}"

    try:
        r = requests.get(url, headers=api_handler.session.headers, timeout=TIMEOUT)
    except BaseException as exception:
        if logger:
            logger.info(exception)
        time.sleep(0.2)
        return get_secure_link(api_handler, path, gameId, generation, logger)

    if r.status_code != 200:
        if logger:
            logger.info("invalid secure link response")
        time.sleep(0.2)
        return get_secure_link(api_handler, path, gameId, generation, logger)

    js = r.json()

    return js['urls']

def get_dependency_link(api_handler):
    data = get_json(
        api_handler,
        f"{constants.GOG_CONTENT_SYSTEM}/open_link?generation=2&_version=2&path=/dependencies/store/",
    )
    if not data:
        return None
    return data["urls"]


def merge_url_with_params(url, parameters):
    for key in parameters.keys():
        url = url.replace("{" + key + "}", str(parameters[key]))
        if not url:
            print(f"Error ocurred getting a secure link: {url}")
    return url


def parent_dir(path: str):
    return os.path.split(path)[0]


def calculate_sum(path, function, read_speed_function=None):
    with open(path, "rb") as f:
        calculate = function()
        while True:
            chunk = f.read(16 * 1024)
            if not chunk:
                break
            if read_speed_function:
                read_speed_function(len(chunk))
            calculate.update(chunk)

        return calculate.hexdigest()


def get_readable_size(size):
    power = 2 ** 10
    n = 0
    power_labels = {0: "", 1: "K", 2: "M", 3: "G"}
    while size > power:
        size /= power
        n += 1
    return size, power_labels[n] + "B"


def check_free_space(size: int, path: str):
    if not os.path.exists(path):
        os.makedirs(path, exist_ok=True)
    _, _, available_space = shutil.disk_usage(path)

    return size < available_space


def get_range_header(offset, size):
    from_value = offset
    to_value = (int(offset) + int(size)) - 1
    return f"bytes={from_value}-{to_value}"

# Creates appropriate Manifest class based on provided meta from json
def create_manifest_class(meta: dict, api_handler):
    version = meta.get("version") 
    if version == 1:
        return v1.Manifest.from_json(meta, api_handler)
    else:
        return v2.Manifest.from_json(meta, api_handler)

def get_case_insensitive_name(path):
    if platform == "win32" or os.path.exists(path):
        return path
    root = path
    # Find existing directory
    while not os.path.exists(root):
        root = os.path.split(root)[0]
    
    if not root[len(root) - 1] in ["/", "\\"]:
        root = root + os.sep
    # Separate unknown path from existing one
    s_working_dir = path.replace(root, "").split(os.sep)
    paths_to_find = len(s_working_dir)
    paths_found = 0
    for directory in s_working_dir:
        if not os.path.exists(root):
            break
        dir_list = os.listdir(root)
        found = False
        for existing_dir in dir_list:
            if existing_dir.lower() == directory.lower():
                root = os.path.join(root, existing_dir)
                paths_found += 1
                found = True
        if not found:
            root = os.path.join(root, directory)
            paths_found += 1

    if paths_to_find != paths_found:
        root = os.path.join(root, os.sep.join(s_working_dir[paths_found:]))
    return root

07070100000012000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000002500000000heroic-gogdl-1.1.2/gogdl/dl/managers07070100000013000081A400000000000000000000000166E0651E000018F3000000000000000000000000000000000000003500000000heroic-gogdl-1.1.2/gogdl/dl/managers/dependencies.pyfrom sys import exit
import logging
import os
import json
from typing import Optional
from gogdl.dl import dl_utils
import gogdl.constants as constants
from gogdl.dl.managers.task_executor import ExecutingManager
from gogdl.dl.objects import v2
from gogdl.dl.objects.generic import BaseDiff


def get_depot_list(manifest, product_id=None):
    download_list = list()
    for item in manifest["depot"]["items"]:
        if item["type"] == "DepotFile":
            download_list.append(v2.DepotFile(item, product_id))
    return download_list


# Looks like we can use V2 dependencies for V1 games too WOAH
# We are doing that obviously 
class DependenciesManager:
    def __init__(
        self, ids, path, workers_count, api_handler, print_manifest=False, download_game_deps_only=False
    ):
        self.api = api_handler

        self.logger = logging.getLogger("REDIST")

        self.path = path
        self.installed_manifest = os.path.join(self.path, '.gogdl-redist-manifest')
        self.workers_count = int(workers_count)
        self.build = self.api.get_dependencies_repo()
        self.repository = dl_utils.get_zlib_encoded(self.api, self.build['repository_manifest'])[0] or {}
        # Put version for easier serialization
        self.repository['build_id'] = self.build['build_id']

        self.ids = ids
        self.download_game_deps_only = download_game_deps_only  # Basically skip all redist with path starting with __redist
        if self.repository and print_manifest:
            print(json.dumps(self.repository))

    def get_files_for_depot_manifest(self, manifest):
        url = f'{constants.GOG_CDN}/content-system/v2/dependencies/meta/{dl_utils.galaxy_path(manifest)}'
        manifest = dl_utils.get_zlib_encoded(self.api, url)[0]

        return get_depot_list(manifest, 'redist')


    def get(self, return_files=False):
        old_depots = []
        new_depots = []
        if not self.ids:
            return []
        installed = set()

        # This will be always None for redist writen in game dir
        existing_manifest = None
        if os.path.exists(self.installed_manifest):
            try:
                with open(self.installed_manifest, 'r') as f:
                    existing_manifest = json.load(f)
            except Exception:
                existing_manifest = None
                pass
            else:
                if 'depots' in existing_manifest and 'build_id' in existing_manifest:
                    already_installed = existing_manifest.get('HGLInstalled') or []
                    for depot in existing_manifest["depots"]:
                        if depot["dependencyId"] in already_installed:
                            old_depots.append(depot)

        for depot in self.repository["depots"]:
            if depot["dependencyId"] in self.ids:
                # By default we want to download all redist beginning
                # with redist (game installation runs installation of the game's ones)
                should_download = depot["executable"]["path"].startswith("__redist")
                
                # If we want to download redist located in game dir we flip the boolean
                if self.download_game_deps_only:
                    should_download = not should_download

                if should_download:
                    installed.add(depot['dependencyId'])
                    new_depots.append(depot)

        new_files = []
        old_files = []

        # Collect files for each redistributable
        for depot in new_depots:
            new_files += self.get_files_for_depot_manifest(depot["manifest"])

        for depot in old_depots:
            old_files += self.get_files_for_depot_manifest(depot["manifest"])

        if return_files:
            return new_files


        diff = DependenciesDiff.compare(new_files, old_files)

        if not len(diff.changed) and not len(diff.deleted) and not len(diff.new):
            self.logger.info("Nothing to do")
            self._write_manifest(installed)
            return

        secure_link = dl_utils.get_dependency_link(self.api) # This should never expire
        executor = ExecutingManager(self.api, self.workers_count, self.path, os.path.join(self.path, 'gog-support'), diff, {'redist': secure_link})
        success = executor.setup()
        if not success:
            print('Unable to proceed, Not enough disk space')
            exit(2)
        cancelled = executor.run()

        if cancelled:
            return

        self._write_manifest(installed)

    def _write_manifest(self, installed: set):
        repository = self.repository
        repository['HGLInstalled'] = list(installed)
        with open(self.installed_manifest, 'w') as f:
            json.dump(repository, f)


class DependenciesDiff(BaseDiff):
    def __init__(self):
        super().__init__()

    @classmethod
    def compare(cls, new_files: list, old_files: Optional[list]):
        comparison = cls()
        
        if not old_files:
            comparison.new = new_files
            return comparison

        new_files_paths = dict()
        for file in new_files:
            new_files_paths.update({file.path.lower(): file})

        old_files_paths = dict()
        for file in old_files:
            old_files_paths.update({file.path.lower(): file})
        
        for old_file in old_files_paths.values():
            if not new_files_paths.get(old_file.path.lower()):
                comparison.deleted.append(old_file)

        for new_file in new_files_paths.values():
            old_file = old_files_paths.get(new_file.path.lower())
            if not old_file:
                comparison.new.append(new_file)
            else:
                if len(new_file.chunks) == 1 and len(old_file.chunks) == 1:
                    if new_file.chunks[0]["md5"] != old_file.chunks[0]["md5"]:
                        comparison.changed.append(new_file)
                else:
                    if (new_file.md5 and old_file.md5 and new_file.md5 != old_file.md5) or (new_file.sha256 and old_file.sha256 != new_file.sha256):
                        comparison.changed.append(v2.FileDiff.compare(new_file, old_file))
                    elif len(new_file.chunks) != len(old_file.chunks):
                        comparison.changed.append(v2.FileDiff.compare(new_file, old_file))
        return comparison 

07070100000014000081A400000000000000000000000166E0651E00002D02000000000000000000000000000000000000002E00000000heroic-gogdl-1.1.2/gogdl/dl/managers/linux.py# Manage downloading of linux native games using new zip method based on Range headers
import json
import logging
import hashlib
import os.path
import stat
from concurrent.futures import ThreadPoolExecutor, as_completed
from zlib import crc32
from gogdl.dl import dl_utils
from gogdl.dl.managers.task_executor import ExecutingManager
from gogdl.dl.objects.generic import BaseDiff
from gogdl.dl.objects.v2 import DepotLink
from gogdl.dl.workers import linux as linux_worker
from gogdl.dl.objects import linux
from gogdl import constants


def get_folder_name_from_windows_manifest(api_handler, id):
    builds = dl_utils.get_json(
        api_handler,
        f"{constants.GOG_CONTENT_SYSTEM}/products/{id}/os/windows/builds?generation=2",
    )

    url = builds["items"][0]["link"]
    meta, headers = dl_utils.get_zlib_encoded(api_handler, url)
    install_dir = (
        meta["installDirectory"]
        if builds["items"][0]["generation"] == 2
        else meta["product"]["installDirectory"]
    )
    return install_dir


class Manager:
    def __init__(self, generic_manager):
        self.game_id = generic_manager.game_id
        self.arguments = generic_manager.arguments
        self.unknown_arguments = generic_manager.unknown_arguments
        self.is_verifying = generic_manager.is_verifying

        self.api_handler = generic_manager.api_handler
        self.allowed_threads = generic_manager.allowed_threads
        self.folder_name = get_folder_name_from_windows_manifest(self.api_handler, self.game_id)

        if "path" in self.arguments:
            self.path = self.arguments.path
            if generic_manager.should_append_folder_name:
                self.path = os.path.join(self.path, self.folder_name)
        else:
            self.path = ""

        self.lang = self.arguments.lang
        self.dlcs_should_be_downloaded = self.arguments.dlcs
        if self.arguments.dlcs_list:
            self.dlcs_list = self.arguments.dlcs_list.split(",")
        else:
            self.dlcs_list = []
        self.dlc_only = self.arguments.dlc_only

        self.logger = logging.getLogger("LINUX")
        self.logger.info("Initialized Linux Download Manager")

        self.game_data = None

        self.languages_codes = list()
        self.downlink = None
        self.game_files = list()

        self.installer_handlers = list()

    @staticmethod
    def filter_linux_installers(installers):
        return [installer for installer in installers if installer["os"] == "linux"]

    def find_matching_installer(self, installers):
        if len(installers) == 1:
            return installers[0]
        for installer in installers:
            if installer["language"] == self.lang:
                return installer

        # English installers should be multilanguage ready
        for installer in installers:
            if installer["language"] == "en":
                return installer

        return None

    def setup(self):
        self.game_data = self.api_handler.get_item_data(self.game_id, expanded=['downloads', 'expanded_dlcs'])

        # Filter linux installers
        game_installers = self.filter_linux_installers(self.game_data["downloads"]["installers"])

        self.languages_codes = [installer["language"] for installer in game_installers]

        self.game_installer = self.find_matching_installer(game_installers)

        if not self.dlc_only:
            installer_data = dl_utils.get_json(self.api_handler, self.game_installer["files"][0]["downlink"])
            game_install_handler = linux.InstallerHandler(installer_data["downlink"],self.game_id,self.api_handler.session)
            self.installer_handlers.append(game_install_handler)

        # Create dlc installer handlers
        if self.dlcs_should_be_downloaded:
            for dlc in self.game_data["expanded_dlcs"]:
                if self.dlcs_should_be_downloaded and self.api_handler.does_user_own(dlc["id"]):
                    if self.dlcs_list and str(dlc["id"]) not in self.dlcs_list:
                        continue

                    linux_installers = self.filter_linux_installers(dlc["downloads"]["installers"])
                    installer = self.find_matching_installer(linux_installers)

                    if installer is None:
                        self.logger.error(
                            dlc["title"] + " - Does not have a linux installer"
                        )
                        continue

                    installer_data = dl_utils.get_json(self.api_handler, installer["files"][0]["downlink"])

                    install_handler = linux.InstallerHandler(installer_data["downlink"],
                                                             str(dlc["id"]),
                                                             self.api_handler.session)

                    self.installer_handlers.append(install_handler)

        pool = ThreadPoolExecutor(self.allowed_threads)
        futures = []
        for handler in self.installer_handlers:
            futures.append(pool.submit(handler.setup))

        for future in as_completed(futures):
            if future.cancelled():
                break

    def calculate_download_sizes(self):
        download_size = 0
        size = 0

        for handler in self.installer_handlers:
            for file in handler.central_directory.files:
                if not file.file_name.startswith("data/noarch") or file.file_name.endswith("/"):
                    continue
                size += file.uncompressed_size
                download_size += file.compressed_size
        return download_size, size

    def get_owned_dlcs(self):
        dlcs = list()
        for dlc in self.game_data["expanded_dlcs"]:
            if self.api_handler.does_user_own(dlc["id"]):
                if not dlc["downloads"]["installers"]:
                    continue
                dlc_languages = [installer["language"] for installer in
                                 self.filter_linux_installers(dlc["downloads"]["installers"])]
                dlcs.append({"title": dlc["title"], "id": dlc["id"], "languages": [dlc_languages]})
        return dlcs

    def get_download_size(self):
        self.setup()

        dlcs = self.get_owned_dlcs()

        download_size, disk_size = self.calculate_download_sizes()

        response = {
            "download_size": download_size,
            "disk_size": disk_size,
            "dlcs": dlcs,
            "languages": self.languages_codes,
            "folder_name": self.folder_name,
            "dependencies": [],
            "versionName": self.game_installer["version"],
        }

        return response

    def download(self):
        self.setup()
        manifest_path = os.path.join(self.path, '.gogdl-linux-manifest')

        cd_files = dict()
        for handler in self.installer_handlers:
            for file in handler.central_directory.files:
                if not file.file_name.startswith("data/noarch") or file.file_name.endswith("/"):
                    continue
                cd_files.update({file.file_name: file})

        manifest_data = None
        if os.path.exists(manifest_path):
            with open(manifest_path, 'r') as f:
                manifest_data = json.load(f)

        new: list[linux.CentralDirectoryFile] = list()
        deleted: list[str] = list()
        if manifest_data and not self.is_verifying:
            manifest_files = dict()
            for file in manifest_data['files']:
                manifest_files.update({file['file_name']: file['crc32']})

            for file_name in manifest_files:
                if file_name in cd_files:
                    if cd_files[file_name].crc32 != manifest_files[file_name]:
                        new.append(cd_files[file_name])
                else:
                    deleted.append(file_name)
            
            for file_name in cd_files:
                if file_name not in manifest_files:
                    new.append(cd_files[file_name])

        else:
            new = list(cd_files.values())

        sources = dict()
        for handler in self.installer_handlers:
            sources.update({handler.product: handler.url})

        print("New/changed files", len(new))
        print("Deleted", len(deleted))
        print("Total files", len(cd_files))

        if self.is_verifying:
            self.logger.info("Verifying files")
            invalid = list()
            for file in new:
                path = file.file_name.replace("data/noarch", self.path)

                if not os.path.exists(path):
                    invalid.append(file)
                else:
                    if file.is_symlink():
                        continue
                    with open(path, 'rb') as fh:
                        sum = 0
                        while data := fh.read(1024*1024):
                            sum = crc32(data, sum)

                        if sum != file.crc32:
                            invalid.append(file)
            if not len(invalid):
                self.logger.info("All files look good")
                return
            new = invalid


        diff = BaseDiff()

        final_files = list()
        for i, file in enumerate(new):
            # Prepare file for download
            # Calculate data offsets 
            handler = None
            for ins in self.installer_handlers:
                if ins.product == file.product:
                    handler = ins
                    break

            if not handler:
                print("Orphan file found")
                continue
            
            data_start = handler.start_of_archive_index + file.file_data_offset
            c_size = file.compressed_size
            size = file.uncompressed_size
            method = file.compression_method
            checksum = file.crc32

            path = file.file_name.replace("data/noarch", self.path)
            if file.is_symlink():
                data = handler.get_bytes_from_file(from_b=data_start, size=c_size, add_archive_index=False)
                diff.links.append(DepotLink({"path": path, "target": os.path.normpath(os.path.join(dl_utils.parent_dir(path), data.decode()))}))
                continue
            file_permissions = int(bin(int.from_bytes(file.ext_file_attrs, "little"))[3:][:9])
            executable = (file_permissions & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) != 0
            final_files.append(linux.LinuxFile(file.product, path, method, data_start, c_size, size, checksum, executable))

        diff.new = final_files

        manager = ExecutingManager(self.api_handler, self.allowed_threads, self.path, None, diff, sources)  
        
        manager.setup()
        for file in deleted:
            path = file.replace('data/noarch', self.path)
            if os.path.exists(path):
                os.remove(path)
        cancelled = manager.run()

        if cancelled:
            return

        new_manifest = dict()

        gameinfo_file = os.path.join(self.path, 'gameinfo')
        if os.path.exists(gameinfo_file):
            checksum = hashlib.md5()
            with open(gameinfo_file, 'rb') as f:
                checksum.update(f.read())
            new_manifest['info_checksum'] = checksum.hexdigest()

        new_manifest['files'] = [f.as_dict() for f in cd_files.values()]

        
        os.makedirs(self.path, exist_ok=True)
        with open(manifest_path, 'w') as f:
            manifest_data = json.dump(new_manifest,f)
07070100000015000081A400000000000000000000000166E0651E00001372000000000000000000000000000000000000003000000000heroic-gogdl-1.1.2/gogdl/dl/managers/manager.pyfrom dataclasses import dataclass
from multiprocessing import cpu_count
from sys import exit
import os
import logging
import json

from gogdl import constants
from gogdl.dl.managers import linux, v1, v2

@dataclass
class UnsupportedPlatform(Exception):
    pass

class Manager:
    def __init__(self, arguments, unknown_arguments, api_handler):
        self.arguments = arguments
        self.unknown_arguments = unknown_arguments
        self.api_handler = api_handler

        self.platform = arguments.platform
        self.should_append_folder_name = self.arguments.command == "download"
        self.is_verifying = self.arguments.command == "repair"
        self.game_id = arguments.id
        self.branch = arguments.branch or None
        if "workers_count" in arguments:
            self.allowed_threads = int(arguments.workers_count)
        else:
            self.allowed_threads = cpu_count()

        self.logger = logging.getLogger("GENERIC DOWNLOAD_MANAGER")

        self.galaxy_api_data = None

        self.download_manager = None
        self.builds = None
        self.target_build = None

    def get_builds(self, build_platform):
        password = '' if not self.arguments.password else '&password=' + self.arguments.password
        generation = self.arguments.force_generation or "2"
        response = self.api_handler.session.get(
            f"{constants.GOG_CONTENT_SYSTEM}/products/{self.game_id}/os/{build_platform}/builds?&generation={generation}{password}"
        )

        if not response.ok:
            raise UnsupportedPlatform()
        data = response.json()

        if data['total_count'] == 0:
            raise UnsupportedPlatform()

        return data 

    def calculate_download_size(self, arguments, unknown_arguments):
        self.setup_download_manager()

        download_size_response = self.download_manager.get_download_size()
        download_size_response['builds'] = self.builds


        print(json.dumps(download_size_response))

    def download(self, arguments, unknown_arguments):
        self.setup_download_manager()

        self.download_manager.download()

    def setup_download_manager(self):
        # TODO: If content system for linux ever appears remove this if statement
        # But keep the one below so we have some sort of fallback
        # in case not all games were available in content system
        if self.platform == "linux":
            self.logger.info(
                "Platform is Linux, redirecting download to Linux Native installer manager"
            )

            self.download_manager = linux.Manager(self)

            return

        try:
            self.builds = self.get_builds(self.platform)
        except UnsupportedPlatform:
            if self.platform == "linux":
                self.logger.info(
                    "Platform is Linux, redirecting download to Linux Native installer manager"
                )

                self.download_manager = linux.Manager(self)

                return

            self.logger.error(f"Game doesn't support content system api, unable to proceed using platform {self.platform}")
            exit(1)

        # If Linux download ever progresses to this point, then it's time for some good party

        if len(self.builds["items"]) == 0:
            self.logger.error("No builds found") 
            exit(1)
        self.target_build = self.builds["items"][0]

        for build in self.builds["items"]:
            if build["branch"] == None:
                self.target_build = build
                break

        for build in self.builds["items"]:
            if build["branch"] == self.branch:
                self.target_build = build
                break

        if self.arguments.build:
            # Find build
            for build in self.builds["items"]:
                if build["build_id"] == self.arguments.build:
                    self.target_build = build
                    break
        self.logger.debug(f'Found build {self.target_build}')

        generation = self.target_build["generation"]

        if self.is_verifying:
            manifest_path = os.path.join(constants.MANIFESTS_DIR, self.game_id)
            if os.path.exists(manifest_path):
                with open(manifest_path, 'r') as f:
                    manifest_data = json.load(f)
                    generation = int(manifest_data['version'])

        # This code shouldn't run at all but it's here just in case GOG decides they will return different generation than requested one
        # Of course assuming they will ever change their content system generation (I highly doubt they will)
        if generation not in [1, 2]:
            raise Exception("Unsupported depot version please report this")

        self.logger.info(f"Depot version: {generation}")

        if generation == 1:
            self.download_manager = v1.Manager(self)
        elif generation == 2:
            self.download_manager = v2.Manager(self)
07070100000016000081A400000000000000000000000166E0651E000099B4000000000000000000000000000000000000003600000000heroic-gogdl-1.1.2/gogdl/dl/managers/task_executor.pyimport logging
import os
import signal
import time
from sys import exit
from threading import Thread
from collections import deque, Counter
from multiprocessing import Queue, Manager as ProcessingManager
from threading import Condition
from multiprocessing.shared_memory import SharedMemory
from queue import Empty
from typing import Union
from gogdl.dl import dl_utils

from gogdl.dl.dl_utils import get_readable_size
from gogdl.dl.progressbar import ProgressBar
from gogdl.dl.workers import task_executor
from gogdl.dl.objects import generic, v2, v1, linux

class ExecutingManager:
    def __init__(self, api_handler, allowed_threads, path, support, diff, secure_links) -> None:
        self.api_handler = api_handler
        self.allowed_threads = allowed_threads
        self.path = path
        self.resume_file = os.path.join(path, '.gogdl-resume')
        self.support = support or os.path.join(path, 'gog-support')
        self.cache = os.path.join(path, '.gogdl-download-cache')
        self.diff: generic.BaseDiff = diff
        self.secure_links = secure_links
        self.logger = logging.getLogger("TASK_EXEC")

        self.download_size = 0
        self.disk_size = 0

        self.shared_memory = None
        self.shm_segments = deque()
        self.hash_map = dict()
        self.v2_chunks_to_download = deque()
        self.v1_chunks_to_download = deque()
        self.linux_chunks_to_download = deque()
        self.tasks = deque()
        self.active_tasks = 0

        self.processed_items = 0
        self.items_to_complete = 0

        self.download_workers = list()
        self.writer_worker = None
        self.threads = list()

        self.shm_cond = Condition()
        self.task_cond = Condition()
        
        self.running = True

    def setup(self):
        self.logger.debug("Beginning executor manager setup")
        self.logger.debug("Initializing queues")
        # Queues
        self.download_queue = Queue()
        self.download_res_queue = Queue()
        self.writer_queue = Queue()
        self.writer_res_queue = Queue()
        
        self.download_speed_updates = Queue()
        self.writer_speed_updates = Queue()

        self.manager = ProcessingManager()
        self.shared_secure_links = self.manager.dict()
        self.shared_secure_links.update(self.secure_links)

        # Required space for download to succeed
        required_disk_size_delta = 0

        # This can be either v1 File or v2 DepotFile
        for f in self.diff.deleted + self.diff.removed_redist:
            support_flag = generic.TaskFlag.SUPPORT if 'support' in f.flags else generic.TaskFlag.NONE
            self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.DELETE_FILE | support_flag))
            if isinstance(f, v1.File):
                required_disk_size_delta -= f.size
            elif isinstance(f, v2.DepotFile):
                required_disk_size_delta -= sum([ch['size'] for ch in f.chunks])

        current_tmp_size = required_disk_size_delta

        shared_chunks_counter = Counter()
        completed_files = set()

        missing_files = set()
        mismatched_files = set()

        downloaded_v1 = dict()
        downloaded_linux = dict()
        cached = set()
        
        # Re-use caches
        if os.path.exists(self.cache):
            for cache_file in os.listdir(self.cache):
                cached.add(cache_file)

        self.biggest_chunk = 0
        # Find biggest chunk to optimize how much memory is 'wasted' per chunk
        # Also create hashmap for those files
        for f in self.diff.new + self.diff.changed + self.diff.redist:
            if isinstance(f, v1.File):
                self.hash_map.update({f.path.lower(): f.hash})

            elif isinstance(f, linux.LinuxFile):
                self.hash_map.update({f.path.lower(): f.hash})

            elif isinstance(f, v2.DepotFile):
                first_chunk_checksum = f.chunks[0]['md5'] if len(f.chunks) else None
                checksum = f.md5 or f.sha256 or first_chunk_checksum
                self.hash_map.update({f.path.lower(): checksum})
                for i, chunk in enumerate(f.chunks):
                    shared_chunks_counter[chunk["compressedMd5"]] += 1
                    if self.biggest_chunk < chunk["size"]:
                        self.biggest_chunk = chunk["size"]

            elif isinstance(f, v2.FileDiff):
                first_chunk_checksum = f.file.chunks[0]['md5'] if len(f.file.chunks) else None
                checksum = f.file.md5 or f.file.sha256 or first_chunk_checksum
                self.hash_map.update({f.file.path.lower(): checksum})
                for i, chunk in enumerate(f.file.chunks):
                    if chunk.get("old_offset") is None:
                        shared_chunks_counter[chunk["compressedMd5"]] += 1
                        if self.biggest_chunk < chunk["size"]:
                            self.biggest_chunk = chunk["size"]
            
            elif isinstance(f, v2.FilePatchDiff):
                first_chunk_checksum = f.new_file.chunks[0]['md5'] if len(f.new_file.chunks) else None
                checksum = f.new_file.md5 or f.new_file.sha256 or first_chunk_checksum
                self.hash_map.update({f.new_file.path.lower(): checksum})
                for chunk in f.chunks:
                    shared_chunks_counter[chunk["compressedMd5"]] += 1
                    if self.biggest_chunk < chunk["size"]:
                        self.biggest_chunk = chunk["size"]


        if not self.biggest_chunk:
            self.biggest_chunk = 20 * 1024 * 1024
        else:
            # Have at least 10 MiB chunk size for V1 downloads
            self.biggest_chunk = max(self.biggest_chunk, 10 * 1024 * 1024)

        if os.path.exists(self.resume_file):
            self.logger.info("Attempting to continue the download")
            try:
                missing = 0
                mismatch = 0

                with open(self.resume_file, 'r') as f:
                    for line in f.readlines():
                        hash, support, file_path = line.strip().split(':')
                        
                        if support == 'support':
                            abs_path = os.path.join(self.support, file_path)
                        else:
                            abs_path = os.path.join(self.path, file_path)

                        if not os.path.exists(dl_utils.get_case_insensitive_name(abs_path)):
                            missing_files.add(file_path.lower())
                            missing += 1
                            continue
                        
                        current_hash = self.hash_map.get(file_path.lower())
                        if current_hash != hash:
                            mismatched_files.add(file_path.lower())
                            mismatch += 1
                            continue

                        completed_files.add(file_path.lower())
                if missing:
                    self.logger.warning(f'There are {missing} missing files, and will be re-downloaded')
                if mismatch:
                    self.logger.warning(f'There are {mismatch} changed files since last download, and will be re-downloaded')

            except Exception as e:
                self.logger.error(f"Unable to resume download, continuing as normal {e}")


        # Create tasks for each chunk
        for f in self.diff.new + self.diff.changed + self.diff.redist:
            if isinstance(f, v1.File):
                support_flag = generic.TaskFlag.SUPPORT if 'support' in f.flags else generic.TaskFlag.NONE
                if f.size == 0:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CREATE_FILE | support_flag))
                    continue

                if f.path.lower() in completed_files:
                    downloaded_v1[f.hash] = f
                    continue

                required_disk_size_delta += f.size
                # In case of same file we can copy it over
                if f.hash in downloaded_v1:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.COPY_FILE | support_flag, old_flags=generic.TaskFlag.SUPPORT if 'support' in downloaded_v1[f.hash].flags else generic.TaskFlag.NONE, old_file=downloaded_v1[f.hash].path))
                    if 'executable' in f.flags:
                        self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.MAKE_EXE | support_flag))
                    continue
                self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.OPEN_FILE | support_flag))
                self.download_size += f.size
                self.disk_size += f.size
                size_left = f.size
                chunk_offset = 0
                i = 0
                # Split V1 file by chunks, so we can store it in shared memory
                # This makes checksum useless during the download, but well...
                while size_left:
                    chunk_size = min(self.biggest_chunk, size_left)
                    offset = f.offset + chunk_offset
                    
                    task = generic.V1Task(f.product_id, i, offset, chunk_size, f.hash)
                    self.tasks.append(task)
                    self.v1_chunks_to_download.append((f.product_id, task.compressed_md5, offset, chunk_size))

                    chunk_offset += chunk_size
                    size_left -= chunk_size
                    i += 1

                self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CLOSE_FILE | support_flag))
                if 'executable' in f.flags:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.MAKE_EXE | support_flag))
                downloaded_v1[f.hash] = f

            elif isinstance(f, linux.LinuxFile):
                if f.size == 0:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CREATE_FILE))
                    continue
                
                if f.path.lower() in completed_files:
                    downloaded_linux[f.hash] = f
                    continue
                
                required_disk_size_delta += f.size
                if f.hash in downloaded_linux:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.COPY_FILE, old_flags=generic.TaskFlag.NONE, old_file=downloaded_linux[f.hash].path))
                    if 'executable' in f.flags:
                        self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.MAKE_EXE))
                    continue
                
                self.tasks.append(generic.FileTask(f.path+'.tmp', flags=generic.TaskFlag.OPEN_FILE))
                self.download_size += f.compressed_size
                self.disk_size += f.size
                size_left = f.compressed_size
                chunk_offset = 0
                i = 0
                # Split V1 file by chunks, so we can store it in shared memory
                # This makes checksum useless during the download, but well...
                while size_left:
                    chunk_size = min(self.biggest_chunk, size_left)
                    offset = f.offset + chunk_offset
                    
                    task = generic.V1Task(f.product, i, offset, chunk_size, f.hash)
                    self.tasks.append(task)
                    self.linux_chunks_to_download.append((f.product, task.compressed_md5, offset, chunk_size))

                    chunk_offset += chunk_size
                    size_left -= chunk_size
                    i += 1

                self.tasks.append(generic.FileTask(f.path + '.tmp', flags=generic.TaskFlag.CLOSE_FILE))
                if f.compression:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.OPEN_FILE))
                    self.tasks.append(generic.ChunkTask(f.product, 0, f.hash+"_dec", f.hash+"_dec", f.compressed_size, f.compressed_size, True, False, 0, old_flags=generic.TaskFlag.ZIP_DEC, old_file=f.path+'.tmp'))
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CLOSE_FILE))
                    self.tasks.append(generic.FileTask(f.path + '.tmp', flags=generic.TaskFlag.DELETE_FILE))
                else:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.DELETE_FILE | generic.TaskFlag.RENAME_FILE, old_file=f.path+'.tmp'))

                if 'executable' in f.flags:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.MAKE_EXE))
                downloaded_linux[f.hash] = f

            elif isinstance(f, v2.DepotFile):
                support_flag = generic.TaskFlag.SUPPORT if 'support' in f.flags else generic.TaskFlag.NONE
                if not len(f.chunks):
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CREATE_FILE | support_flag))
                    continue
                if f.path.lower() in completed_files:
                    continue
                self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.OPEN_FILE | support_flag))
                for i, chunk in enumerate(f.chunks):
                    new_task = generic.ChunkTask(f.product_id, i, chunk["compressedMd5"], chunk["md5"], chunk["size"], chunk["compressedSize"])
                    is_cached = chunk["md5"] in cached
                    if shared_chunks_counter[chunk["compressedMd5"]] > 1 and not is_cached:
                        self.v2_chunks_to_download.append((f.product_id, chunk["compressedMd5"]))
                        self.download_size += chunk['compressedSize']
                        new_task.offload_to_cache = True
                        new_task.cleanup = True
                        cached.add(chunk["md5"])
                        current_tmp_size += chunk['size']
                    elif is_cached:
                        new_task.old_offset = 0
                        # This can safely be absolute path, due to
                        # how os.path.join works in Writer
                        new_task.old_file = os.path.join(self.cache, chunk["md5"])
                    else:
                        self.v2_chunks_to_download.append((f.product_id, chunk["compressedMd5"]))
                        self.download_size += chunk['compressedSize']
                    self.disk_size += chunk['size']
                    current_tmp_size += chunk['size']
                    shared_chunks_counter[chunk["compressedMd5"]] -= 1
                    new_task.cleanup = True
                    self.tasks.append(new_task)
                    if is_cached and shared_chunks_counter[chunk["compressedMd5"]] == 0:
                        cached.remove(chunk["md5"])
                        self.tasks.append(generic.FileTask(os.path.join(self.cache, chunk["md5"]), flags=generic.TaskFlag.DELETE_FILE))
                        current_tmp_size -= chunk['size']
                self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CLOSE_FILE | support_flag))
                if 'executable' in f.flags:
                    self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.MAKE_EXE | support_flag))

            elif isinstance(f, v2.FileDiff):
                chunk_tasks = []
                reused = 0
                file_size = 0
                support_flag = generic.TaskFlag.SUPPORT if 'support' in f.file.flags else generic.TaskFlag.NONE
                old_support_flag = generic.TaskFlag.SUPPORT if 'support' in f.old_file_flags else generic.TaskFlag.NONE
                if f.file.path.lower() in completed_files:
                    continue
                for i, chunk in enumerate(f.file.chunks):
                    chunk_task = generic.ChunkTask(f.file.product_id, i, chunk["compressedMd5"], chunk["md5"], chunk["size"], chunk["compressedSize"])
                    file_size += chunk['size']
                    if chunk.get("old_offset") is not None and f.file.path.lower() not in mismatched_files and f.file.path.lower() not in missing_files:
                        chunk_task.old_offset = chunk["old_offset"]
                        chunk_task.old_flags = old_support_flag  
                        chunk_task.old_file = f.file.path
                        reused += 1

                        chunk_tasks.append(chunk_task)
                    else:
                        is_cached = chunk["md5"] in cached
                        if shared_chunks_counter[chunk["compressedMd5"]] > 1 and not is_cached:
                            self.v2_chunks_to_download.append((f.file.product_id, chunk["compressedMd5"]))
                            self.download_size += chunk['compressedSize']
                            chunk_task.offload_to_cache = True
                            cached.add(chunk["md5"])
                            current_tmp_size += chunk['size']
                        elif is_cached:
                            chunk_task.old_offset = 0
                            chunk_task.old_file = os.path.join(self.cache, chunk["md5"])
                        else:
                            self.v2_chunks_to_download.append((f.file.product_id, chunk["compressedMd5"]))
                            self.download_size += chunk['compressedSize']

                        shared_chunks_counter[chunk["compressedMd5"]] -= 1
                        chunk_task.cleanup = True
                        chunk_tasks.append(chunk_task)
                        if is_cached and shared_chunks_counter[chunk["compressedMd5"]] == 0:
                            cached.remove(chunk["md5"])
                            self.tasks.append(generic.FileTask(os.path.join(self.cache, chunk["md5"]), flags=generic.TaskFlag.DELETE_FILE))
                            current_tmp_size -= chunk['size']
                current_tmp_size += file_size
                required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)
                if reused:
                    self.tasks.append(generic.FileTask(f.file.path + ".tmp", flags=generic.TaskFlag.OPEN_FILE | support_flag))
                    self.tasks.extend(chunk_tasks)
                    self.tasks.append(generic.FileTask(f.file.path + ".tmp", flags=generic.TaskFlag.CLOSE_FILE | support_flag))
                    self.tasks.append(generic.FileTask(f.file.path, flags=generic.TaskFlag.RENAME_FILE | generic.TaskFlag.DELETE_FILE | support_flag, old_file=f.file.path + ".tmp"))
                    current_tmp_size -= file_size
                else:
                    self.tasks.append(generic.FileTask(f.file.path, flags=generic.TaskFlag.OPEN_FILE | support_flag))
                    self.tasks.extend(chunk_tasks)
                    self.tasks.append(generic.FileTask(f.file.path, flags=generic.TaskFlag.CLOSE_FILE | support_flag))
                if 'executable' in f.file.flags:
                    self.tasks.append(generic.FileTask(f.file.path, flags=generic.TaskFlag.MAKE_EXE | support_flag))
                self.disk_size += file_size

            elif isinstance(f, v2.FilePatchDiff):
                chunk_tasks = []
                patch_size = 0
                old_file_size = 0
                out_file_size = 0
                if f.target.lower() in completed_files:
                    continue

                # Calculate output size  
                for chunk in f.new_file.chunks:
                    out_file_size += chunk['size']

                # Calculate old size  
                for chunk in f.old_file.chunks:
                    old_file_size += chunk['size']

                # Make chunk tasks
                for i, chunk in enumerate(f.chunks):
                    chunk_task = generic.ChunkTask(f'{f.new_file.product_id}_patch', i, chunk['compressedMd5'], chunk['md5'], chunk['size'], chunk['compressedSize'])
                    chunk_task.cleanup = True
                    patch_size += chunk['size']
                    is_cached = chunk["md5"] in cached
                    if shared_chunks_counter[chunk["compressedMd5"]] > 1 and not is_cached:
                        self.v2_chunks_to_download.append((f'{f.new_file.product_id}_patch', chunk["compressedMd5"]))
                        chunk_task.offload_to_cache = True
                        cached.add(chunk["md5"])
                        self.download_size += chunk['compressedSize']
                        current_tmp_size += chunk['size']
                        required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)
                    elif is_cached:
                        chunk_task.old_offset = 0
                        chunk_task.old_file = os.path.join(self.cache, chunk["md5"])
                    else:
                        self.v2_chunks_to_download.append((f'{f.new_file.product_id}_patch', chunk["compressedMd5"]))
                        self.download_size += chunk['compressedSize']
                    shared_chunks_counter[chunk['compressedMd5']] -= 1
                    chunk_tasks.append(chunk_task)
                    if is_cached and shared_chunks_counter[chunk["compressedMd5"]] == 0:
                        cached.remove(chunk["md5"])
                        self.tasks.append(generic.FileTask(os.path.join(self.cache, chunk["md5"]), flags=generic.TaskFlag.DELETE_FILE))
                        current_tmp_size -= chunk['size']

                self.disk_size += patch_size
                current_tmp_size += patch_size 
                required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)

                # Download patch
                self.tasks.append(generic.FileTask(f.target + ".delta", flags=generic.TaskFlag.OPEN_FILE))
                self.tasks.extend(chunk_tasks)
                self.tasks.append(generic.FileTask(f.target + ".delta", flags=generic.TaskFlag.CLOSE_FILE))

                current_tmp_size += out_file_size
                required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)
                
                # Apply patch to .tmp file
                self.tasks.append(generic.FileTask(f.target + ".tmp", flags=generic.TaskFlag.PATCH, patch_file=(f.target + '.delta'), old_file=f.source))
                current_tmp_size -= patch_size 
                required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)
                # Remove patch file
                self.tasks.append(generic.FileTask(f.target + ".delta", flags=generic.TaskFlag.DELETE_FILE))
                current_tmp_size -= old_file_size
                required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)
                # Move new file to old one's location
                self.tasks.append(generic.FileTask(f.target, flags=generic.TaskFlag.RENAME_FILE | generic.TaskFlag.DELETE_FILE, old_file=f.target + ".tmp"))
                self.disk_size += out_file_size

            required_disk_size_delta = max(current_tmp_size, required_disk_size_delta)
            
            
        for f in self.diff.links:
            self.tasks.append(generic.FileTask(f.path, flags=generic.TaskFlag.CREATE_SYMLINK, old_file=f.target))

        self.items_to_complete = len(self.tasks)

        print(get_readable_size(self.download_size), self.download_size)
        print(get_readable_size(required_disk_size_delta), required_disk_size_delta)
                
        return dl_utils.check_free_space(required_disk_size_delta, self.path)

        
    def run(self):
        self.shared_memory = SharedMemory(create=True, size=1024*1024*1024)
        self.logger.debug(f"Created shared memory {self.shared_memory.size / 1024 / 1024:.02f} MiB")

        chunk_size = self.biggest_chunk 
        for i in range(int(self.shared_memory.size / chunk_size)):
            segment = generic.MemorySegment(offset=i*chunk_size, end=i*chunk_size+chunk_size)
            self.shm_segments.append(segment)
        self.logger.debug(f"Created shm segments {len(self.shm_segments)}, chunk size = {self.biggest_chunk / 1024 / 1024:.02f} MiB")
        interrupted = False
        self.fatal_error = False
        def handle_sig(num, frame):
            nonlocal interrupted
            self.interrupt_shutdown()
            interrupted = True
            exit(-num)

        try:
            self.threads.append(Thread(target=self.download_manager, args=(self.task_cond, self.shm_cond)))
            self.threads.append(Thread(target=self.process_task_results, args=(self.task_cond,)))
            self.threads.append(Thread(target=self.process_writer_task_results, args=(self.shm_cond,)))
            self.progress = ProgressBar(self.disk_size, self.download_speed_updates, self.writer_speed_updates)

            # Spawn workers 
            for _ in range(self.allowed_threads):
                worker = task_executor.Download(self.shared_memory.name, self.download_queue, self.download_res_queue, self.download_speed_updates, self.shared_secure_links)
                worker.start()
                self.download_workers.append(worker)
        
            self.writer_worker = task_executor.Writer(self.shared_memory.name, self.writer_queue, self.writer_res_queue, self.writer_speed_updates, self.cache)
            self.writer_worker.start()

            [th.start() for th in self.threads]

            signal.signal(signal.SIGTERM, handle_sig)
            signal.signal(signal.SIGINT, handle_sig)

            if self.disk_size:
                self.progress.start()

            while self.processed_items < self.items_to_complete and not interrupted and not self.fatal_error:
                time.sleep(1)
            if interrupted:
                return True
        except KeyboardInterrupt:
            return True
        
        self.shutdown()
        return self.fatal_error

    def interrupt_shutdown(self):
        self.progress.completed = True
        self.running = False
            
        with self.task_cond:
            self.task_cond.notify()

        with self.shm_cond:
            self.shm_cond.notify()

        for t in self.threads:
            t.join(timeout=5.0)
            if t.is_alive():
                self.logger.warning(f'Thread did not terminate! {repr(t)}')

        for child in self.download_workers:
            child.join(timeout=5.0)
            if child.exitcode is None:
                child.terminate()
            
        # Clean queues
        for queue in [self.writer_res_queue, self.writer_queue, self.download_queue, self.download_res_queue, self.download_speed_updates, self.writer_speed_updates]:
            try:
                while True:
                    _ = queue.get_nowait()
            except Empty:
                queue.close()
                queue.join_thread()

        self.shared_memory.close()
        self.shared_memory.unlink()
        self.shared_memory = None
        self.manager.shutdown()


    def shutdown(self):
        self.logger.debug("Stopping progressbar")
        self.progress.completed = True
        
        # Clear speed queues
        for q in [self.download_speed_updates, self.writer_speed_updates]:
            while True:
                try:
                    _ = q.get_nowait()
                except Empty:
                    break

        self.logger.debug("Sending terminate instruction to workers")
        for _ in range(self.allowed_threads):
            self.download_queue.put(generic.TerminateWorker())
        
        self.writer_queue.put(generic.TerminateWorker())

        for worker in self.download_workers:
            worker.join(timeout=2)
            if worker.is_alive():
                self.logger.warning("Forcefully terminating download workers")
                worker.terminate()
        self.writer_worker.join(timeout=10)
        
        self.writer_queue.close()
        self.writer_res_queue.close()
        self.download_queue.close()
        self.download_res_queue.close()
        self.download_speed_updates.close()
        self.writer_speed_updates.close()

        self.logger.debug("Unlinking shared memory")
        if self.shared_memory:
            self.shared_memory.close()
            self.shared_memory.unlink()
            self.shared_memory = None

        self.running = False
        with self.task_cond:
            self.task_cond.notify()

        with self.shm_cond:
            self.shm_cond.notify()

        self.manager.shutdown()

        try:
            if os.path.exists(self.resume_file):
                os.remove(self.resume_file)
        except:
            self.logger.error("Failed to remove resume file")

    def download_manager(self, task_cond: Condition, shm_cond: Condition):
        self.logger.debug("Starting download scheduler")
        no_shm = False
        while self.running:
            while self.active_tasks <= self.allowed_threads * 2 and (self.v2_chunks_to_download or self.v1_chunks_to_download or self.linux_chunks_to_download):

                try:
                    memory_segment = self.shm_segments.popleft()
                    no_shm = False
                except IndexError:
                    no_shm = True
                    break 

                if self.v1_chunks_to_download:
                    product_id, chunk_id, offset, chunk_size = self.v1_chunks_to_download.popleft()

                    try:
                        self.download_queue.put(task_executor.DownloadTask1(product_id, offset, chunk_size, chunk_id, memory_segment))
                        self.logger.debug(f"Pushed v1 download to queue {chunk_id} {product_id} {offset} {chunk_size}")
                        self.active_tasks += 1
                        continue
                    except Exception as e:
                        self.logger.warning(f"Failed to push v1 task to download {e}")
                        self.v1_chunks_to_download.appendleft((product_id, chunk_id, offset, chunk_size))
                        self.shm_segments.appendleft(memory_segment)
                        break
                elif self.linux_chunks_to_download:
                    product_id, chunk_id, offset, chunk_size = self.linux_chunks_to_download.popleft()
                    try:
                        self.download_queue.put(task_executor.DownloadTask1(product_id, offset, chunk_size, chunk_id, memory_segment))
                        self.logger.debug(f"Pushed linux download to queue {chunk_id} {product_id} {offset} {chunk_size}")
                        self.active_tasks += 1
                        continue
                    except Exception as e:
                        self.logger.warning(f"Failed to push v1 task to download {e}")
                        self.v1_chunks_to_download.appendleft((product_id, chunk_id, offset, chunk_size))
                        self.shm_segments.appendleft(memory_segment)
                        break

                elif self.v2_chunks_to_download:
                    product_id, chunk_hash = self.v2_chunks_to_download.popleft()
                    try:
                        self.download_queue.put(task_executor.DownloadTask2(product_id, chunk_hash, memory_segment), timeout=1)
                        self.logger.debug(f"Pushed DownloadTask2 for {chunk_hash}")
                        self.active_tasks += 1
                    except Exception as e:
                        self.logger.warning(f"Failed to push task to download {e}")
                        self.v2_chunks_to_download.appendleft((product_id, chunk_hash))
                        self.shm_segments.appendleft(memory_segment)
                        break

            else:
                with task_cond:
                    self.logger.debug("Waiting for more tasks")
                    task_cond.wait(timeout=1.0)
                    continue

            if no_shm:
                with shm_cond:
                    self.logger.debug(f"Waiting for more memory")
                    shm_cond.wait(timeout=1.0)

        self.logger.debug("Download scheduler out..")


    def process_task_results(self, task_cond: Condition):
        self.logger.debug("Download results collector starting")
        ready_chunks = dict()

        try:
            task = self.tasks.popleft()
        except IndexError:
            task = None
            
        current_dest = self.path
        current_file = ''

        while task and self.running:
            if isinstance(task, generic.FileTask):
                try:
                    task_dest = self.path
                    old_destination = None
                    if task.flags & generic.TaskFlag.SUPPORT:
                        task_dest = self.support
                    if task.old_flags & generic.TaskFlag.SUPPORT:
                        old_destination = self.support

                    writer_task = task_executor.WriterTask(task_dest, task.path, task.flags, old_destination=old_destination, old_file=task.old_file, patch_file=task.patch_file)
                    self.writer_queue.put(writer_task, timeout=1)
                    if task.flags & generic.TaskFlag.OPEN_FILE:
                        current_file = task.path
                        current_dest = task_dest 
                except Exception as e:
                    self.tasks.appendleft(task)
                    self.logger.warning(f"Failed to add queue element {e}")
                    continue

                try:
                    task: Union[generic.ChunkTask, generic.V1Task] = self.tasks.popleft()
                except IndexError:
                    break
                continue
            
            while ((task.compressed_md5 in ready_chunks) or task.old_file):
                shm = None
                if not task.old_file:
                    shm = ready_chunks[task.compressed_md5].task.memory_segment

                try:
                    self.logger.debug(f"Adding {task.compressed_md5} to writer")
                    flags =  generic.TaskFlag.NONE
                    old_destination = None
                    if task.cleanup:
                        flags |= generic.TaskFlag.RELEASE_MEM
                    if task.offload_to_cache:
                        flags |= generic.TaskFlag.OFFLOAD_TO_CACHE
                    if task.old_flags & generic.TaskFlag.ZIP_DEC:
                        flags |= generic.TaskFlag.ZIP_DEC
                    if task.old_flags & generic.TaskFlag.SUPPORT:
                        old_destination = self.support
                    self.writer_queue.put(task_executor.WriterTask(current_dest, current_file, flags=flags, shared_memory=shm, old_destination=old_destination, old_file=task.old_file, old_offset=task.old_offset, size=task.size, hash=task.md5), timeout=1)
                except Exception as e:
                    self.logger.error(f"Adding to writer queue failed {e}")
                    break

                if task.cleanup and not task.old_file:
                    del ready_chunks[task.compressed_md5]

                try:
                    task = self.tasks.popleft()
                    if isinstance(task, generic.FileTask):
                        break
                except IndexError:
                    task = None
                    break

            else:
                try:
                    res: task_executor.DownloadTaskResult = self.download_res_queue.get(timeout=1)
                    if res.success:
                        self.logger.debug(f"Chunk {res.task.compressed_sum} ready")
                        ready_chunks[res.task.compressed_sum] = res
                        self.progress.update_downloaded_size(res.download_size)
                        self.progress.update_decompressed_size(res.decompressed_size)
                        self.active_tasks -= 1
                    else:
                        self.logger.warning(f"Chunk download failed, reason {res.fail_reason}")
                        try:
                            self.download_queue.put(res.task, timeout=1)
                        except Exception as e:
                            self.logger.warning("Failed to resubmit download task, pushing to chunks queue")

                    with task_cond:
                        task_cond.notify()
                except Empty:
                    pass
                except Exception as e:
                    self.logger.warning(f"Unhandled exception {e}")

        self.logger.debug("Download results collector exiting...")

    def process_writer_task_results(self, shm_cond: Condition):
        self.logger.debug("Starting writer results collector")
        while self.running:
            try:
                res: task_executor.WriterTaskResult = self.writer_res_queue.get(timeout=1)

                if isinstance(res.task, generic.TerminateWorker):
                    break
                
                if res.success and res.task.flags & generic.TaskFlag.CLOSE_FILE and not res.task.file_path.endswith('.delta'):
                    if res.task.file_path.endswith('.tmp'):
                        res.task.file_path = res.task.file_path[:-4]
                        
                    checksum = self.hash_map.get(res.task.file_path.lower())
                    if not checksum:
                        self.logger.warning(f"No checksum for closed file, unable to push to resume file {res.task.file_path}")
                    else:
                        if res.task.flags & generic.TaskFlag.SUPPORT:
                            support = "support"
                        else:
                            support = ""

                        with open(self.resume_file, 'a') as f:
                            f.write(f"{checksum}:{support}:{res.task.file_path}\n")

                if res.success and res.task.flags & generic.TaskFlag.PATCH:
                    if res.task.file_path.endswith('.tmp'):
                        res.task.file_path = res.task.file_path[:-4]

                    checksum = self.hash_map.get(res.task.file_path.lower())
                    if not checksum:
                        self.logger.warning(f"No checksum for patched file, unable to push to resume file {res.task.file_path}")
                    else:
                        if res.task.flags & generic.TaskFlag.SUPPORT:
                            support = "support"
                        else:
                            support = ""

                        with open(self.resume_file, 'a') as f:
                            f.write(f"{checksum}:{support}:{res.task.file_path}\n")

                if not res.success:
                    self.logger.fatal("Task writer failed")
                    self.fatal_error = True
                    return
    
                self.progress.update_bytes_written(res.written)
                if res.task.flags & generic.TaskFlag.RELEASE_MEM and res.task.shared_memory:
                    self.logger.debug(f"Releasing memory {res.task.shared_memory}")
                    self.shm_segments.appendleft(res.task.shared_memory)
                with shm_cond:
                    shm_cond.notify()
                self.processed_items += 1

            except Empty:
                continue

        self.logger.debug("Writer results collector exiting...")
    
07070100000017000081A400000000000000000000000166E0651E00002D72000000000000000000000000000000000000002B00000000heroic-gogdl-1.1.2/gogdl/dl/managers/v1.py# Handle old games downloading via V1 depot system
# V1 is there since GOG 1.0 days, it has no compression and relies on downloading chunks from big main.bin file
import hashlib
from sys import exit
import os 
import logging
import json
from typing import Union
from gogdl import constants
from gogdl.dl import dl_utils
from gogdl.dl.managers.dependencies import DependenciesManager
from gogdl.dl.managers.task_executor import ExecutingManager
from gogdl.dl.workers.task_executor import DownloadTask1, DownloadTask2, WriterTask
from gogdl.dl.objects import v1


class Manager:
    def __init__(self, generic_manager):
        self.game_id = generic_manager.game_id
        self.arguments = generic_manager.arguments
        self.unknown_arguments = generic_manager.unknown_arguments
        if "path" in self.arguments:
            self.path = self.arguments.path
        else:
            self.path = ""

        if "support_path" in self.arguments:
            self.support = self.arguments.support_path
        else:
            self.support = ""

        self.api_handler = generic_manager.api_handler
        self.should_append_folder_name = generic_manager.should_append_folder_name
        self.is_verifying = generic_manager.is_verifying
        self.allowed_threads = generic_manager.allowed_threads

        self.platform = generic_manager.platform

        self.builds = generic_manager.builds
        self.build = generic_manager.target_build
        self.version_name = self.build["version_name"]

        self.lang = self.arguments.lang or "English"
        self.dlcs_should_be_downloaded = self.arguments.dlcs
        if self.arguments.dlcs_list:
            self.dlcs_list = self.arguments.dlcs_list.split(",")

        else:
            self.dlcs_list = list()
        
        self.dlc_only = self.arguments.dlc_only

        self.manifest = None
        self.meta = None

        self.logger = logging.getLogger("V1")
        self.logger.info("Initialized V1 Download Manager")

    # Get manifest of selected build
    def get_meta(self):
        meta_url = self.build["link"]
        self.meta, headers = dl_utils.get_zlib_encoded(self.api_handler, meta_url)
        if not self.meta:
            raise Exception("There was an error obtaining meta")
        if headers:
            self.version_etag = headers.get("Etag")

        # Append folder name when downloading
        if self.should_append_folder_name:
            self.path = os.path.join(self.path, self.meta["product"]["installDirectory"]) 

    def get_download_size(self):
        self.get_meta()
        dlcs = self.get_dlcs_user_owns(True)
        self.manifest = v1.Manifest(self.platform, self.meta, self.lang, dlcs, self.api_handler, False)

        build = self.api_handler.get_dependencies_repo()
        repository = dl_utils.get_zlib_encoded(self.api_handler, build['repository_manifest'])[0] or {}

        size_data = self.manifest.calculate_download_size()

        for depot in repository["depots"]:
            if depot["dependencyId"] in self.manifest.dependencies_ids:
                if not depot["executable"]["path"].startswith("__redist"):
                    size_data[self.game_id]['*']["download_size"] += depot["compressedSize"]
                    size_data[self.game_id]['*']["disk_size"] += depot["size"]

        available_branches = set([build["branch"] for build in self.builds["items"] if build["branch"]])
        available_branches_list = [None] + list(available_branches)

        for dlc in dlcs:
            dlc.update({"size": size_data[dlc["id"]]})

        response = {
            "size": size_data[self.game_id],
            "dlcs": dlcs,
            "buildId": self.build["legacy_build_id"],
            "languages": self.manifest.list_languages(),
            "folder_name": self.meta["product"]["installDirectory"],
            "dependencies": [dep.id for dep in self.manifest.dependencies],
            "versionEtag": self.version_etag,
            "versionName": self.version_name,
            "available_branches": available_branches_list 
        }
        return response


    def get_dlcs_user_owns(self, info_command=False, requested_dlcs=None):
        if requested_dlcs is None:
            requested_dlcs = list()
        if not self.dlcs_should_be_downloaded and not info_command:
            return []
        self.logger.debug("Getting dlcs user owns")
        dlcs = []
        if len(requested_dlcs) > 0:
            for product in self.meta["product"]["gameIDs"]:
                if (
                        product["gameID"] != self.game_id # Check if not base game
                        and product["gameID"] in requested_dlcs # Check if requested by user
                        and self.api_handler.does_user_own(product["gameID"]) # Check if owned
                ):
                    dlcs.append({"title": product["name"]["en"], "id": product["gameID"]})
            return dlcs
        for product in self.meta["product"]["gameIDs"]:
            # Check if not base game and if owned
            if product["gameID"] != self.game_id and self.api_handler.does_user_own(
                    product["gameID"]
            ):
                dlcs.append({"title": product["name"]["en"], "id": product["gameID"]})
        return dlcs


    def download(self):
        manifest_path = os.path.join(constants.MANIFESTS_DIR, self.game_id)
        old_manifest = None

        # Load old manifest
        if os.path.exists(manifest_path):
            with open(manifest_path, "r") as f_handle:
                try:
                    json_data = json.load(f_handle)
                    old_manifest = dl_utils.create_manifest_class(json_data, self.api_handler)
                except json.JSONDecodeError:
                    old_manifest = None
                    pass

        if self.is_verifying:
            if old_manifest:
                self.manifest = old_manifest
                old_manifest = None
                dlcs_user_owns = self.manifest.dlcs or []
            else:
                raise Exception("No manifest stored locally, unable to verify")
        else:
            self.get_meta()
            dlcs_user_owns = self.get_dlcs_user_owns(requested_dlcs=self.dlcs_list)

            if self.arguments.dlcs_list:
                self.logger.info(f"Requested dlcs {self.arguments.dlcs_list}")
                self.logger.info(f"Owned dlcs {dlcs_user_owns}")
            self.logger.debug("Parsing manifest")
            self.manifest = v1.Manifest(self.platform, self.meta, self.lang, dlcs_user_owns, self.api_handler, self.dlc_only)

        if self.manifest:
            self.manifest.get_files()

        if old_manifest:
            old_manifest.get_files()

        diff = v1.ManifestDiff.compare(self.manifest, old_manifest)

        self.logger.info(f"{diff}")


        has_dependencies = len(self.manifest.dependencies) > 0
        
        secure_link_endpoints_ids = [product["id"] for product in dlcs_user_owns]
        if not self.dlc_only:
            secure_link_endpoints_ids.append(self.game_id)
        secure_links = dict()
        for product_id in secure_link_endpoints_ids:
            secure_links.update(
                {
                    product_id: dl_utils.get_secure_link(
                        self.api_handler, f"/{self.platform}/{self.manifest.data['product']['timestamp']}/", product_id, generation=1
                    )
                }
            )
        
        dependency_manager = DependenciesManager([dep.id for dep in self.manifest.dependencies], self.path, self.allowed_threads, self.api_handler, download_game_deps_only=True)
        
        # Find dependencies that are no longer used
        if old_manifest:
            removed_dependencies = [id for id in old_manifest.dependencies_ids if id not in self.manifest.dependencies_ids]
            
            for depot in dependency_manager.repository["depots"]:
                if depot["dependencyId"] in removed_dependencies and not depot["executable"]["path"].startswith("__redist"):
                    diff.removed_redist += dependency_manager.get_files_for_depot_manifest(depot['manifest'])

        if has_dependencies:
            secure_links.update({'redist': dl_utils.get_dependency_link(self.api_handler)})
            
            diff.redist = dependency_manager.get(return_files=True) or []


        if not len(diff.changed) and not len(diff.deleted) and not len(diff.new) and not len(diff.redist) and not len(diff.removed_redist):
            self.logger.info("Nothing to do")
            return

        if self.is_verifying:
            new_diff = v1.ManifestDiff()
            invalid = 0
            for file in diff.new:
                # V1 only files
                if not file.size:
                    continue

                if 'support' in file.flags:
                    file_path = os.path.join(self.support, file.path)
                else:
                    file_path = os.path.join(self.path, file.path)
                file_path = dl_utils.get_case_insensitive_name(file_path)

                if not os.path.exists(file_path):
                    invalid += 1
                    new_diff.new.append(file)
                    continue

                with open(file_path, 'rb') as fh:
                    file_sum  = hashlib.md5()
                    
                    while chunk := fh.read(8 * 1024 * 1024):
                        file_sum.update(chunk)

                    if file_sum.hexdigest() != file.hash:
                        invalid += 1
                        new_diff.new.append(file)
                        continue

            for file in diff.redist:
                if len(file.chunks) == 0:
                    continue
                file_path = dl_utils.get_case_insensitive_name(os.path.join(self.path, file.path))
                if not os.path.exists(file_path):
                    invalid += 1
                    new_diff.redist.append(file)
                    continue
                valid = True
                with open(file_path, 'rb') as fh:
                    for chunk in file.chunks:
                        chunk_sum  = hashlib.md5()
                        chunk_data = fh.read(chunk['size'])
                        chunk_sum.update(chunk_data)

                        if chunk_sum.hexdigest() != chunk['md5']:
                            valid = False
                            break
                if not valid:
                    invalid += 1
                    new_diff.redist.append(file)
                    continue
            if not invalid:
                self.logger.info("All files look good")
                return

            self.logger.info(f"Found {invalid} broken files, repairing...")
            diff = new_diff

        executor = ExecutingManager(self.api_handler, self.allowed_threads, self.path, self.support, diff, secure_links)
        success = executor.setup()
        if not success:
            print('Unable to proceed, Not enough disk space')
            exit(2)
        dl_utils.prepare_location(self.path)

        for dir in self.manifest.dirs:
            manifest_dir_path = os.path.join(self.path, dir.path)
            dl_utils.prepare_location(dl_utils.get_case_insensitive_name(manifest_dir_path))

        cancelled = executor.run()

        if cancelled:
            return

        dl_utils.prepare_location(constants.MANIFESTS_DIR)
        if self.manifest:
            with open(manifest_path, 'w') as f_handle:
                data = self.manifest.serialize_to_json()
                f_handle.write(data)

07070100000018000081A400000000000000000000000166E0651E000030F4000000000000000000000000000000000000002B00000000heroic-gogdl-1.1.2/gogdl/dl/managers/v2.py# Handle newer depots download
# This was introduced in GOG Galaxy 2.0, it features compression and files split by chunks
import json
from sys import exit
from gogdl.dl import dl_utils
import gogdl.dl.objects.v2 as v2
import hashlib
from gogdl.dl.managers import dependencies
from gogdl.dl.managers.task_executor import ExecutingManager
from gogdl.dl.workers import task_executor
from gogdl import constants
import os
import logging


class Manager:
    def __init__(self, generic_manager):
        self.game_id = generic_manager.game_id
        self.arguments = generic_manager.arguments
        self.unknown_arguments = generic_manager.unknown_arguments
        if "path" in self.arguments:
            self.path = self.arguments.path
        else:
            self.path = ""
        if "support_path" in self.arguments:
            self.support = self.arguments.support_path
        else:
            self.support = ""

        self.allowed_threads = generic_manager.allowed_threads

        self.api_handler = generic_manager.api_handler
        self.should_append_folder_name = generic_manager.should_append_folder_name
        self.is_verifying = generic_manager.is_verifying

        self.builds = generic_manager.builds
        self.build = generic_manager.target_build
        self.version_name = self.build["version_name"]

        self.lang = self.arguments.lang or "en-US"
        self.dlcs_should_be_downloaded = self.arguments.dlcs
        if self.arguments.dlcs_list:
            self.dlcs_list = self.arguments.dlcs_list.split(",")
        else:
            self.dlcs_list = list()
        self.dlc_only = self.arguments.dlc_only

        self.manifest = None
        self.stop_all_threads = False

        self.logger = logging.getLogger("V2")
        self.logger.info("Initialized V2 Download Manager")

    def get_download_size(self):
        self.get_meta()
        dlcs = self.get_dlcs_user_owns(info_command=True)
        self.manifest = v2.Manifest(self.meta, self.lang, dlcs, self.api_handler, False)
        
        build = self.api_handler.get_dependencies_repo()
        repository = dl_utils.get_zlib_encoded(self.api_handler, build['repository_manifest'])[0] or {}
    
        size_data = self.manifest.calculate_download_size()

        for depot in repository["depots"]:
            if depot["dependencyId"] in self.manifest.dependencies_ids:
                if not depot["executable"]["path"].startswith("__redist"):
                    size_data[self.game_id]['*']["download_size"] += depot["compressedSize"]
                    size_data[self.game_id]['*']["disk_size"] += depot["size"]

        available_branches = set([build["branch"] for build in self.builds["items"] if build["branch"]])
        available_branches_list = [None] + list(available_branches)
        

        for dlc in dlcs:
            dlc.update({"size": size_data[dlc["id"]]})

        response = {
            "size": size_data[self.game_id],
            "dlcs": dlcs,
            "buildId": self.build["build_id"],
            "languages": self.manifest.list_languages(),
            "folder_name": self.meta["installDirectory"],
            "dependencies": self.manifest.dependencies_ids,
            "versionEtag": self.version_etag,
            "versionName": self.version_name,
            "available_branches": available_branches_list
        }
        return response

    def download(self):
        manifest_path = os.path.join(constants.MANIFESTS_DIR, self.game_id)
        old_manifest = None

        # Load old manifest
        if os.path.exists(manifest_path):
            self.logger.debug(f"Loading existing manifest for game {self.game_id}")
            with open(manifest_path, 'r') as f_handle:
                try:
                    json_data = json.load(f_handle)
                    self.logger.info("Creating Manifest instance from existing manifest")
                    old_manifest = dl_utils.create_manifest_class(json_data, self.api_handler)
                except json.JSONDecodeError:
                    old_manifest = None
                    pass

        if self.is_verifying:
            if old_manifest:
                self.logger.warning("Verifying - ignoring obtained manifest in favor of existing one")
                self.manifest = old_manifest
                dlcs_user_owns = self.manifest.dlcs or []
                old_manifest = None
            else:
                raise Exception("No manifest stored locally, unable to verify")
        else:
            self.get_meta()
            dlcs_user_owns = self.get_dlcs_user_owns(
                requested_dlcs=self.dlcs_list
            )
    
            if self.arguments.dlcs_list:
                self.logger.info(f"Requested dlcs {self.arguments.dlcs_list}")
                self.logger.info(f"Owned dlcs {dlcs_user_owns}")

            self.logger.debug("Parsing manifest")
            self.manifest = v2.Manifest(
                self.meta, self.lang, dlcs_user_owns, self.api_handler, self.dlc_only
            )
        patch = None
        if self.manifest:
            self.logger.debug("Requesting files of primary manifest")
            self.manifest.get_files()
        if old_manifest:
            self.logger.debug("Requesting files of previous manifest")
            old_manifest.get_files()
            patch = v2.Patch.get(self.manifest, old_manifest, self.lang, dlcs_user_owns, self.api_handler)
            if not patch:
                self.logger.info("No patch found, falling back to chunk based updates")

        diff = v2.ManifestDiff.compare(self.manifest, old_manifest, patch)
        self.logger.info(diff)


        dependencies_manager = dependencies.DependenciesManager(self.manifest.dependencies_ids, self.path,
                                                                self.arguments.workers_count, self.api_handler, download_game_deps_only=True)

        # Find dependencies that are no longer used
        if old_manifest:
            removed_dependencies = [id for id in old_manifest.dependencies_ids if id not in self.manifest.dependencies_ids]
            
            for depot in dependencies_manager.repository["depots"]:
                if depot["dependencyId"] in removed_dependencies and not depot["executable"]["path"].startswith("__redist"):
                    diff.removed_redist += dependencies_manager.get_files_for_depot_manifest(depot['manifest'])


        diff.redist = dependencies_manager.get(True) or []

        if not len(diff.changed) and not len(diff.deleted) and not len(diff.new) and not len(diff.redist) and not len(diff.removed_redist):
            self.logger.info("Nothing to do")
            return
        secure_link_endpoints_ids = [product["id"] for product in dlcs_user_owns]
        if not self.dlc_only:
            secure_link_endpoints_ids.append(self.game_id)
        secure_links = dict()
        for product_id in secure_link_endpoints_ids:
            secure_links.update(
                {
                    product_id: dl_utils.get_secure_link(
                        self.api_handler, "/", product_id
                    )
                }
            )
            if patch:
                secure_links.update(
                    {
                        f"{product_id}_patch": dl_utils.get_secure_link(
                            self.api_handler, "/", product_id, root="/patches/store"
                        )
                    }
                )

        if len(diff.redist) > 0:
            secure_links.update(
                {
                    'redist': dl_utils.get_dependency_link(self.api_handler)
                }
            )
        
        if self.is_verifying:
            new_diff = v2.ManifestDiff()
            invalid = 0

            for file in diff.new:
                if len(file.chunks) == 0:
                    continue
                if 'support' in file.flags:
                    file_path = os.path.join(self.support, file.path)
                else:
                    file_path = os.path.join(self.path, file.path)
                file_path = dl_utils.get_case_insensitive_name(file_path)
                if not os.path.exists(file_path):
                    invalid += 1
                    new_diff.new.append(file)
                    continue
                valid = True
                with open(file_path, 'rb') as fh:
                    for chunk in file.chunks:
                        chunk_sum  = hashlib.md5()
                        chunk_data = fh.read(chunk['size'])
                        chunk_sum.update(chunk_data)

                        if chunk_sum.hexdigest() != chunk['md5']:
                            valid = False
                            break
                if not valid:
                    invalid += 1
                    new_diff.new.append(file)
                    continue

            for file in diff.redist:
                if len(file.chunks) == 0:
                    continue
                file_path = dl_utils.get_case_insensitive_name(os.path.join(self.path, file.path))
                if not os.path.exists(file_path):
                    invalid += 1
                    new_diff.redist.append(file)
                    continue
                valid = True
                with open(file_path, 'rb') as fh:
                    for chunk in file.chunks:
                        chunk_sum  = hashlib.md5()
                        chunk_data = fh.read(chunk['size'])
                        chunk_sum.update(chunk_data)

                        if chunk_sum.hexdigest() != chunk['md5']:
                            valid = False
                            break
                if not valid:
                    invalid += 1
                    new_diff.redist.append(file)
                    continue
            for file in diff.links:
                file_path = os.path.join(self.path, file.path)
                file_path = dl_utils.get_case_insensitive_name(file_path)
                if not os.path.exists(file_path):
                    new_diff.links.append(file)

            if not invalid:
                self.logger.info("All files look good")
                return

            self.logger.info(f"Found {invalid} broken files, repairing...")
            diff = new_diff

        executor = ExecutingManager(self.api_handler, self.allowed_threads, self.path, self.support, diff, secure_links)
        success = executor.setup()
        if not success:
            print('Unable to proceed, Not enough disk space')
            exit(2)
        dl_utils.prepare_location(self.path)

        for dir in self.manifest.dirs:
            manifest_dir_path = os.path.join(self.path, dir.path)
            dl_utils.prepare_location(dl_utils.get_case_insensitive_name(manifest_dir_path))
        cancelled = executor.run()

        if cancelled:
            return

        dl_utils.prepare_location(constants.MANIFESTS_DIR)
        if self.manifest:
            with open(manifest_path, 'w') as f_handle:
                data = self.manifest.serialize_to_json()
                f_handle.write(data)

    def get_meta(self):
        meta_url = self.build["link"]
        self.meta, headers = dl_utils.get_zlib_encoded(self.api_handler, meta_url)
        self.version_etag = headers.get("Etag")

        # Append folder name when downloading
        if self.should_append_folder_name:
            self.path = os.path.join(self.path, self.meta["installDirectory"])

    def get_dlcs_user_owns(self, info_command=False, requested_dlcs=None):
        if requested_dlcs is None:
            requested_dlcs = list()
        if not self.dlcs_should_be_downloaded and not info_command:
            return []
        self.logger.debug("Getting dlcs user owns")
        dlcs = []
        if len(requested_dlcs) > 0:
            for product in self.meta["products"]:
                if (
                        product["productId"] != self.game_id
                        and product["productId"] in requested_dlcs
                        and self.api_handler.does_user_own(product["productId"])
                ):
                    dlcs.append({"title": product["name"], "id": product["productId"]})
            return dlcs
        for product in self.meta["products"]:
            if product["productId"] != self.game_id and self.api_handler.does_user_own(
                    product["productId"]
            ):
                dlcs.append({"title": product["name"], "id": product["productId"]})
        return dlcs

07070100000019000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000002400000000heroic-gogdl-1.1.2/gogdl/dl/objects0707010000001A000081A400000000000000000000000166E0651E00000790000000000000000000000000000000000000002F00000000heroic-gogdl-1.1.2/gogdl/dl/objects/generic.pyfrom dataclasses import dataclass
from enum import Flag, auto
from typing import Optional


class BaseDiff:
    def __init__(self):
        self.deleted = []
        self.new = []
        self.changed = []
        self.redist = []
        self.removed_redist = []

        self.links = [] # Unix only

    def __str__(self):
        return f"Deleted: {len(self.deleted)} New: {len(self.new)} Changed: {len(self.changed)}"

class TaskFlag(Flag):
    NONE = 0
    SUPPORT = auto()
    OPEN_FILE = auto()
    CLOSE_FILE = auto()
    CREATE_FILE = auto()
    CREATE_SYMLINK = auto()
    RENAME_FILE = auto()
    COPY_FILE = auto()
    DELETE_FILE = auto()
    OFFLOAD_TO_CACHE = auto()
    MAKE_EXE = auto()
    PATCH = auto()
    RELEASE_MEM = auto()
    ZIP_DEC = auto()

@dataclass
class MemorySegment:
    offset: int
    end: int

    @property
    def size(self):
        return self.end - self.offset

@dataclass
class ChunkTask:
    product: str
    index: int

    compressed_md5: str
    md5: str
    size: int
    download_size: int
    
    cleanup: bool = False
    offload_to_cache: bool = False
    old_offset: Optional[int] = None
    old_flags: TaskFlag = TaskFlag.NONE 
    old_file: Optional[str] = None

@dataclass
class V1Task:
    product: str
    index: int
    offset: int
    size: int
    md5: str
    cleanup: Optional[bool] = True

    old_offset: Optional[int] = None
    offload_to_cache: Optional[bool] = False
    old_flags: TaskFlag = TaskFlag.NONE 
    old_file: Optional[str] = None

    # This isn't actual sum, but unique id of chunk we use to decide 
    # if we should push it to writer
    @property
    def compressed_md5(self):
        return self.md5 + "_" + str(self.index)

@dataclass
class FileTask:
    path: str
    flags: TaskFlag

    old_flags: TaskFlag = TaskFlag.NONE 
    old_file: Optional[str] = None

    patch_file: Optional[str] = None


@dataclass
class TerminateWorker:
    pass
0707010000001B000081A400000000000000000000000166E0651E00003D5C000000000000000000000000000000000000002D00000000heroic-gogdl-1.1.2/gogdl/dl/objects/linux.pyfrom io import BytesIO
import stat


END_OF_CENTRAL_DIRECTORY = b"\x50\x4b\x05\x06"
CENTRAL_DIRECTORY = b"\x50\x4b\x01\x02"
LOCAL_FILE_HEADER = b"\x50\x4b\x03\x04"

# ZIP64
ZIP_64_END_OF_CD_LOCATOR = b"\x50\x4b\x06\x07"
ZIP_64_END_OF_CD = b"\x50\x4b\x06\x06"

class LocalFile:
    def __init__(self) -> None:
        self.relative_local_file_offset: int
        self.version_needed: bytes 
        self.general_purpose_bit_flag: bytes
        self.compression_method: int
        self.last_modification_time: bytes
        self.last_modification_date: bytes
        self.crc32: bytes
        self.compressed_size: int
        self.uncompressed_size: int
        self.file_name_length: int
        self.extra_field_length: int
        self.file_name: str
        self.extra_field: bytes
        self.last_byte: int

    def load_data(self, handler):
        return handler.get_bytes_from_file(
            from_b=self.last_byte + self.relative_local_file_offset,
            size=self.compressed_size,
            raw_response=True
        )

    @classmethod
    def from_bytes(cls, data, offset, handler):
        local_file = cls()
        local_file.relative_local_file_offset = 0
        local_file.version_needed = data[4:6]
        local_file.general_purpose_bit_flag = data[6:8]
        local_file.compression_method = int.from_bytes(data[8:10], "little")
        local_file.last_modification_time = data[10:12]
        local_file.last_modification_date = data[12:14]
        local_file.crc32 = data[14:18]
        local_file.compressed_size = int.from_bytes(data[18:22], "little")
        local_file.uncompressed_size = int.from_bytes(data[22:26], "little")
        local_file.file_name_length = int.from_bytes(data[26:28], "little")
        local_file.extra_field_length = int.from_bytes(data[28:30], "little")

        extra_data = handler.get_bytes_from_file(
            from_b=30 + offset,
            size=local_file.file_name_length + local_file.extra_field_length,
        )

        local_file.file_name = bytes(
            extra_data[0: local_file.file_name_length]
        ).decode()

        local_file.extra_field = data[
                                 local_file.file_name_length: local_file.file_name_length
                                                              + local_file.extra_field_length
                                 ]
        local_file.last_byte = (
                local_file.file_name_length + local_file.extra_field_length + 30
        )
        return local_file

    def __str__(self):
        return f"\nCompressionMethod: {self.compression_method} \nFileNameLen: {self.file_name_length} \nFileName: {self.file_name} \nCompressedSize: {self.compressed_size} \nUncompressedSize: {self.uncompressed_size}"


class CentralDirectoryFile:
    def __init__(self, product):
        self.product = product
        self.version_made_by: bytes
        self.version_needed_to_extract: bytes
        self.general_purpose_bit_flag: bytes
        self.compression_method: int 
        self.last_modification_time: bytes
        self.last_modification_date: bytes
        self.crc32: int
        self.compressed_size: int
        self.uncompressed_size: int
        self.file_name_length: int
        self.extra_field_length: int
        self.file_comment_length: int
        self.disk_number_start: bytes
        self.int_file_attrs: bytes
        self.ext_file_attrs: bytes
        self.relative_local_file_offset: int
        self.file_name: str
        self.extra_field: BytesIO 
        self.comment: bytes
        self.last_byte: int
        self.file_data_offset: int

    @classmethod
    def from_bytes(cls, data, product):
        cd_file = cls(product)

        cd_file.version_made_by = data[4:6]
        cd_file.version_needed_to_extract = data[6:8]
        cd_file.general_purpose_bit_flag = data[8:10]
        cd_file.compression_method = int.from_bytes(data[10:12], "little")
        cd_file.last_modification_time = data[12:14]
        cd_file.last_modification_date = data[14:16]
        cd_file.crc32 = int.from_bytes(data[16:20], "little")
        cd_file.compressed_size = int.from_bytes(data[20:24], "little")
        cd_file.uncompressed_size = int.from_bytes(data[24:28], "little")
        cd_file.file_name_length = int.from_bytes(data[28:30], "little")
        cd_file.extra_field_length = int.from_bytes(data[30:32], "little")
        cd_file.file_comment_length = int.from_bytes(data[32:34], "little")
        cd_file.disk_number_start = data[34:36]
        cd_file.int_file_attrs = data[36:38]
        cd_file.ext_file_attrs = data[38:42]
        cd_file.relative_local_file_offset = int.from_bytes(data[42:46], "little")
        cd_file.file_data_offset = 0

        extra_field_start = 46 + cd_file.file_name_length
        cd_file.file_name = bytes(data[46:extra_field_start]).decode()

        cd_file.extra_field = BytesIO(data[
                              extra_field_start: extra_field_start + cd_file.extra_field_length
                              ])

        field = None
        while True:
            id = int.from_bytes(cd_file.extra_field.read(2), "little")
            size = int.from_bytes(cd_file.extra_field.read(2), "little")

            if id == 0x01:
                if cd_file.extra_field_length - cd_file.extra_field.tell() >= size:
                    field = BytesIO(cd_file.extra_field.read(size))
                break
            
            cd_file.extra_field.seek(size, 1)

            if cd_file.extra_field_length - cd_file.extra_field.tell() == 0:
                break
        

        if field:
            if cd_file.uncompressed_size == 0xFFFFFFFF:
                cd_file.uncompressed_size = int.from_bytes(field.read(8), "little")

            if cd_file.compressed_size == 0xFFFFFFFF:
                cd_file.compressed_size = int.from_bytes(field.read(8), "little")

            if cd_file.relative_local_file_offset == 0xFFFFFFFF:
                cd_file.relative_local_file_offset = int.from_bytes(field.read(8), "little")

        comment_start = extra_field_start + cd_file.extra_field_length
        cd_file.comment = data[
                          comment_start: comment_start + cd_file.file_comment_length
                          ]

        cd_file.last_byte = comment_start + cd_file.file_comment_length

        return cd_file, comment_start + cd_file.file_comment_length
    
    def is_symlink(self):
        return stat.S_ISLNK(int.from_bytes(self.ext_file_attrs, "little") >> 16)

    def as_dict(self):
        return {'file_name': self.file_name, 'crc32': self.crc32, 'compressed_size': self.compressed_size, 'size': self.uncompressed_size, 'is_symlink': self.is_symlink()}

    def __str__(self):
        return f"\nCompressionMethod: {self.compression_method} \nFileNameLen: {self.file_name_length} \nFileName: {self.file_name} \nStartDisk: {self.disk_number_start} \nCompressedSize: {self.compressed_size} \nUncompressedSize: {self.uncompressed_size}"

    def __repr__(self):
        return self.file_name


class CentralDirectory:
    def __init__(self, product):
        self.files = []
        self.product = product

    @staticmethod
    def create_central_dir_file(data, product):
        return CentralDirectoryFile.from_bytes(data, product)

    @classmethod
    def from_bytes(cls, data, n, product):
        central_dir = cls(product)
        for record in range(n):
            cd_file, next_offset = central_dir.create_central_dir_file(data, product)
            central_dir.files.append(cd_file)
            data = data[next_offset:]
            if record == 0:
                continue
            
            prev_i = record - 1
            if not (prev_i >= 0 and prev_i < len(central_dir.files)):
                continue
            prev = central_dir.files[prev_i]
            prev.file_data_offset = cd_file.relative_local_file_offset - prev.compressed_size
        
        return central_dir

class Zip64EndOfCentralDirLocator:
    def __init__(self):
        self.number_of_disk: int
        self.zip64_end_of_cd_offset: int
        self.total_number_of_disks: int

    @classmethod
    def from_bytes(cls, data):
        zip64_end_of_cd = cls()
        zip64_end_of_cd.number_of_disk = int.from_bytes(data[4:8], "little")
        zip64_end_of_cd.zip64_end_of_cd_offset = int.from_bytes(data[8:16], "little")
        zip64_end_of_cd.total_number_of_disks = int.from_bytes(data[16:20], "little")
        return zip64_end_of_cd
    
    def __str__(self):
        return f"\nZIP64EOCDLocator\nDisk Number: {self.number_of_disk}\nZ64_EOCD Offset: {self.zip64_end_of_cd_offset}\nNumber of disks: {self.total_number_of_disks}"

class Zip64EndOfCentralDir:
    def __init__(self):
        self.size: int
        self.version_made_by: bytes
        self.version_needed: bytes
        self.number_of_disk: bytes
        self.central_directory_start_disk: bytes
        self.number_of_entries_on_this_disk: int
        self.number_of_entries_total: int
        self.size_of_central_directory: int
        self.central_directory_offset: int
        self.extensible_data = None

    @classmethod
    def from_bytes(cls, data):
        end_of_cd = cls()

        end_of_cd.size = int.from_bytes(data[4:12], "little")
        end_of_cd.version_made_by = data[12:14]
        end_of_cd.version_needed = data[14:16]
        end_of_cd.number_of_disk = data[16:20]
        end_of_cd.central_directory_start_disk = data[20:24]
        end_of_cd.number_of_entries_on_this_disk = int.from_bytes(data[24:32], "little")
        end_of_cd.number_of_entries_total = int.from_bytes(data[32:40], "little")
        end_of_cd.size_of_central_directory = int.from_bytes(data[40:48], "little")
        end_of_cd.central_directory_offset = int.from_bytes(data[48:56], "little")

        return end_of_cd

    def __str__(self) -> str:
        return f"\nZ64 EndOfCD\nSize: {self.size}\nNumber of disk: {self.number_of_disk}\nEntries on this disk: {self.number_of_entries_on_this_disk}\nEntries total: {self.number_of_entries_total}\nCD offset: {self.central_directory_offset}"


class EndOfCentralDir:
    def __init__(self):
        self.number_of_disk: bytes
        self.central_directory_disk: bytes
        self.central_directory_records: int
        self.size_of_central_directory: int
        self.central_directory_offset: int
        self.comment_length: bytes
        self.comment: bytes

    @classmethod
    def from_bytes(cls, data):
        central_dir = cls()
        central_dir.number_of_disk = data[4:6]
        central_dir.central_directory_disk = data[6:8]
        central_dir.central_directory_records = int.from_bytes(data[8:10], "little")
        central_dir.size_of_central_directory = int.from_bytes(data[12:16], "little")
        central_dir.central_directory_offset = int.from_bytes(data[16:20], "little")
        central_dir.comment_length = data[20:22]
        central_dir.comment = data[
                              22: 22 + int.from_bytes(central_dir.comment_length, "little")
                              ]

        return central_dir

    def __str__(self):
        return f"\nDiskNumber: {self.number_of_disk} \nCentralDirRecords: {self.central_directory_records} \nCentralDirSize: {self.size_of_central_directory} \nCentralDirOffset: {self.central_directory_offset}"


class InstallerHandler:
    def __init__(self, url, product_id, session):
        self.url = url
        self.product = product_id
        self.session = session
        self.file_size = 0
        beginning_of_file = self.get_bytes_from_file(
            from_b=1024*512, size=1024*1024, add_archive_index=False
        )
        
        self.start_of_archive_index = beginning_of_file.find(LOCAL_FILE_HEADER) + 1024*512

        # ZIP contents
        self.central_directory_offset: int
        self.central_directory_records: int
        self.size_of_central_directory: int
        self.central_directory: CentralDirectory

    def get_bytes_from_file(self, from_b=-1, size=None, add_archive_index=True, raw_response=False):
        if add_archive_index:
            from_b += self.start_of_archive_index

        from_b_repr = str(from_b) if from_b > -1 else ""
        if size:
            end_b = from_b + size - 1
        else:
            end_b = ""
        range_header = self.get_range_header(from_b_repr, end_b)

        response = self.session.get(self.url, headers={'Range': range_header},
                                    allow_redirects=False, stream=raw_response)
        if response.status_code == 302:
            # Skip content-system API
            self.url = response.headers.get('Location') or self.url
            return self.get_bytes_from_file(from_b, size, add_archive_index, raw_response)
        if not self.file_size:
            self.file_size = int(response.headers.get("Content-Range").split("/")[-1])
        if raw_response:
            return response
        else:
            data = response.content
            return data

    @staticmethod
    def get_range_header(from_b="", to_b=""):
        return f"bytes={from_b}-{to_b}"

    def setup(self):
        self.__find_end_of_cd()
        self.__find_central_directory()

    def __find_end_of_cd(self):
        end_of_cd_data = self.get_bytes_from_file(
            from_b=self.file_size - 100, add_archive_index=False
        )

        end_of_cd_header_data_index = end_of_cd_data.find(END_OF_CENTRAL_DIRECTORY)
        zip64_end_of_cd_locator_index = end_of_cd_data.find(ZIP_64_END_OF_CD_LOCATOR)
        assert end_of_cd_header_data_index != -1
        end_of_cd = EndOfCentralDir.from_bytes(end_of_cd_data[end_of_cd_header_data_index:])
        if end_of_cd.central_directory_offset == 0xFFFFFFFF:
            assert zip64_end_of_cd_locator_index != -1
            # We need to find zip64 headers

            zip64_end_of_cd_locator = Zip64EndOfCentralDirLocator.from_bytes(end_of_cd_data[zip64_end_of_cd_locator_index:])
            zip64_end_of_cd_data = self.get_bytes_from_file(from_b=zip64_end_of_cd_locator.zip64_end_of_cd_offset, size=200)
            zip64_end_of_cd = Zip64EndOfCentralDir.from_bytes(zip64_end_of_cd_data)

            self.central_directory_offset = zip64_end_of_cd.central_directory_offset
            self.size_of_central_directory = zip64_end_of_cd.size_of_central_directory
            self.central_directory_records = zip64_end_of_cd.number_of_entries_total
        else:
            self.central_directory_offset = end_of_cd.central_directory_offset
            self.size_of_central_directory = end_of_cd.size_of_central_directory
            self.central_directory_records = end_of_cd.central_directory_records 

    def __find_central_directory(self):
        central_directory_data = self.get_bytes_from_file(
            from_b=self.central_directory_offset,
            size=self.size_of_central_directory,
        )

        assert central_directory_data[:4] == CENTRAL_DIRECTORY

        self.central_directory = CentralDirectory.from_bytes(
            central_directory_data, self.central_directory_records, self.product
        )
        last_entry = self.central_directory.files[-1]
        last_entry.file_data_offset = self.central_directory_offset - last_entry.compressed_size


class LinuxFile:
    def __init__(self, product, path, compression, start, compressed_size, size, checksum, executable):
        self.product = product
        self.path = path
        self.compression = compression == 8
        self.offset = start
        self.compressed_size = compressed_size
        self.size = size
        self.hash = str(checksum)
        self.flags = []
        if executable:
            self.flags.append("executable")

0707010000001C000081A400000000000000000000000166E0651E0000169B000000000000000000000000000000000000002A00000000heroic-gogdl-1.1.2/gogdl/dl/objects/v1.pyimport json
import os
from gogdl.dl import dl_utils
from gogdl.dl.objects import generic, v2
from gogdl import constants


class Depot:
    def __init__(self, target_lang, depot_data):
        self.target_lang = target_lang
        self.languages = depot_data["languages"]
        self.game_ids = depot_data["gameIDs"]
        self.size = int(depot_data["size"])
        self.manifest = depot_data["manifest"]

    def check_language(self):
        status = True
        for lang in self.languages:
            status = lang == "Neutral" or lang == self.target_lang
            if status:
                break
        return status

class Directory:
    def __init__(self, item_data):
        self.path = item_data["path"].replace(constants.NON_NATIVE_SEP, os.sep).lstrip(os.sep)

class Dependency:
    def __init__(self, data):
        self.id = data["redist"]
        self.size = data.get("size")
        self.target_dir = data.get("targetDir")


class File:
    def __init__(self, data, product_id):
        self.offset = data.get("offset")
        self.hash = data.get("hash")
        self.url = data.get("url")
        self.path = data["path"].lstrip("/")
        self.size = data["size"]
        self.flags = []
        if data.get("support"):
            self.flags.append("support")
        if data.get("executable"):
            self.flags.append("executble")

        self.product_id = product_id

class Manifest:
    def __init__(self, platform, meta, language, dlcs, api_handler, dlc_only):
        self.platform = platform
        self.data = meta
        self.data['HGLPlatform'] = platform
        self.data["HGLInstallLanguage"] = language
        self.data["HGLdlcs"] = dlcs
        self.product_id = meta["product"]["rootGameID"]
        self.dlcs = dlcs
        self.dlc_only = dlc_only 
        self.all_depots = [] 
        self.depots = self.parse_depots(language, meta["product"]["depots"])
        self.dependencies = [Dependency(depot) for depot in meta["product"]["depots"] if depot.get('redist')]
        self.dependencies_ids = [depot['redist'] for depot in meta["product"]["depots"] if depot.get('redist')]

        self.api_handler = api_handler

        self.files = []
        self.dirs = []

    @classmethod
    def from_json(cls, meta, api_handler):
        manifest = cls(meta['HGLPlatform'], meta, meta['HGLInstallLanguage'], meta["HGLdlcs"], api_handler, False)
        return manifest
    
    def serialize_to_json(self):
        return json.dumps(self.data)

    def parse_depots(self, language, depots):
        parsed = []
        dlc_ids = [dlc["id"] for dlc in self.dlcs]
        for depot in depots:
            if depot.get("redist"):
                continue
            
            for g_id in depot["gameIDs"]:
                if g_id in dlc_ids or (not self.dlc_only and self.product_id == g_id):
                    new_depot = Depot(language, depot)
                    parsed.append(new_depot)
                    self.all_depots.append(new_depot)
                    break
        return list(filter(lambda x: x.check_language(), parsed))

    def list_languages(self):
        languages_dict = set()
        for depot in self.all_depots:
            for language in depot.languages:
                if language != "Neutral":
                    languages_dict.add(language)

        return list(languages_dict)

    def calculate_download_size(self):
        data = dict()

        for depot in self.all_depots:
            for product_id in depot.game_ids:
                if not product_id in data:
                    data[product_id] = dict()
                product_data = data[product_id]
                for lang in depot.languages:
                    if lang == "Neutral":
                        lang = "*"
                    if not lang in product_data:
                        product_data[lang] = {"download_size": 0, "disk_size": 0}
                    
                    product_data[lang]["download_size"] += depot.size
                    product_data[lang]["disk_size"] += depot.size
        
        return data 

    
    def get_files(self):
        for depot in self.depots:
            manifest = dl_utils.get_json(self.api_handler, f"{constants.GOG_CDN}/content-system/v1/manifests/{depot.game_ids[0]}/{self.platform}/{self.data['product']['timestamp']}/{depot.manifest}")
            for record in manifest["depot"]["files"]:
                if "directory" in record:
                    self.dirs.append(Directory(record)) 
                else:
                    self.files.append(File(record, depot.game_ids[0]))

class ManifestDiff(generic.BaseDiff):
    def __init__(self):
        super().__init__()
    
    @classmethod
    def compare(cls, new_manifest, old_manifest=None):
        comparison = cls()

        if not old_manifest:
            comparison.new = new_manifest.files
            return comparison

        new_files = dict()
        for file in new_manifest.files:
            new_files.update({file.path.lower(): file})
        
        old_files = dict()
        for file in old_manifest.files:
            old_files.update({file.path.lower(): file})

        for old_file in old_files.values():
            if not new_files.get(old_file.path.lower()):
                comparison.deleted.append(old_file)
        
        if type(old_manifest) == v2.Manifest:
            comparison.new = new_manifest.files
            return comparison
    
        for new_file in new_files.values():
            old_file = old_files.get(new_file.path.lower())
            if not old_file:
                comparison.new.append(new_file)
            else:
                if new_file.hash != old_file.hash:
                    comparison.changed.append(new_file)

        return comparison
0707010000001D000081A400000000000000000000000166E0651E00002A8D000000000000000000000000000000000000002A00000000heroic-gogdl-1.1.2/gogdl/dl/objects/v2.pyimport json
import os

from gogdl.dl import dl_utils
from gogdl.dl.objects import generic, v1
from gogdl import constants


class DepotFile:
    def __init__(self, item_data, product_id):
        self.flags = item_data.get("flags") or list()
        self.path = item_data["path"].replace(constants.NON_NATIVE_SEP, os.sep).lstrip(os.sep)
        if "support" in self.flags:
            self.path = os.path.join(product_id, self.path)
        self.chunks = item_data["chunks"]
        self.md5 = item_data.get("md5")
        self.sha256 = item_data.get("sha256")
        self.product_id = product_id


# That exists in some depots, indicates directory to be created, it has only path in it
# Yes that's the thing
class DepotDirectory:
    def __init__(self, item_data):
        self.path = item_data["path"].replace(constants.NON_NATIVE_SEP, os.sep).rstrip(os.sep)
    
class DepotLink:
    def __init__(self, item_data):
        self.path = item_data["path"]
        self.target = item_data["target"]


class Depot:
    def __init__(self, target_lang, depot_data):
        self.target_lang = target_lang
        self.languages = depot_data["languages"]
        self.bitness = depot_data.get("osBitness")
        self.product_id = depot_data["productId"]
        self.compressed_size = depot_data.get("compressedSize")
        self.size = depot_data["size"]
        self.manifest = depot_data["manifest"]

    def check_language(self):
        status = False
        for lang in self.languages:
            status = (
                    lang == "*"
                    or self.target_lang == lang
                    or self.target_lang.split("-")[0] == lang
            )
            if status:
                break
        return status

class Manifest:
    def __init__(self, meta, language, dlcs, api_handler, dlc_only):
        self.data = meta
        self.data["HGLInstallLanguage"] = language
        self.data["HGLdlcs"] = dlcs
        self.product_id = meta["baseProductId"]
        self.dlcs = dlcs
        self.dlc_only = dlc_only
        self.all_depots = []
        self.depots = self.parse_depots(language, meta["depots"])
        self.dependencies_ids = meta.get("dependencies")
        if not self.dependencies_ids:
            self.dependencies_ids = list()
        self.install_directory = meta["installDirectory"]

        self.api_handler = api_handler

        self.files = []
        self.dirs = []

    @classmethod
    def from_json(cls, meta, api_handler):
        manifest = cls(meta, meta["HGLInstallLanguage"], meta["HGLdlcs"], api_handler, False)
        return manifest

    def serialize_to_json(self):
        return json.dumps(self.data)

    def parse_depots(self, language, depots):
        parsed = []
        dlc_ids = [dlc["id"] for dlc in self.dlcs]
        for depot in depots:
            if depot["productId"] in dlc_ids or (
                    not self.dlc_only and self.product_id == depot["productId"]
            ):
                new_depot = Depot(language, depot)
                parsed.append(new_depot)
                self.all_depots.append(new_depot)
                

        return list(filter(lambda x: x.check_language(), parsed))

    def list_languages(self):
        languages_dict = set()
        for depot in self.all_depots:
            for language in depot.languages:
                if language != "*":
                    languages_dict.add(language)

        return list(languages_dict)

    def calculate_download_size(self):
        data = dict()

        for depot in self.all_depots:
            if not depot.product_id in data:
                data[depot.product_id] = dict()
                data[depot.product_id]['*'] = {"download_size": 0, "disk_size": 0}
            product_data = data[depot.product_id]
            for lang in depot.languages:
                if not lang in product_data:
                    product_data[lang] = {"download_size":0, "disk_size":0} 
                
                product_data[lang]["download_size"] += depot.compressed_size
                product_data[lang]["disk_size"] += depot.size

        return data 

    def get_files(self):
        for depot in self.depots:
            manifest = dl_utils.get_zlib_encoded(
                self.api_handler,
                f"{constants.GOG_CDN}/content-system/v2/meta/{dl_utils.galaxy_path(depot.manifest)}",
            )[0]
            for item in manifest["depot"]["items"]:
                if item["type"] == "DepotFile":
                    self.files.append(DepotFile(item, depot.product_id))
                elif item["type"] == "DepotLink":
                    self.files.append(DepotLink(item))
                else:
                    self.dirs.append(DepotDirectory(item))

class FileDiff:
    def __init__(self):
        self.file: DepotFile
        self.old_file_flags: list[str]
        self.disk_size_diff: int = 0

    @classmethod
    def compare(cls, new: DepotFile, old: DepotFile):
        diff = cls()
        diff.disk_size_diff = sum([ch['size'] for ch in new.chunks])
        diff.disk_size_diff -= sum([ch['size'] for ch in old.chunks])
        diff.old_file_flags = old.flags
        for new_chunk in new.chunks:
            old_offset = 0
            for old_chunk in old.chunks:
                if old_chunk["md5"] == new_chunk["md5"]:
                    new_chunk["old_offset"] = old_offset
                old_offset += old_chunk["size"]
        diff.file = new
        return diff

# Using xdelta patching
class FilePatchDiff:
    def __init__(self, data):
        self.md5_source = data['md5_source']
        self.md5_target = data['md5_target']
        self.source = data['path_source'].replace('\\', '/')
        self.target = data['path_target'].replace('\\', '/')
        self.md5 = data['md5']
        self.chunks = data['chunks']

        self.old_file: DepotFile
        self.new_file: DepotFile

class ManifestDiff(generic.BaseDiff):
    def __init__(self):
        super().__init__()

    @classmethod
    def compare(cls, manifest, old_manifest=None, patch=None):
        comparison = cls()
        is_manifest_upgrade = isinstance(old_manifest, v1.Manifest)

        if not old_manifest:
            comparison.new = manifest.files
            return comparison

        new_files = dict()
        for file in manifest.files:
            new_files.update({file.path.lower(): file})

        old_files = dict()
        for file in old_manifest.files:
            old_files.update({file.path.lower(): file})

        for old_file in old_files.values():
            if not new_files.get(old_file.path.lower()):
                comparison.deleted.append(old_file)

        for new_file in new_files.values():
            old_file = old_files.get(new_file.path.lower())
            if isinstance(new_file, DepotLink):
                comparison.links.append(new_file)
                continue
            if not old_file:
                comparison.new.append(new_file)
            else:
                if is_manifest_upgrade:
                    if len(new_file.chunks) == 0:
                        continue
                    new_final_sum = new_file.md5 or new_file.chunks[0]["md5"]
                    if new_final_sum:
                        if old_file.hash != new_final_sum:
                            comparison.changed.append(new_file)
                    continue

                patch_file = None
                if patch and len(old_file.chunks):
                    for p_file in patch.files:
                        old_final_sum = old_file.md5 or old_file.chunks[0]["md5"]
                        if p_file.md5_source == old_final_sum:
                            patch_file = p_file
                            patch_file.old_file = old_file
                            patch_file.new_file = new_file 

                if patch_file:
                    comparison.changed.append(patch_file)
                    continue

                if len(new_file.chunks) == 1 and len(old_file.chunks) == 1:
                    if new_file.chunks[0]["md5"] != old_file.chunks[0]["md5"]:
                        comparison.changed.append(new_file)
                else:
                    if (new_file.md5 and old_file.md5 and new_file.md5 != old_file.md5) or (new_file.sha256 and old_file.sha256 and old_file.sha256 != new_file.sha256):
                        comparison.changed.append(FileDiff.compare(new_file, old_file))
                    elif len(new_file.chunks) != len(old_file.chunks):
                        comparison.changed.append(FileDiff.compare(new_file, old_file))
        return comparison

class Patch:
    def __init__(self):
        self.patch_data = {}
        self.files = []

    @classmethod
    def get(cls,  manifest, old_manifest, lang: str, dlcs: list, api_handler):
        if isinstance(manifest, v1.Manifest) or isinstance(old_manifest, v1.Manifest):
            return None
        from_build = old_manifest.data.get('buildId')
        to_build = manifest.data.get('buildId')
        if not from_build or not to_build:
            return None
        dlc_ids = [dlc["id"] for dlc in dlcs]
        patch_meta = dl_utils.get_zlib_encoded(api_handler, f'{constants.GOG_CONTENT_SYSTEM}/products/{manifest.product_id}/patches?_version=4&from_build_id={from_build}&to_build_id={to_build}')[0]
        if not patch_meta or patch_meta.get('error'):
            return None
        patch_data = dl_utils.get_zlib_encoded(api_handler, patch_meta['link'])[0]
        if not patch_data:
            return None
         
        if patch_data['algorithm'] != 'xdelta3':
            print("Unsupported patch algorithm")
            return None
        
        depots = []
        # Get depots we need
        for depot in patch_data['depots']:
            if depot['productId'] == patch_data['baseProductId'] or depot['productId'] in dlc_ids:
                if lang in depot['languages']:
                    depots.append(depot)

        if not depots:
            return None

        files = []
        fail = False
        for depot in depots:
            depotdiffs = dl_utils.get_zlib_encoded(api_handler, f'{constants.GOG_CDN}/content-system/v2/patches/meta/{dl_utils.galaxy_path(depot["manifest"])}')[0]
            if not depotdiffs:
                fail = True
                break
            for diff in depotdiffs['depot']['items']:
                if diff['type'] == 'DepotDiff':
                   files.append(FilePatchDiff(diff))
                else:
                    print('Unknown type in patcher', diff['type'])
                    return None
    
        if fail:
            # TODO: Handle this beter
            # Maybe exception?
            print("Failed to get patch manifests")
            return None
        
        patch = cls()
        patch.patch_data = patch_data
        patch.files = files

        return patch
0707010000001E000081ED00000000000000000000000166E0651E00001002000000000000000000000000000000000000002B00000000heroic-gogdl-1.1.2/gogdl/dl/progressbar.pyimport queue
from multiprocessing import Queue
import threading
import logging
from time import sleep, time


class ProgressBar(threading.Thread):
    def __init__(self, max_val: int, speed_queue: Queue, write_queue: Queue):
        self.logger = logging.getLogger("PROGRESS")
        self.downloaded = 0
        self.total = max_val
        self.speed_queue = speed_queue
        self.write_queue = write_queue
        self.started_at = time()
        self.last_update = time()
        self.completed = False

        self.decompressed = 0

        self.downloaded_since_last_update = 0
        self.decompressed_since_last_update = 0
        self.written_since_last_update = 0
        self.read_since_last_update = 0

        self.written_total = 0

        super().__init__(target=self.loop)

    def loop(self):
        while not self.completed:
            self.print_progressbar()
            self.downloaded_since_last_update = self.decompressed_since_last_update = 0
            self.written_since_last_update = self.read_since_last_update = 0
            timestamp = time()
            while not self.completed and (time() - timestamp) < 1:
                try:
                    dl, dec = self.speed_queue.get(timeout=1)
                    self.downloaded_since_last_update += dl
                    self.decompressed_since_last_update += dec
                except queue.Empty:
                    pass
                try:
                    wr, r = self.write_queue.get(timeout=1)
                    self.written_since_last_update += wr
                    self.read_since_last_update += r
                except queue.Empty:
                    pass
                
        self.print_progressbar()
    def print_progressbar(self):
        percentage = (self.written_total / self.total) * 100
        running_time = time() - self.started_at
        runtime_h = int(running_time // 3600)
        runtime_m = int((running_time % 3600) // 60)
        runtime_s = int((running_time % 3600) % 60)

        print_time_delta = time() - self.last_update
        
        current_dl_speed = 0
        current_decompress = 0
        if print_time_delta:
            current_dl_speed = self.downloaded_since_last_update / print_time_delta
            current_decompress = self.decompressed_since_last_update / print_time_delta
            current_w_speed = self.written_since_last_update / print_time_delta
            current_r_speed = self.read_since_last_update / print_time_delta
        else:
            current_w_speed = 0
            current_r_speed = 0

        if percentage > 0:
            estimated_time = (100 * running_time) / percentage - running_time
        else:
            estimated_time = 0
        estimated_time = max(estimated_time, 0) # Cap to 0

        estimated_h = int(estimated_time // 3600)
        estimated_time = estimated_time % 3600
        estimated_m = int(estimated_time // 60)
        estimated_s = int(estimated_time % 60)

        self.logger.info(
            f"= Progress: {percentage:.02f} {self.written_total}/{self.total}, "
            + f"Running for: {runtime_h:02d}:{runtime_m:02d}:{runtime_s:02d}, "
            + f"ETA: {estimated_h:02d}:{estimated_m:02d}:{estimated_s:02d}"
        )

        self.logger.info(
            f"= Downloaded: {self.downloaded / 1024 / 1024:.02f} MiB, "
            f"Written: {self.written_total / 1024 / 1024:.02f} MiB"
        )

        self.logger.info(
            f" + Download\t- {current_dl_speed / 1024 / 1024:.02f} MiB/s (raw) "
            f"/ {current_decompress / 1024 / 1024:.02f} MiB/s (decompressed)"
        )

        self.logger.info(
            f" + Disk\t- {current_w_speed / 1024 / 1024:.02f} MiB/s (write) / "
            f"{current_r_speed / 1024 / 1024:.02f} MiB/s (read)"
        )

        self.last_update = time()

    def update_downloaded_size(self, addition):
        self.downloaded += addition

    def update_decompressed_size(self, addition):
        self.decompressed += addition

    def update_bytes_written(self, addition):
        self.written_total += addition
0707010000001F000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000002400000000heroic-gogdl-1.1.2/gogdl/dl/workers07070100000020000081A400000000000000000000000166E0651E00000B6B000000000000000000000000000000000000002D00000000heroic-gogdl-1.1.2/gogdl/dl/workers/linux.pyimport os
import zlib

from gogdl.dl.objects.linux import LocalFile


class DLWorker:
    def __init__(self, file_data, path):
        self.data = file_data
        self.install_path = path
        self.file_path = self.data.file_name.replace("data/noarch", self.install_path)

        self.retries = 0

    def verify(self):
        file_handle = open(self.file_path, 'rb')
        crc = 0
        while data := file_handle.read(1024 * 1024):
            crc = zlib.crc32(data, crc)

        return crc == self.data.crc32

    def work(self, installer_handler):
        if os.path.exists(self.file_path):
            if self.verify():
                return

        file_permissions = bin(int.from_bytes(self.data.ext_file_attrs, "little"))[9:][:9]

        # Load local file header
        file_data = installer_handler.get_bytes_from_file(
            from_b=self.data.relative_local_file_offset,
            size=30,
        )
        local_file = LocalFile.from_bytes(
            file_data,
            self.data.relative_local_file_offset,
            installer_handler,  # Passsing in handler to be able to pull more data
        )
        local_file.relative_local_file_offset = self.data.relative_local_file_offset

        directory, name = os.path.split(self.file_path)
        os.makedirs(directory, exist_ok=True)

        response = local_file.load_data(installer_handler)
        total = response.headers.get("Content-Length")

        with open(self.file_path + ".tmp", "wb") as f:
            if total is None:
                f.write(response.content)
            else:
                total = int(total)
                for data in response.iter_content(
                        chunk_size=max(int(total / 1000), 1024 * 1024)
                ):
                    f.write(data)

            f.close()

        with open(self.file_path, "wb") as f:
            tmp_handle = open(self.file_path + ".tmp", 'rb')
            decompressor = zlib.decompressobj(-15)

            if local_file.compression_method == 8:
                while stream := tmp_handle.read(1024 * 1024):
                    decompressed = decompressor.decompress(stream)
                    f.write(decompressed)
                f.flush()
                f.close()
            elif local_file.compression_method == 0:
                tmp_handle.close()
                f.close()
                os.rename(self.file_path + ".tmp", self.file_path)
            else:
                print("Unsupported compression method", local_file.compression_method)

        if os.path.exists(self.file_path + ".tmp"):
            os.remove(self.file_path + ".tmp")

        if not self.verify():
            if self.retries < 3:
                self.retries += 1
                os.remove(self.file_path)
                self.work(installer_handler)
                return

        os.chmod(self.file_path, int(f"0b{file_permissions}", base=0))
07070100000021000081A400000000000000000000000166E0651E00004591000000000000000000000000000000000000003500000000heroic-gogdl-1.1.2/gogdl/dl/workers/task_executor.pyfrom multiprocessing.shared_memory import SharedMemory
import os
from queue import Empty
import shutil
import sys
import stat
import traceback
import time
import requests
import zlib
import hashlib
from io import BytesIO
from typing import Optional, Union
from copy import copy
from gogdl.dl import dl_utils
from dataclasses import dataclass
from enum import Enum, auto
from multiprocessing import Process, Queue
from gogdl.dl.objects.generic import MemorySegment, TaskFlag, TerminateWorker
from gogdl.xdelta import patcher


class FailReason(Enum):
    UNKNOWN = 0
    CHECKSUM = auto()
    CONNECTION = auto()
    UNAUTHORIZED = auto()

    MISSING_CHUNK = auto()


@dataclass
class DownloadTask:
    product_id: str

@dataclass
class DownloadTask1(DownloadTask):
    offset: int
    size: int
    # This sum is not valid MD5 as it contains chunk id too
    # V1 doesn't support chunks, this is sort of forceful way to use them
    # in this algorithm
    compressed_sum: str
    memory_segment: MemorySegment

@dataclass
class DownloadTask2(DownloadTask):
    compressed_sum: str
    memory_segment: MemorySegment


@dataclass
class WriterTask:
    # Root directory of game files
    destination: str
    # File path from manifest
    file_path: str
    flags: TaskFlag

    hash: Optional[str] = None
    size: Optional[int] = None
    shared_memory: Optional[MemorySegment] = None
    old_destination: Optional[str] = None
    old_file: Optional[str] = None
    old_offset: Optional[int] = None

    patch_file: Optional[str] = None

@dataclass
class DownloadTaskResult:
    success: bool
    fail_reason: Optional[FailReason]
    task: Union[DownloadTask2, DownloadTask1]
    download_size: Optional[int] = None
    decompressed_size: Optional[int] = None

@dataclass
class WriterTaskResult:
    success: bool
    task: Union[WriterTask, TerminateWorker]
    written: int = 0


class Download(Process):
    def __init__(self, shared_memory, download_queue, results_queue, speed_queue, shared_secure_links):
        self.shared_memory = SharedMemory(name=shared_memory)
        self.download_queue: Queue = download_queue
        self.results_queue: Queue = results_queue
        self.speed_queue: Queue = speed_queue
        self.secure_links: dict = shared_secure_links
        self.session = requests.session()
        self.early_exit = False
        super().__init__()

    def run(self):
        while not self.early_exit:
            try:
                task: Union[DownloadTask1, DownloadTask2, TerminateWorker] = self.download_queue.get(timeout=1)
            except Empty:
               continue 

            if isinstance(task, TerminateWorker):
                break

            if type(task) == DownloadTask2:
                self.v2(task)
            elif type(task) == DownloadTask1:
                self.v1(task)

        self.session.close()
        self.shared_memory.close()

    def v2(self, task: DownloadTask2):
        retries = 5 
        urls = self.secure_links[task.product_id]

        compressed_md5 = task.compressed_sum

        endpoint = copy(urls[0])
        if task.product_id != 'redist':
            endpoint["parameters"]["path"] += f"/{dl_utils.galaxy_path(compressed_md5)}"
            url = dl_utils.merge_url_with_params(
                endpoint["url_format"], endpoint["parameters"]
            )
        else:
            endpoint["url"] += "/" + dl_utils.galaxy_path(compressed_md5)
            url = endpoint["url"]

        buffer = bytes()
        compressed_sum = hashlib.md5()
        download_size = 0
        response = None
        while retries > 0:
            buffer = bytes()
            compressed_sum = hashlib.md5()
            download_size = 0
            decompressor = zlib.decompressobj()
            try:
                response = self.session.get(url, stream=True, timeout=10)
                response.raise_for_status()
                for chunk in response.iter_content(1024 * 512):
                    download_size += len(chunk)
                    compressed_sum.update(chunk)
                    decompressed = decompressor.decompress(chunk)
                    buffer += decompressed
                    self.speed_queue.put((len(chunk), len(decompressed)))

            except Exception as e:
                print("Connection failed", e)
                if response and response.status_code == 401:
                    self.results_queue.put(DownloadTaskResult(False, FailReason.UNAUTHORIZED, task))
                    print("Connection failed, unauthorized")
                    return
                retries -= 1
                time.sleep(2)
                continue
            break
        else:
            self.results_queue.put(DownloadTaskResult(False, FailReason.CHECKSUM, task))
            return

        decompressed_size = 0
        try:
            decompressed_size = len(buffer)
            self.shared_memory.buf[task.memory_segment.offset:decompressed_size+task.memory_segment.offset] = buffer

        except Exception as e:
            print("ERROR", e)
            self.results_queue.put(DownloadTaskResult(False, FailReason.UNKNOWN, task))
            return 

        if compressed_sum.hexdigest() != compressed_md5:
            self.results_queue.put(DownloadTaskResult(False, FailReason.CHECKSUM, task))
            return 

        self.results_queue.put(DownloadTaskResult(True, None, task, download_size=download_size, decompressed_size=decompressed_size))
    
    def v1(self, task: DownloadTask1):
        retries = 5
        urls = self.secure_links[task.product_id]

        response = None
        if type(urls) == str:
            url = urls
        else:
            endpoint = copy(urls[0])
            endpoint["parameters"]["path"] += "/main.bin"
            url = dl_utils.merge_url_with_params(
                endpoint["url_format"], endpoint["parameters"]
            )
        range_header = dl_utils.get_range_header(task.offset, task.size)

        buffer = bytes()
        while retries > 0:
            buffer = bytes()
            try:
                response = self.session.get(url, stream=True, timeout=10, headers={'Range': range_header})
                response.raise_for_status()
                for chunk in response.iter_content(1024 * 512):
                    buffer += chunk 
                    self.speed_queue.put((len(chunk), len(chunk)))
            except Exception as e:
                print("Connection failed", e)
                #Handle exception
                if response and response.status_code == 401:
                    self.results_queue.put(DownloadTaskResult(False, FailReason.UNAUTHORIZED, task))
                    return
                retries -= 1
                time.sleep(2)
                continue
            break
        else:
            self.results_queue.put(DownloadTaskResult(False, FailReason.CHECKSUM, task))
            return
         
        download_size = 0
        try:
            download_size = len(buffer)
            self.shared_memory.buf[task.memory_segment.offset:download_size + task.memory_segment.offset] = buffer

        except Exception as e:
            print("ERROR", e)
            self.results_queue.put(DownloadTaskResult(False, FailReason.UNKNOWN, task))
            return 

        if len(buffer) != task.size:
            self.results_queue.put(DownloadTaskResult(False, FailReason.CHECKSUM, task))
            return 

        self.results_queue.put(DownloadTaskResult(True, None, task, download_size=download_size, decompressed_size=download_size))

class Writer(Process):
    def __init__(self, shared_memory, writer_queue, results_queue, speed_queue, cache):
        self.shared_memory = SharedMemory(name=shared_memory)
        self.cache = cache
        self.writer_queue: Queue = writer_queue
        self.results_queue: Queue = results_queue
        self.speed_queue: Queue = speed_queue
        self.early_exit = False
        super().__init__()

    def run(self):
        file_handle = None
        current_file = ''

        while not self.early_exit:
            try:
                task: Union[WriterTask, TerminateWorker] = self.writer_queue.get(timeout=2)
            except Empty:
                continue

            if isinstance(task, TerminateWorker):
                self.results_queue.put(WriterTaskResult(True, task))
                break

            written = 0
            
            task_path = dl_utils.get_case_insensitive_name(os.path.join(task.destination, task.file_path))
            split_path = os.path.split(task_path)
            if split_path[0] and not os.path.exists(split_path[0]):
                dl_utils.prepare_location(split_path[0])

            if task.flags & TaskFlag.CREATE_FILE:
                open(task_path, 'a').close()
                self.results_queue.put(WriterTaskResult(True, task))
                continue

            elif task.flags & TaskFlag.CREATE_SYMLINK:
                dest = task.old_destination or task.destination
                # Windows will likely not have this ran ever
                if os.path.exists(task_path):
                    os.unlink(task_path)
                os.symlink(dl_utils.get_case_insensitive_name(os.path.join(dest, task.old_file)), task_path)
                self.results_queue.put(WriterTaskResult(True, task))
                continue

            elif task.flags & TaskFlag.OPEN_FILE:
                if file_handle:
                    print("Opening on unclosed file")
                    file_handle.close()
                file_handle = open(task_path, 'wb')
                current_file = task_path

                self.results_queue.put(WriterTaskResult(True, task))
                continue
            elif task.flags & TaskFlag.CLOSE_FILE:
                if file_handle:
                    file_handle.close()
                    file_handle = None
                self.results_queue.put(WriterTaskResult(True, task))
                continue
            
            elif task.flags & TaskFlag.COPY_FILE:
                if file_handle and task.file_path == current_file:
                    print("Copy on unclosed file")
                    file_handle.close()
                    file_handle = None

                if not task.old_file:
                    # if this ever happens....
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue

                dest = task.old_destination or task.destination
                try:
                    shutil.copy(dl_utils.get_case_insensitive_name(os.path.join(dest, task.old_file)), task_path)
                except shutil.SameFileError:
                    pass
                except Exception:
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue
                self.results_queue.put(WriterTaskResult(True, task))
                continue

            elif task.flags & TaskFlag.RENAME_FILE:
                if file_handle and task.file_path == current_file:
                    print("Renaming on unclosed file")
                    file_handle.close()
                    file_handle = None

                if not task.old_file:
                    # if this ever happens....
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue
                
                if task.flags & TaskFlag.DELETE_FILE and os.path.exists(task_path):
                    try:
                        os.remove(task_path)
                    except OSError as e:
                        self.results_queue.put(WriterTaskResult(False, task))
                        continue
                dest = task.old_destination or task.destination
                try:
                    os.rename(dl_utils.get_case_insensitive_name(os.path.join(dest, task.old_file)), task_path)
                except OSError as e:
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue

                self.results_queue.put(WriterTaskResult(True, task))
                continue
            
            elif task.flags & TaskFlag.PATCH:
                if file_handle and task.file_path == current_file:
                    print("Patching on unclosed file")
                    file_handle.close()
                    file_handle = None

                if not task.old_file or not task.patch_file:
                    # if this ever happens....
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue

                try:
                    dest = task.old_destination or task.destination
                    source = os.path.join(dest, task.old_file)
                    source = dl_utils.get_case_insensitive_name(source)
                    patch = os.path.join(task.destination, task.patch_file)
                    patch = dl_utils.get_case_insensitive_name(patch)
                    target = task_path

                    patcher.patch(source, patch, target, self.speed_queue)

                except Exception as e:
                    print("Patch failed", e)
                    print(traceback.format_exc())
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue
                written = 0
                if os.path.exists(target):
                    written = os.path.getsize(target)
                self.results_queue.put(WriterTaskResult(True, task, written=written))
                continue
            
            elif task.flags & TaskFlag.DELETE_FILE:
                if file_handle and task.file_path == current_file:
                    print("Deleting on unclosed file")
                    file_handle.close()
                    file_handle = None
                try:
                    if os.path.exists(task_path):
                        os.remove(task_path)
                except OSError as e:
                    self.results_queue.put(WriterTaskResult(False, task))
                    continue

            elif task.flags & TaskFlag.MAKE_EXE:
                if file_handle and task.file_path == current_file:
                    print("Making exe on unclosed file")
                    file_handle.close()
                    file_handle = None
                if sys.platform != 'win32':
                    try:
                        st = os.stat(task_path)
                        os.chmod(task_path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
                    except Exception as e:
                        self.results_queue.put(WriterTaskResult(False, task))
                        continue
                self.results_queue.put(WriterTaskResult(True, task))
                continue

            try:
                if task.shared_memory:
                    if not task.size:
                        print("No size")
                        self.results_queue.put(WriterTaskResult(False, task))
                        continue
                    offset = task.shared_memory.offset
                    end = offset + task.size
                    left = task.size
                    buffer = BytesIO(self.shared_memory.buf[offset:end].tobytes())
                    while left > 0:
                        chunk = buffer.read(min(1024 * 1024, left))   
                        written += file_handle.write(chunk)
                        self.speed_queue.put((len(chunk), 0))
                        left -= len(chunk)
                        
                    if task.flags & TaskFlag.OFFLOAD_TO_CACHE and task.hash:
                        cache_file_path = os.path.join(self.cache, task.hash)
                        dl_utils.prepare_location(self.cache)
                        cache_file = open(cache_file_path, 'wb')
                        cache_file.write(self.shared_memory.buf[offset:end].tobytes())
                        self.speed_queue.put((task.size, 0))
                        cache_file.close()
                elif task.old_file:
                    if not task.size:
                        print("No size")
                        self.results_queue.put(WriterTaskResult(False, task))
                        continue
                    dest = task.old_destination or task.destination
                    old_file_path = dl_utils.get_case_insensitive_name(os.path.join(dest, task.old_file))
                    old_file_handle = open(old_file_path, "rb")
                    if task.old_offset:
                        old_file_handle.seek(task.old_offset)
                    left = task.size
                    if task.flags & TaskFlag.ZIP_DEC:
                        decompressor = zlib.decompressobj(-15)
                    else:
                        decompressor = None
                    while left > 0:
                        chunk = old_file_handle.read(min(1024*1024, left))
                        if decompressor:
                            data = decompressor.decompress(chunk)
                        else:
                            data = chunk
                        written += file_handle.write(data)
                        self.speed_queue.put((len(data), len(chunk)))
                        left -= len(chunk)
                    old_file_handle.close()
                    if task.flags & TaskFlag.ZIP_DEC:
                        written = written - task.size

            except Exception as e:
                print("Writer exception", e)
                self.results_queue.put(WriterTaskResult(False, task))
            else:
                self.results_queue.put(WriterTaskResult(True, task, written=written))

        
        self.shared_memory.close()
        shutil.rmtree(self.cache, ignore_errors=True)

07070100000022000081ED00000000000000000000000166E0651E000010FA000000000000000000000000000000000000002400000000heroic-gogdl-1.1.2/gogdl/imports.pyimport os
import glob
import json
import logging
from sys import exit
from gogdl import constants
import requests


def get_info(args, unknown_args):
    logger = logging.getLogger("IMPORT")
    path = args.path
    if not os.path.exists(path):
        logger.error("Provided path is invalid!")
        exit(1)
    game_details = load_game_details(path)

    info_file = game_details[0]
    build_id_file = game_details[1]
    platform = game_details[2]
    with_dlcs = game_details[3]
    build_id = ""
    installed_language = None
    info = {}
    if platform != "linux":
        if not info_file:
            print("Error importing, no info file")
            return
        f = open(info_file, "r")
        info = json.loads(f.read())
        f.close()

        title = info["name"]
        game_id = info["rootGameId"]
        build_id = info.get("buildId")
        if "languages" in info:
            installed_language = info["languages"][0]
        elif "language" in info:
            installed_language = info["language"]
        else:
            installed_language = "en-US"
        if build_id_file:
            f = open(build_id_file, "r")
            build = json.loads(f.read())
            f.close()
            build_id = build.get("buildId")

        version_name = build_id
        if build_id and platform != "linux":
            # Get version name
            builds_res = requests.get(
                f"{constants.GOG_CONTENT_SYSTEM}/products/{game_id}/os/{platform}/builds?generation=2",
                headers={
                    "User-Agent": "GOGGalaxyCommunicationService/2.0.4.164 (Windows_32bit)"
                },
            )
            builds = builds_res.json()
            target_build = builds["items"][0]
            for build in builds["items"]:
                if build["build_id"] == build_id:
                    target_build = build
                    break
            version_name = target_build["version_name"]
    if platform == "linux" and os.path.exists(os.path.join(path, "gameinfo")):
        # Linux version installed using installer
        gameinfo_file = open(os.path.join(path, "gameinfo"), "r")
        data = gameinfo_file.read()
        lines = data.split("\n")
        title = lines[0]
        version_name = lines[1]

        if not installed_language:
            installed_language = lines[3]
        if len(lines) > 4:
            game_id = lines[4]
            build_id = lines[6]
        else:
            game_id = None
            build_id = None
    print(
        json.dumps(
            {
                "appName": game_id,
                "buildId": build_id,
                "title": title,
                "tasks": info["playTasks"] if info and info.get("playTasks") else None,
                "installedLanguage": installed_language,
                "dlcs": with_dlcs,
                "platform": platform,
                "versionName": version_name,
            }
        )
    )


def load_game_details(path):
    base_path = path
    found = glob.glob(os.path.join(path, "goggame-*.info"))
    build_id = glob.glob(os.path.join(path, "goggame-*.id"))
    platform = "windows"
    if not found:
        base_path = os.path.join(path, "Contents", "Resources")
        found = glob.glob(os.path.join(path, "Contents", "Resources", "goggame-*.info"))
        build_id = glob.glob(
            os.path.join(path, "Contents", "Resources", "goggame-*.id")
        )
        platform = "osx"
    if not found:
        base_path = os.path.join(path, "game")
        found = glob.glob(os.path.join(path, "game", "goggame-*.info"))
        build_id = glob.glob(os.path.join(path, "game", "goggame-*.id"))
        platform = "linux"
    if not found:
        if os.path.exists(os.path.join(path, "gameinfo")):
            return (None, None, "linux", [])

    root_id = None
    # Array of DLC game ids
    dlcs = []
    for info in found:
        with open(info) as info_file:
            data = json.load(info_file)
            if not root_id:
                root_id = data.get("rootGameId")
            if data["gameId"] == root_id:
                continue
            
            dlcs.append(data["gameId"])

    return (os.path.join(base_path, f"goggame-{root_id}.info"), os.path.join(base_path, f"goggame-{root_id}.id") if build_id else None, platform, dlcs)

07070100000023000081A400000000000000000000000166E0651E00002587000000000000000000000000000000000000002300000000heroic-gogdl-1.1.2/gogdl/launch.pyimport os
import json
import sys
import subprocess
import time
from gogdl.dl.dl_utils import get_case_insensitive_name
from ctypes import *
from gogdl.process import Process
import signal
import shutil
import shlex

class NoMoreChildren(Exception):
    pass

def get_flatpak_command(id: str) -> list[str]:
    if sys.platform != "linux":
        return []
    new_process_command = []
    process_command = ["flatpak", "info", id] 
    if os.path.exists("/.flatpak-info"):
        try:
            spawn_test = subprocess.run(["flatpak-spawn", "--host", "ls"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except FileNotFoundError:
            return []
        if spawn_test.returncode != 0:
            return []

        new_process_command = ["flatpak-spawn", "--host"]
        process_command = new_process_command + process_command

    try:
        output = subprocess.run(process_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        if output.returncode == 0:
            return new_process_command + ["flatpak", "run", id]

    except FileNotFoundError:
        pass
    return []


# Supports launching linux builds
def launch(arguments, unknown_args):
    # print(arguments)
    info = load_game_info(arguments.path, arguments.id, arguments.platform)

    wrapper = []
    if arguments.wrapper:
        wrapper = shlex.split(arguments.wrapper)
    envvars = {}

    unified_platform = {"win32": "windows", "darwin": "osx", "linux": "linux"}
    command = list()
    working_dir = arguments.path
    # If type is a string we know it's a path to start.sh on linux
    if type(info) != str:
        if sys.platform != "win32":
            if not arguments.dont_use_wine and arguments.platform != unified_platform[sys.platform]:
                if arguments.wine_prefix:
                    envvars["WINEPREFIX"] = arguments.wine_prefix
                wrapper.append(arguments.wine)

        primary_task = get_preferred_task(info, arguments.preferred_task)
        launch_arguments = primary_task.get("arguments")
        compatibility_flags = primary_task.get("compatibilityFlags")
        executable = os.path.join(arguments.path, primary_task["path"])
        if arguments.platform == "linux":
            executable = os.path.join(arguments.path, "game", primary_task["path"])
        if launch_arguments is None:
            launch_arguments = []
        if type(launch_arguments) == str:
            launch_arguments = launch_arguments.replace('\\', '/')
            launch_arguments = shlex.split(launch_arguments)
        if compatibility_flags is None:
            compatibility_flags = []

        relative_working_dir = (
            primary_task["workingDir"] if primary_task.get("workingDir") else ""
        )
        if sys.platform != "win32":
            relative_working_dir = relative_working_dir.replace("\\", os.sep)
            executable = executable.replace("\\", os.sep)
        working_dir = os.path.join(arguments.path, relative_working_dir)

        if not os.path.exists(executable):
            executable = get_case_insensitive_name(executable)
        # Handle case sensitive file systems
        if not os.path.exists(working_dir):
            working_dir = get_case_insensitive_name(working_dir)

        os.chdir(working_dir)
        
        if sys.platform != "win32" and arguments.platform == 'windows' and not arguments.override_exe:
            if "scummvm.exe" in executable.lower():
                flatpak_scummvm = get_flatpak_command("org.scummvm.ScummVM")
                native_scummvm = shutil.which("scummvm")
                if native_scummvm:
                    native_scummvm = [native_scummvm]
            
                native_runner = flatpak_scummvm or native_scummvm
                if native_runner:
                    wrapper = native_runner
                    executable = None
            elif "dosbox.exe" in executable.lower():
                flatpak_dosbox = get_flatpak_command("io.github.dosbox-staging")
                native_dosbox= shutil.which("dosbox")
                if native_dosbox:
                    native_dosbox = [native_dosbox]
                
                native_runner = flatpak_dosbox or native_dosbox
                if native_runner:
                    wrapper = native_runner
                    executable = None

        if len(wrapper) > 0 and wrapper[0] is not None:
            command.extend(wrapper)

        if arguments.override_exe:
            command.append(arguments.override_exe)
            working_dir = os.path.split(arguments.override_exe)[0]
            if not os.path.exists(working_dir):
                working_dir = get_case_insensitive_name(working_dir)
        elif executable:
            command.append(executable)
        command.extend(launch_arguments)
    else:
        if len(wrapper) > 0 and wrapper[0] is not None:
            command.extend(wrapper)

        if arguments.override_exe:
            command.append(arguments.override_exe)
            working_dir = os.path.split(arguments.override_exe)[0]
            # Handle case sensitive file systems
            if not os.path.exists(working_dir):
                working_dir = get_case_insensitive_name(working_dir)
        else:
            command.append(info)

    os.chdir(working_dir)
    command.extend(unknown_args)
    environment = os.environ.copy()
    environment.update(envvars)
    
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        bundle_dir = sys._MEIPASS 
        ld_library = environment.get("LD_LIBRARY_PATH")
        if ld_library:
            splitted = ld_library.split(":")
            try:
                splitted.remove(bundle_dir)
            except ValueError:
                pass
            environment.update({"LD_LIBRARY_PATH": ":".join(splitted)})
    
    print("Launch command:", command)

    status = None
    if sys.platform == 'linux':
        libc = cdll.LoadLibrary("libc.so.6")
        prctl = libc.prctl
        result = prctl(36 ,1, 0, 0, 0, 0) # PR_SET_CHILD_SUBREAPER = 36

        if result == -1:
            print("PR_SET_CHILD_SUBREAPER is not supported by your kernel (Linux 3.4 and above)")
        
        process = subprocess.Popen(command, env=environment)
        process_pid = process.pid

        def iterate_processes():
            for child in Process(os.getpid()).iter_children():
                if child.state == 'Z':
                    continue

                if child.name:
                    yield child

        def hard_sig_handler(signum, _frame):
            for _ in range(3):  # just in case we race a new process.
                for child in Process(os.getpid()).iter_children():
                    try:
                        os.kill(child.pid, signal.SIGKILL)
                    except ProcessLookupError:
                        pass


        def sig_handler(signum, _frame):
            signal.signal(signal.SIGTERM, hard_sig_handler)
            signal.signal(signal.SIGINT, hard_sig_handler)
            for _ in range(3):  # just in case we race a new process.
                for child in Process(os.getpid()).iter_children():
                    try:
                        os.kill(child.pid, signal.SIGTERM)
                    except ProcessLookupError:
                        pass

        def is_alive():
            return next(iterate_processes(), None) is not None

        signal.signal(signal.SIGTERM, sig_handler)
        signal.signal(signal.SIGINT, sig_handler)

        def reap_children():
            nonlocal status
            while True:
                try:
                    child_pid, child_returncode, _resource_usage = os.wait3(os.WNOHANG)
                except ChildProcessError:
                    raise NoMoreChildren from None  # No processes remain.
                if child_pid == process_pid:
                    status = child_returncode

                if child_pid == 0:
                    break

        try:
            # The initial wait loop:
            #  the initial process may have been excluded. Wait for the game
            #  to be considered "started".
            if not is_alive():
                while not is_alive():
                    reap_children()
                    time.sleep(0.1)
            while is_alive():
                reap_children()
                time.sleep(0.1)
            reap_children()
        except NoMoreChildren:
            print("All processes exited")


    else:
        process = subprocess.Popen(command, env=environment, 
                                   shell=sys.platform=="win32")
        status = process.wait()

    sys.exit(status)


def get_preferred_task(info, index):
    primaryTask = None
    for task in info["playTasks"]:
        if task.get("isPrimary") == True:
            primaryTask = task
            break
    if index is None:
        return primaryTask
    indexI = int(index)
    if len(info["playTasks"]) > indexI:
        return info["playTasks"][indexI]
    
    return primaryTask




def load_game_info(path, id, platform):
    filename = f"goggame-{id}.info"
    abs_path = (
        (
            os.path.join(path, filename)
            if platform == "windows"
            else os.path.join(path, "start.sh")
        )
        if platform != "osx"
        else os.path.join(path, "Contents", "Resources", filename)
    )
    if not os.path.isfile(abs_path):
        sys.exit(1)
    if platform == "linux":
        return abs_path
    with open(abs_path) as f:
        data = f.read()
        f.close()
        return json.loads(data)


07070100000024000081A400000000000000000000000166E0651E000011D7000000000000000000000000000000000000002400000000heroic-gogdl-1.1.2/gogdl/process.pyimport os


class InvalidPid(Exception):

    """Exception raised when an operation on a non-existent PID is called"""


class Process:

    """Python abstraction a Linux process"""

    def __init__(self, pid):
        try:
            self.pid = int(pid)
            self.error_cache = []
        except ValueError as err:
            raise InvalidPid("'%s' is not a valid pid" % pid) from err

    def __repr__(self):
        return "Process {}".format(self.pid)

    def __str__(self):
        return "{} ({}:{})".format(self.name, self.pid, self.state)

    def _read_content(self, file_path):
        """Return the contents from a file in /proc"""
        try:
            with open(file_path, encoding='utf-8') as proc_file:
                content = proc_file.read()
        except (ProcessLookupError, FileNotFoundError, PermissionError):
            return ""
        return content

    def get_stat(self, parsed=True):
        stat_filename = "/proc/{}/stat".format(self.pid)
        try:
            with open(stat_filename, encoding='utf-8') as stat_file:
                _stat = stat_file.readline()
        except (ProcessLookupError, FileNotFoundError):
            return None
        if parsed:
            return _stat[_stat.rfind(")") + 1:].split()
        return _stat

    def get_thread_ids(self):
        """Return a list of thread ids opened by process."""
        basedir = "/proc/{}/task/".format(self.pid)
        if os.path.isdir(basedir):
            try:
                return os.listdir(basedir)
            except FileNotFoundError:
                return []
        else:
            return []

    def get_children_pids_of_thread(self, tid):
        """Return pids of child processes opened by thread `tid` of process."""
        children_path = "/proc/{}/task/{}/children".format(self.pid, tid)
        try:
            with open(children_path, encoding='utf-8') as children_file:
                children_content = children_file.read()
        except (FileNotFoundError, ProcessLookupError):
            children_content = ""
        return children_content.strip().split()

    @property
    def name(self):
        """Filename of the executable."""
        _stat = self.get_stat(parsed=False)
        if _stat:
            return _stat[_stat.find("(") + 1:_stat.rfind(")")]
        return None

    @property
    def state(self):
        """One character from the string "RSDZTW" where R is running, S is
        sleeping in an interruptible wait, D is waiting in uninterruptible disk
        sleep, Z is zombie, T is traced or stopped (on a signal), and W is
        paging.
        """
        _stat = self.get_stat()
        if _stat:
            return _stat[0]
        return None

    @property
    def cmdline(self):
        """Return command line used to run the process `pid`."""
        cmdline_path = "/proc/{}/cmdline".format(self.pid)
        _cmdline_content = self._read_content(cmdline_path)
        if _cmdline_content:
            return _cmdline_content.replace("\x00", " ").replace("\\", "/")

    @property
    def cwd(self):
        """Return current working dir of process"""
        cwd_path = "/proc/%d/cwd" % int(self.pid)
        return os.readlink(cwd_path)

    @property
    def environ(self):
        """Return the process' environment variables"""
        environ_path = "/proc/{}/environ".format(self.pid)
        _environ_text = self._read_content(environ_path)
        if not _environ_text:
            return {}
        try:
            return dict([line.split("=", 1) for line in _environ_text.split("\x00") if line])
        except ValueError:
            if environ_path not in self.error_cache:
                self.error_cache.append(environ_path)
            return {}

    @property
    def children(self):
        """Return the child processes of this process"""
        _children = []
        for tid in self.get_thread_ids():
            for child_pid in self.get_children_pids_of_thread(tid):
                _children.append(Process(child_pid))
        return _children

    def iter_children(self):
        """Iterator that yields all the children of a process"""
        for child in self.children:
            yield child
            yield from child.iter_children()

    def wait_for_finish(self):
        """Waits until the process finishes
        This only works if self.pid is a child process of Lutris
        """
        try:
            pid, ret_status = os.waitpid(int(self.pid) * -1, 0)
        except OSError as ex:
            return -1
        return ret_status
07070100000025000081A400000000000000000000000166E0651E000034F4000000000000000000000000000000000000002200000000heroic-gogdl-1.1.2/gogdl/saves.pyimport os
import sys
import logging
import requests
import hashlib
import datetime
import gzip
from enum import Enum

import gogdl.dl.dl_utils as dl_utils
import gogdl.constants as constants

LOCAL_TIMEZONE = datetime.datetime.utcnow().astimezone().tzinfo


class SyncAction(Enum):
    DOWNLOAD = 0
    UPLOAD = 1
    CONFLICT = 2
    NONE = 3


class SyncFile:
    def __init__(self, path, abs_path, md5=None, update_time=None):
        self.relative_path = path.replace('\\', '/')  # cloud file identifier
        self.absolute_path = abs_path
        self.md5 = md5
        self.update_time = update_time
        self.update_ts = (
            datetime.datetime.fromisoformat(update_time).astimezone().timestamp()
            if update_time
            else None
        )

    def get_file_metadata(self):
        ts = os.stat(self.absolute_path).st_mtime
        date_time_obj = datetime.datetime.fromtimestamp(
            ts, tz=LOCAL_TIMEZONE
        ).astimezone(datetime.timezone.utc)
        self.md5 = hashlib.md5(
            gzip.compress(open(self.absolute_path, "rb").read(), 6, mtime=0)
        ).hexdigest()

        self.update_time = date_time_obj.isoformat(timespec="seconds")
        self.update_ts = date_time_obj.timestamp()

    def __repr__(self):
        return f"{self.md5} {self.relative_path}"


class CloudStorageManager:
    def __init__(self, api_handler, authorization_manager):
        self.api = api_handler
        self.auth_manager = authorization_manager
        self.session = requests.Session()
        self.logger = logging.getLogger("SAVES")

        self.session.headers.update(
            {"User-Agent": "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog",
             "X-Object-Meta-User-Agent": "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog"}
        )

        self.credentials = dict()
        self.client_id = str()
        self.client_secret = str()

    def create_directory_map(self, path: str) -> list:
        """
        Creates list of every file in directory to be synced
        """
        files = list()
        directory_contents = os.listdir(path)

        for content in directory_contents:
            abs_path = os.path.join(path, content)
            if os.path.isdir(abs_path):
                files.extend(self.create_directory_map(abs_path))
            else:
                files.append(abs_path)
        return files

    @staticmethod
    def get_relative_path(root: str, path: str) -> str:
        if not root.endswith("/") and not root.endswith("\\"):
            root = root + os.sep
        return path.replace(root, "")

    def sync(self, arguments, unknown_args):
        prefered_action = arguments.prefered_action
        self.sync_path = os.path.normpath(arguments.path.strip('"'))
        self.sync_path = self.sync_path.replace("\\", os.sep)
        self.cloud_save_dir_name = arguments.dirname
        self.arguments = arguments
        self.unknown_args = unknown_args

        if not os.path.exists(self.sync_path):
            self.logger.warning("Provided path doesn't exist, creating")
            os.makedirs(self.sync_path, exist_ok=True)
        dir_list = self.create_directory_map(self.sync_path)
        if len(dir_list) == 0:
            self.logger.info("No files in directory")

        local_files = [
            SyncFile(self.get_relative_path(self.sync_path, f), f) for f in dir_list
        ]

        for f in local_files:
            f.get_file_metadata()

        self.logger.info(f"Local files: {len(dir_list)}")
        self.client_id, self.client_secret = self.get_auth_ids()
        self.get_auth_token()

        cloud_files = self.get_cloud_files_list()
        downloadable_cloud = [f for f in cloud_files if f.md5 != "aadd86936a80ee8a369579c3926f1b3c"]

        if len(local_files) > 0 and len(cloud_files) == 0:
            action = SyncAction.UPLOAD
            self.logger.info("No files in cloud, uploading")
            for f in local_files:
                self.upload_file(f)
            self.logger.info("Done")
            sys.stdout.write(str(datetime.datetime.now().timestamp()))
            sys.stdout.flush()
            return
        elif len(local_files) == 0 and len(cloud_files) > 0:
            self.logger.info("No files locally, downloading")
            action = SyncAction.DOWNLOAD
            for f in downloadable_cloud:
                self.download_file(f)
            self.logger.info("Done")
            sys.stdout.write(str(datetime.datetime.now().timestamp()))
            sys.stdout.flush()
            return

        timestamp = float(arguments.timestamp)
        classifier = SyncClassifier.classify(local_files, cloud_files, timestamp)

        action = classifier.get_action()

        if prefered_action:
            if prefered_action == "forceupload":
                self.logger.warning("Forcing upload")
                classifier.updated_local = local_files
                action = SyncAction.UPLOAD
            elif prefered_action == "forcedownload":
                self.logger.warning("Forcing download")
                classifier.updated_cloud = downloadable_cloud 
                action = SyncAction.DOWNLOAD
            if prefered_action == "upload" and action == SyncAction.DOWNLOAD:
                self.logger.warning("Refused to upload files, newer files in the cloud")
                print(self.arguments.timestamp)
                return
            elif prefered_action == "download" and action == SyncAction.UPLOAD:
                self.logger.warning("Refused to download files, newer files locally")
                print(self.arguments.timestamp)
                return

        if action == SyncAction.UPLOAD:
            self.logger.info("Uploading files")
            for f in classifier.updated_local:
                self.upload_file(f)
            for f in classifier.not_existing_locally:
                self.logger.info(f"DELETING IN CLOUD {f}")
                self.delete_file(f)
        elif action == SyncAction.DOWNLOAD:
            self.logger.info("Downloading files")
            for f in classifier.updated_cloud:
                self.download_file(f)
            for f in classifier.not_existing_remotely:
                self.logger.info(f"DELETING LOCALLY {f.absolute_path}")
                os.remove(f.absolute_path)

        elif action == SyncAction.CONFLICT:
            self.logger.warning(
                "Files in conflict force downloading or uploading of files"
            )
        elif action == SyncAction.NONE:
            self.logger.info("Nothing to do")

        sys.stdout.write(str(datetime.datetime.now().timestamp()))
        sys.stdout.flush()
        self.logger.info("Done")

    def clear(self, arguments, unknown_args):
        self.sync_path = os.path.normpath(arguments.path.strip('"'))
        self.sync_path = self.sync_path.replace("\\", os.sep)
        self.cloud_save_dir_name = arguments.dirname
        self.arguments = arguments
        self.unknown_args = unknown_args

        self.client_id, self.client_secret = self.get_auth_ids()
        self.get_auth_token()

        cloud_files = self.get_cloud_files_list()
        for f in cloud_files:
            self.delete_file(f)
        self.logger.info("Done")

    def get_auth_token(self):
        self.credentials = self.auth_manager.get_credentials(self.client_id, self.client_secret)
        self.session.headers.update(
            {"Authorization": f"Bearer {self.credentials['access_token']}"}
        )

    def is_in_our_dir(self, value):
        return value["name"].startswith(self.cloud_save_dir_name)

    def get_cloud_files_list(self):
        response = self.session.get(
            f"{constants.GOG_CLOUDSTORAGE}/v1/{self.credentials['user_id']}/{self.client_id}",
            headers={"Accept": "application/json"},
        )

        if response.status_code == 404:
            return []
        else:
            response.raise_for_status()

        json_res = response.json()
        # print(json_res)
        self.logger.info(f"Files in cloud: {len(json_res)}")

        filtered = filter(self.is_in_our_dir, json_res)

        files = [
            SyncFile(
                sync_f["name"].replace(f"{self.cloud_save_dir_name}/", "", 1),
                os.path.join(
                    self.sync_path,
                    sync_f["name"].replace(f"{self.cloud_save_dir_name}/", "", 1),
                ),
                md5=sync_f["hash"],
                update_time=sync_f["last_modified"],
            )
            for sync_f in filtered
        ]

        return files

    def get_auth_ids(self):
        builds = dl_utils.get_json(
            self.api,
            f"{constants.GOG_CONTENT_SYSTEM}/products/{self.arguments.id}/os/{self.arguments.platform}/builds?generation=2",
        )
        meta_url = builds["items"][0]["link"]

        meta, headers = dl_utils.get_zlib_encoded(self.api, meta_url)
        return meta["clientId"], meta["clientSecret"]

    def delete_file(self, file: SyncFile):
        self.logger.info(f"Deleting {file.relative_path}")
        response = self.session.delete(
            f"{constants.GOG_CLOUDSTORAGE}/v1/{self.credentials['user_id']}/{self.client_id}/{self.cloud_save_dir_name}/{file.relative_path}",
        )

    def upload_file(self, file: SyncFile):
        compressed_data = gzip.compress(
            open(file.absolute_path, "rb").read(), 6, mtime=0
        )
        headers = {
            "X-Object-Meta-LocalLastModified": f"{file.update_time}",
            "Etag": hashlib.md5(compressed_data).hexdigest(),
            "Content-Encoding": "gzip",
        }

        response = self.session.put(
            f"{constants.GOG_CLOUDSTORAGE}/v1/{self.credentials['user_id']}/{self.client_id}/{self.cloud_save_dir_name}/{file.relative_path}",
            data=compressed_data,
            headers=headers,
        )

        if not response.ok:
            self.logger.error(
                f"There was an error uploading a file \n{response.status_code}\n{response.content}"
            )
            return

    def download_file(self, file: SyncFile, retries=3):
        try:
            response = self.session.get(
                f"{constants.GOG_CLOUDSTORAGE}/v1/{self.credentials['user_id']}/{self.client_id}/{self.cloud_save_dir_name}/{file.relative_path}",
                stream=True,
            )
        except:
            if (retries > 1):
                self.logger.debug(f"Failed sync of {file}, retrying (retries left {retries - 1})")
                self.download_file(file, retries - 1)
                return
            else:
                response = {}

        if not response.ok:
            self.logger.error("Downloading file failed")

        total = response.headers.get("Content-Length")
        os.makedirs(os.path.split(file.absolute_path)[0], exist_ok=True)
        with open(file.absolute_path, "wb") as f:
            # if not total:
            #     f.write(response.content)
            total = int(total)
            for data in response.iter_content(
                    chunk_size=max(int(total / 1000), 1024 * 1024)
            ):
                f.write(data)

        try:
            f_timestamp = (
                datetime.datetime.fromisoformat(
                    response.headers.get("X-Object-Meta-LocalLastModified")
                )
                .astimezone()
                .timestamp()
            )
            os.utime(file.absolute_path, (f_timestamp, f_timestamp))
        except (ValueError, TypeError):
            self.logger.warning(f"Incorrect LastModified header for file {file.relative_path} {response.headers.get('X-Object-Meta-LocalLastModified')} ; Ignoring...")
            pass 

    def commit_changes(self):
        response = self.session.post(f"{constants.GOG_CLOUDSTORAGE}/v1/{self.credentials['user_id']}/{self.client_id}")
        if not response.ok:
            self.logger.error("Failed to commit")


class SyncClassifier:
    def __init__(self):
        self.action = None
        self.updated_local = list()
        self.updated_cloud = list()

        self.not_existing_locally = list()
        self.not_existing_remotely = list()

    def get_action(self):
        if len(self.updated_local) == 0 and len(self.updated_cloud) > 0:
            self.action = SyncAction.DOWNLOAD

        elif len(self.updated_local) > 0 and len(self.updated_cloud) == 0:
            self.action = SyncAction.UPLOAD

        elif len(self.updated_local) == 0 and len(self.updated_cloud) == 0:
            self.action = SyncAction.NONE

        else:
            self.action = SyncAction.CONFLICT

        return self.action

    @classmethod
    def classify(cls, local, cloud, timestamp):
        classifier = cls()

        local_paths = [f.relative_path for f in local]
        cloud_paths = [f.relative_path for f in cloud]

        for f in local:
            if f.relative_path not in cloud_paths:
                classifier.not_existing_remotely.append(f)
            if f.update_ts > timestamp:
                classifier.updated_local.append(f)

        for f in cloud:
            if f.md5 == "aadd86936a80ee8a369579c3926f1b3c":
                continue
            if f.relative_path not in local_paths:
                classifier.not_existing_locally.append(f)
            if f.update_ts > timestamp:
                classifier.updated_cloud.append(f)

        return classifier
07070100000026000041ED00000000000000000000000266E0651E00000000000000000000000000000000000000000000002000000000heroic-gogdl-1.1.2/gogdl/xdelta07070100000027000081A400000000000000000000000166E0651E00000031000000000000000000000000000000000000002C00000000heroic-gogdl-1.1.2/gogdl/xdelta/__init__.py# Python implementation of xdelta3 decoding only
07070100000028000081A400000000000000000000000166E0651E00000D2A000000000000000000000000000000000000002B00000000heroic-gogdl-1.1.2/gogdl/xdelta/objects.pyfrom dataclasses import dataclass
from io import IOBase, BytesIO
from typing import Optional

@dataclass
class CodeTable:
    add_sizes = 17
    near_modes = 4
    same_modes = 3

    cpy_sizes = 15

    addcopy_add_max = 4
    addcopy_near_cpy_max = 6
    addcopy_same_cpy_max = 4

    copyadd_add_max = 1
    copyadd_near_cpy_max = 4
    copyadd_same_cpy_max = 4

    addcopy_max_sizes = [ [6,163,3],[6,175,3],[6,187,3],[6,199,3],[6,211,3],[6,223,3],
    [4,235,1],[4,239,1],[4,243,1]]
    copyadd_max_sizes = [[4,247,1],[4,248,1],[4,249,1],[4,250,1],[4,251,1],[4,252,1],
    [4,253,1],[4,254,1],[4,255,1]]

XD3_NOOP = 0
XD3_ADD = 1
XD3_RUN = 2
XD3_CPY = 3

@dataclass
class Instruction:
    type1:int = 0
    size1:int = 0
    type2:int = 0
    size2:int = 0

@dataclass
class HalfInstruction:
    type: int = 0
    size: int = 0
    addr: int = 0


@dataclass
class AddressCache:
    s_near = CodeTable.near_modes
    s_same = CodeTable.same_modes
    next_slot = 0
    near_array = [0 for _ in range(s_near)]
    same_array = [0 for _ in range(s_same * 256)]

    def update(self, addr):
        self.near_array[self.next_slot] = addr
        self.next_slot = (self.next_slot + 1) % self.s_near

        self.same_array[addr % (self.s_same*256)] = addr

@dataclass
class Context:
    source: IOBase
    target: IOBase

    data_sec: BytesIO
    inst_sec: BytesIO
    addr_sec: BytesIO

    acache: AddressCache
    dec_pos: int = 0
    cpy_len: int = 0
    cpy_off: int = 0
    dec_winoff: int = 0

    target_buffer: Optional[bytearray] = None
    
def build_code_table():
    table: list[Instruction] = []
    for _ in range(256):
        table.append(Instruction())

    cpy_modes = 2 + CodeTable.near_modes + CodeTable.same_modes
    i = 0
    
    table[i].type1 = XD3_RUN
    i+=1
    table[i].type1 = XD3_ADD
    i+=1

    size1 = 1

    for size1 in range(1, CodeTable.add_sizes + 1):
        table[i].type1 = XD3_ADD
        table[i].size1 = size1
        i+=1

    for mode in range(0, cpy_modes):
        table[i].type1 = XD3_CPY + mode
        i += 1
        for size1 in range(4, 4 + CodeTable.cpy_sizes):
            table[i].type1 = XD3_CPY + mode
            table[i].size1 = size1
            i+=1


    for mode in range(cpy_modes):
        for size1 in range(1, CodeTable.addcopy_add_max + 1):
            is_near = mode < (2 + CodeTable.near_modes)
            if is_near:
                max = CodeTable.addcopy_near_cpy_max
            else:
                max = CodeTable.addcopy_same_cpy_max
            for size2 in range(4, max + 1):
                table[i].type1 = XD3_ADD
                table[i].size1 = size1
                table[i].type2 = XD3_CPY + mode
                table[i].size2 = size2
                i+=1


    for mode in range(cpy_modes):
        is_near = mode < (2 + CodeTable.near_modes)
        if is_near:
            max = CodeTable.copyadd_near_cpy_max
        else:
            max = CodeTable.copyadd_same_cpy_max
        for size1 in range(4, max + 1):
            for size2 in range(1, CodeTable.copyadd_add_max + 1):
                table[i].type1 = XD3_CPY + mode
                table[i].size1 = size1
                table[i].type2 = XD3_ADD
                table[i].size2 = size2
                i+=1

    return table

CODE_TABLE = build_code_table()

class ChecksumMissmatch(AssertionError):
    pass
07070100000029000081A400000000000000000000000166E0651E00001B4F000000000000000000000000000000000000002B00000000heroic-gogdl-1.1.2/gogdl/xdelta/patcher.pyfrom io import BytesIO
import math
from multiprocessing import Queue
from zlib import adler32
from gogdl.xdelta import objects

# Convert stfio integer
def read_integer_stream(stream):
    res = 0
    while True:
        res <<= 7
        integer = stream.read(1)[0]
        res |= (integer & 0b1111111)
        if not (integer & 0b10000000):
            break

    return res

def parse_halfinst(context: objects.Context, halfinst: objects.HalfInstruction):
    if halfinst.size == 0:
        halfinst.size = read_integer_stream(context.inst_sec)

    if halfinst.type >= objects.XD3_CPY:
        # Decode address
        mode = halfinst.type - objects.XD3_CPY
        same_start = 2 + context.acache.s_near

        if mode < same_start:
            halfinst.addr = read_integer_stream(context.addr_sec)

            if mode == 0:
                pass
            elif mode == 1:
                halfinst.addr = context.dec_pos - halfinst.addr
                if halfinst.addr < 0:
                    halfinst.addr = context.cpy_len + halfinst.addr
            else:
                halfinst.addr += context.acache.near_array[mode - 2]
        else:
            mode -= same_start
            addr = context.addr_sec.read(1)[0]
            halfinst.addr = context.acache.same_array[(mode * 256) + addr]
        context.acache.update(halfinst.addr)

    context.dec_pos += halfinst.size


def decode_halfinst(context:objects.Context, halfinst: objects.HalfInstruction, speed_queue: Queue):
    take = halfinst.size

    if halfinst.type == objects.XD3_RUN:
        byte = context.data_sec.read(1)

        for _ in range(take):
            context.target_buffer.extend(byte)

        halfinst.type = objects.XD3_NOOP
    elif halfinst.type == objects.XD3_ADD:
        buffer = context.data_sec.read(take)
        assert len(buffer) == take
        context.target_buffer.extend(buffer)
        halfinst.type = objects.XD3_NOOP
    else: # XD3_CPY and higher
        if halfinst.addr < (context.cpy_len or 0):
            context.source.seek(context.cpy_off + halfinst.addr)
            left = take
            while left > 0:
                buffer = context.source.read(min(1024 * 1024, left))
                size = len(buffer)
                speed_queue.put((0, size))
                context.target_buffer.extend(buffer)
                left -= size

        else:
            print("OVERLAP NOT IMPLEMENTED")
            raise Exception("OVERLAP")
        halfinst.type = objects.XD3_NOOP


def patch(source: str, patch: str, out: str, speed_queue: Queue):
    src_handle = open(source, 'rb') 
    patch_handle = open(patch, 'rb')
    dst_handle = open(out, 'wb')


    # Verify if patch is actually xdelta patch
    headers = patch_handle.read(5)
    try:
        assert headers[0] == 0xD6
        assert headers[1] == 0xC3
        assert headers[2] == 0xC4
    except AssertionError:
        print("Specified patch file is unlikely to be xdelta patch")
        return

    HDR_INDICATOR = headers[4]
    COMPRESSOR_ID = HDR_INDICATOR & (1 << 0) != 0
    CODE_TABLE = HDR_INDICATOR & (1 << 1) != 0
    APP_HEADER = HDR_INDICATOR & (1 << 2) != 0
    app_header_data = bytes()

    if COMPRESSOR_ID or CODE_TABLE:
        print("Compressor ID and codetable are yet not supported")
        return

    if APP_HEADER:
        app_header_size = read_integer_stream(patch_handle)
        app_header_data = patch_handle.read(app_header_size)

    context = objects.Context(src_handle, dst_handle, BytesIO(), BytesIO(), BytesIO(), objects.AddressCache())

    win_number = 0
    win_indicator = patch_handle.read(1)[0]
    while win_indicator is not None:
        context.acache = objects.AddressCache()
        source_used = win_indicator & (1 << 0) != 0
        target_used = win_indicator & (1 << 1) != 0
        adler32_sum = win_indicator & (1 << 2) != 0

        if source_used:
            source_segment_length = read_integer_stream(patch_handle)
            source_segment_position = read_integer_stream(patch_handle)
        else:
            source_segment_length = 0
            source_segment_position = 0

        context.cpy_len = source_segment_length
        context.cpy_off = source_segment_position
        context.source.seek(context.cpy_off or 0)
        context.dec_pos = 0

        # Parse delta
        delta_encoding_length = read_integer_stream(patch_handle)

        window_length = read_integer_stream(patch_handle)
        context.target_buffer = bytearray()

        delta_indicator = patch_handle.read(1)[0]
        
        add_run_data_length = read_integer_stream(patch_handle)
        instructions_length = read_integer_stream(patch_handle)
        addresses_length = read_integer_stream(patch_handle)

        parsed_sum = 0
        if adler32_sum:
            checksum = patch_handle.read(4)
            parsed_sum = int.from_bytes(checksum, 'big')
        

        context.data_sec = BytesIO(patch_handle.read(add_run_data_length))
        context.inst_sec = BytesIO(patch_handle.read(instructions_length))
        context.addr_sec = BytesIO(patch_handle.read(addresses_length))


        current1 = objects.HalfInstruction()
        current2 = objects.HalfInstruction()

        while context.inst_sec.tell() < instructions_length or current1.type != objects.XD3_NOOP or current2.type != objects.XD3_NOOP:
            if current1.type == objects.XD3_NOOP and current2.type == objects.XD3_NOOP:
                ins = objects.CODE_TABLE[context.inst_sec.read(1)[0]]
                current1.type = ins.type1
                current2.type = ins.type2
                current1.size = ins.size1
                current2.size = ins.size2
    
                if current1.type != objects.XD3_NOOP:
                    parse_halfinst(context, current1)
                if current2.type != objects.XD3_NOOP:
                    parse_halfinst(context, current2)
            
            while current1.type != objects.XD3_NOOP:
                decode_halfinst(context, current1, speed_queue)
                
            while current2.type != objects.XD3_NOOP:
                decode_halfinst(context, current2, speed_queue)

        if adler32_sum:
            calculated_sum = adler32(context.target_buffer)
            if parsed_sum != calculated_sum:
                raise objects.ChecksumMissmatch

        total_size = len(context.target_buffer)
        chunk_size = 1024 * 1024
        for i in range(math.ceil(total_size / chunk_size)):
            chunk = context.target_buffer[i * chunk_size : min((i + 1) * chunk_size, total_size)]
            context.target.write(chunk)
            speed_queue.put((len(chunk), 0))
            
        context.target.flush()

        indicator = patch_handle.read(1)
        if not len(indicator):
            win_indicator = None
            continue
        win_indicator = indicator[0]
        win_number += 1


    dst_handle.flush()
    src_handle.close()
    patch_handle.close()
    dst_handle.close()

 
0707010000002A000081A400000000000000000000000166E0651E000005A6000000000000000000000000000000000000002200000000heroic-gogdl-1.1.2/pyproject.toml[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project]
name = "gogdl"
description = "GOG Downloading module for Heroic Games Launcher"
readme = "README.md"
requires-python = ">=3.8"
keywords = ["GOG", "HGL", "Heroic Games Launcher", "Games"]
license = { text = "GPL-3" }
authors = [
  { name = "imLinguin", email = "lidwinpawel@gmail.com" }
]
classifiers = [
  "Development Status :: 5 - Production/Stable",
  "Intended Audience :: Developers",
  "Environment :: Console",
  "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
  "Topic :: Games/Entertainment",
  "Operating System :: OS Independent",
  "Operating System :: POSIX",
  "Operating System :: POSIX :: BSD",
  "Operating System :: POSIX :: Linux",
  "Operating System :: MacOS :: MacOS X",
  "Operating System :: Microsoft :: Windows",
  "Programming Language :: Python :: 3",
  "Programming Language :: Python :: 3.8",
  "Programming Language :: Python :: 3.9",
  "Programming Language :: Python :: 3.10",
  "Programming Language :: Python :: 3 :: Only",
  "Programming Language :: Python :: Implementation :: CPython"
]
dependencies = [
  "setuptools",
  "requests"
]
dynamic = ["version"]

[project.scripts]
gogdl = "gogdl.cli:main"

[project.urls]
Issues = "https://github.com/Heroic-Games-Launcher/heroic-gogdl/issues"

[tool.setuptools.dynamic]
version = {attr = "gogdl.version"}07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!508 blocks
openSUSE Build Service is sponsored by